1

Just having a conversation with someone in the office about using a business logic class to build up some data in order to test another class.

Basically, he has class A which takes a complex type as a parameter and then generates a collection of a different complex type as a result. He's written tests around this class already. Now he's moved on to testing another class (class B) which takes the result of class A then performs some logic on it.

He's asked the question, "should I use class A to build up a scenario to test class B with".

At first I said yes as class A has tests around it. But then I figured well what if there's some bugs in class A that we haven't found yet... so I guess there must be a better way to address this scenario.

Does anyone have any thoughts on this? Is it OK to use existing logic to save time writing other tests?

Regards,

James

james lewis
  • 2,486
  • 3
  • 24
  • 30
  • I would take the stance that all inputs to a unit test should be predictable and not the output of another method. If that is the case, you cease to be testing a unit of code. – Tomas McGuinness Apr 10 '12 at 15:20

2 Answers2

2

Stances on that might differ. Generally, if code is tested and you assume it works, you're free to use it. This is especially true when using already tested methods to help with testing others (within single class/unit). However, as this happens within single unit it's a bit different from your case.

Now, when dealing with 2 separate classes I'd say you should avoid such approach. Purely for the reason that those two classes might not be related in obvious way or their context/scope of usage might vastly differ. As in, somebody might change class A without even knowing class B exists. Class B tests suddenly break even though no changes were made to B code. This brings unnecessary confusion and is situation you usually don't want to find yourself in.

Instead, I suggest creating helper method within tested class B file. With stubs/fakes and tools like AutoFixture, you should be able to easily reproduce generation logic used by class A and have your own "copy" contained in class B tests.

Community
  • 1
  • 1
k.m
  • 30,794
  • 10
  • 62
  • 86
0

In order to test class B, the result returned from the class A should be replicated somewhere in your test. If class A returns a list of persons, you will have an helper function in your test returning a fake List<Person> to use for your test. Because you are only testing the class B, class A should not be used in your test.

NUnit provides a built in functionality in order to provide data for your tests, have a look to : http://www.nunit.org/index.php?p=testCaseSource&r=2.5

Or you can simply create a DataFactory class with methods that returns the data (simple objects, collections etc..) you will consume in your tests.

Giorgio Minardi
  • 2,765
  • 1
  • 15
  • 11