Question

I am new to C# and Unit testing and I have been trying to implement tests for the following constructor:

public Stepup()
{
    InitializeComponent();
}

Stepup is a partial class and inherits an Interface. How does one implement unit test for such a constructor? Also in addition to that, what are some ways to unit test a simple constructor with no parameters?

Was it helpful?

Solution

When a constructor runs, certain invariants about the constructed object should be true. You need to specify what those invariants are, and then test that they are true when the constructor finishes executing. The main point here is that you do not test in the internal implementation details of the constructor, only that whatever your specification says is true about the constructed objects is actually true.

For example:

class Circle {
    private readonly double radius;
    public double Radius { 
        get { 
            Contract.Ensures(Contract.Result<double>() >= 0));             
            return this.radius;
        }
    }

    public Circle(double radius) { 
        Contract.Requires(radius >= 0);
        this.radius = radius; 
    }
}

Here, the invariant after the constructor finishes is that Circle.Radius returns the value for the constructor parameter radius that was passed in. This is the specification, and it can be tested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top