7

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);
}
DIF
  • 2,470
  • 6
  • 35
  • 49

1 Answers1

11

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.

k.m
  • 30,794
  • 10
  • 62
  • 86
  • 3
    Absolutely... if all combinations of testing isInFruitsList are good, and they are the author of that code, then it should be reliable for other testing... Just like we "rely" on C# and NUnit... – DRapp Jan 26 '12 at 13:14
  • 2
    That's right. You always need to find the balance between writing too few/too general tests and diving into testing whether `int a = 5` actually assigns value. It's always more sane to assume CLR, 3rd party code and your tested code works, than going paranoid and testing everything that moves. – k.m Jan 26 '12 at 13:44
  • Thank you both! I do feel a lot safer now, knowing that it is "allowed" to rely on own tests. – DIF Jan 26 '12 at 13:50