I’m using MS UnitTesting and trying to find my way around writing my first unit tests. It seems like all my unit tests start off with creating the same few objects…
[TestMethod]
CanCreateOrder()
{
<create an order>
...
}
[TestMethod]
CanSetOrderDeliveryAddress()
{
<create an order>
<create an address>
order.DeliveryAddress = address;
...
}
[TestMethod]
CanDispatchAnOrder()
{
<create an order>
<create an address>
order.DeliveryAddress = address;
order.Dispatch();
...
}
…etc
Is this normal, or have I got the wrong idea? I kind of thought every test was supposed to be independent, but how would it be possible to test Dispatch() without that implicitly relying on CreateOrder and SetDeliveryAddress already passing?
And the second part of the question, if the above approach looks ok, should I be using a factory or something to instantiate these objects in my test project? I’m not sure if a test project should only contain test classes/methods, or it’s ok to add a bunch of helpers in there too.
You seem to be on the right track to me. In a lot of unit tests you will need to set up the state of the object you are testing in order to be able to test a particular part of behaviour.
It will help to group tests in classes when the bahaviour you are testing requires similar setup, and to use [TestInitialize] methods to reduce the duplication of that setup.
eg:
It’s fine to have helper classes in the test project – you should be aiming to make you test code well factored as your production code.