-1

In my domain layer I create a lot of classes which looks like this

public class Route
{
    public Route(Location origin, Location destination)
    {
        this.Origin = origin;
        this.Destination = destination;
    }
    public Location Origin { get; }
    public Location Destination { get; }
}

Now I need to unit-test this constructor

[Test]
public void PropertiesAreAssigned()
{
    var origin = new Location(...);
    var destination = new Location(...);
    var route = new Route(origin, destination);
    route.Origin.Should().Be(origin);
    route.Destination.Should().Be(destination);
}

I have quite a few of those classes and tests which are very similar to each other. What I'd like is to have some kind of method which just accepts the type arguments, and then does all the testing for me, i.e.

  • instantiate a variable per constructor parameter (with whole graph of dependencies needed)
  • pass these variables to constructor
  • checks that the property values are assigned correctly

I'm pretty sure I can do this with a bit of reflection, but maybe is there an existing library for doing that? More tests are welcome, e.g.

  • Testing the null argument throws the proper exception
  • Testing that Equals and GetHashCode are implemented correctly
Mikhail Shilkov
  • 34,128
  • 3
  • 68
  • 107

1 Answers1

0

For me testing a simple constructor, simple accessors and mutators are a bad practice... It will be covered with behavioral (with intention) test. The less you test implementation details, the more your tests will be robust and resist to changes.

Testing constructor with complex behavior can be useful. But I often try to don't have any complex behavior in my constructors ^^

rad
  • 1,857
  • 1
  • 20
  • 30
  • How do you TDD them? I saw bugs in constructors of this kind, so why not test them if it's easy (that's what I'm trying to achieve here). – Mikhail Shilkov Dec 11 '15 at 16:21
  • If you work in TDD, you should only write the constructor needed by your test, any field or object should be created directly for the needs of a behavior – rad Dec 11 '15 at 16:27
  • You can found more answers in this thread http://stackoverflow.com/questions/357929/is-it-important-to-unit-test-a-constructor – rad Dec 11 '15 at 17:03