Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good way of unit testing to use another, tested function to make preparations for the actual test?

I'm trying to get into unit testing with NUnit. At the moment, I'm writing a simple test to get used to the syntax and the way of unit testing. But I'm not sure if I'm doing it right with the following test:

The class under test holds a list of strings containing fruit names, where new fruit names can be added via class_under_test.addNewFruit(...). So, to test the functionality of addNewFruit(...), I first use the method to add a new string to the list (e.g. "Pinapple") and, in the next step, verify if the list contains this new string.

I'm not sure if this is a good way to test the functionality of the method, because I rely on the response of another function (which I have already tested in a previous unit test).

Is this the way to test this function, or are there better solutions?

public void addNewFruit_validNewFruitName_ReturnsFalse()
{
    //arrange
    string newFruit = "Pineapple";

    //act
    class_under_test.addNewFruit(newFruit);
    bool result = class_under_test.isInFruitList(newFruit);

    //assert
    Assert.That(!result);
}
like image 319
DIF Avatar asked Jan 26 '12 12:01

DIF


1 Answers

In a perfect world, every unit test can only be broken in single way. Every unit test "lives" in isolation to every other. Your addNewFruit test can be broken by breaking isInFruitsList - but luckily, this isn't a perfect world either.

Since you already tested isInFruitsList method, you shouldn't worry about that. That's like using 3rd party API - it (usually) is tested, and you assume it works. In your case, you assume isInFruitsList works because, well - you tested it.

Going around the "broken in a single way" you could try to expose underlying fruits list internally (and use InternalsVisibleTo attribute), or passing it via dependency injection. Question is - is it worth the effort? What do you really gain? In such simple case, you usually gain very little and overhead of introducing such constructs usually is not worth the time.

like image 101
k.m Avatar answered Oct 21 '22 11:10

k.m