Unit testing factory methods which have a concrete class as a return type

factory, tdd, unit-testing

Solution

Often, there's nothing wrong with creating public properties that can be used for state-based testing. Yes: It's code you created to enable a test scenario, but does it hurt your API? Is it conceivable that other clients would find the same property useful later on?

There's a fine line between test-specific code and Test-Driven Design. We shouldn't introduce code that has no other potential than to satisfy a testing requirement, but it's quite alright to introduce new code that follow generally accepted design principles. We let the testing drive our design - that's why we call it TDD :)

Adding one or more properties to a class to give the user a better possibility of inspecting that class is, in my opinion, often a reasonable thing to do, so I don't think you should dismiss introducing such properties.

Apart from that, I second nader's answer :)

Problem

So I have a factory class and I'm trying to work out what the unit tests should do. From this question I could verify that the interface returned is of a particular concrete type that I would expect. What should I check for if the factory is returning concrete types (because there is no need - at the moment - for interfaces to be used)? Currently I'm doing something like the following: ``` [Test] public void CreateSomeClassWithDependencies() { // m_factory is instantiated in the SetUp method var someClass = m_factory.CreateSomeClassWithDependencies(); Assert.IsNotNull(someClass); } ``` The problem with this is that the `Assert.IsNotNull` seems somewhat redundant. Also, my factory method might be setting up the dependencies of that particular class like so: ``` public SomeClass CreateSomeClassWithDependencies() { return new SomeClass(CreateADependency(), CreateAnotherDependency(), CreateAThirdDependency()); } ``` And I want to make sure that my factory method sets up all these dependencies correctly. Is there no other way to do this then to make those dependencies `public/internal` properties which I then check for in the unit test? (I'm not a big fan of modifying the test subjects to suit the testing) Edit: In response to Robert Harvey's question, I'm using NUnit as my unit testing framework (but I wouldn't have thought that it would make too much of a difference)

Original source

Related problems