Insights and outlooks on software development

S'true

Having NUnit executing the same tests on two ways to create objects

Monday, February 11, 2008 by Thomas L

Let's say that you have two different ways of creating an object, let it be e.g. deserializing the instance from an xml blob and creating it manually, and you'd like to make sure that the instance has the same state and behaviour either way it's created. How to solve that? Since NUnit reads the tests to execute via reflection, we have to in some way make sure that the instances are created individually and the same test code (not a copy-pasted test fixture, that is) is run. For this problem I give the following suggestion

public class DualOrderCreationBase { [Test] public void ShouldBeInCreatedStateBeforeSave() { /* test code here */ } // More test methods here. // Note that all tests are run by NUnit both after // creation using default ctor and xmlblob. } [TestFixture] public class HavingOrderCreatedViaDefaultConstructor : DualOrderCreationBase { [SetUp] public void SetUp() { /*create order using default ctor*/} } [TestFixture] public class HavingOrderCreatedViaXmlBlob : DualOrderCreationBase { [SetUp] public void SetUp() { /*create order using xmlblob*/} }

Note here, that the two classes below inherit from the DualOrderCreationBase, which in fact contains all of the actual test methods. When NUnit reads the DualOrderCreationBase, it's not marked with the TestFixture attribute, which makes NUnit skip it. But the two classes that inherit from the DualOrderCreationBase will inherit all of the test methods together with the Test attribute, which means that we are executing the same tests for objects instantiated in two different ways, just as we wanted!

Regarding project organization, it seems as if having all of the three classes in their own file is quite nice. This organization more or less means that the file encapsulates a specific behaviour of the domain object.

Technorati tags: ,,

Filed under having  

0 kommentarer: