I have coded a constructor for a class and I am testing for each parameter being null. See example below:
public MyClass(IObjectA objA, IObjectB objB) : IMyClass
{
if (objA == null)
{
throw new ArgumentNullException("objA");
}
if (objB == null)
{
throw new ArgumentNullException("objB");
}
...
}
Usually I unit test (using Moq) this by mocking out IObjectA
and IObjectB
and passing them in. The example above would create 2 unit tests to test each scenario.
The problem I have is when a 3rd parameter is passed into the constructor. It requires that I alter my previous tests, as I suddenly get a "No constructor for MyClass has 2 parameters" type exception.
I also use AutoMockContainer. Essentially I'd like to be able to test the constructor by registering a null object in the container. For example:
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructionThrowsExceptionForNullObjA()
{
// Arrange.
var container = new AutoMockContainer(new MockRepository(MockBehavior.Default));
container.Register<IObjectA>(null);
// Act.
var sut = container.Create<MyClass>();
}
Then it doesn't matter how many new parameters are added to the constructor. I will not have to update my unit tests.
Sadly, the above unit test passes. But for the wrong reason. The Register<T>()
method throws the ArgumentNullException
not the code executed in the 'Act' section.
Does anyone have a suggestion for being able to test constructor parameters and not have to revisit the unit test when new parameters are later added?