1

Let's say I have a simple data-structure Store with two methods: add and list_all (Example in python):

class Store:
    def __init__(self):
        self.data = []
    def add(self, item):
        self.data.append(item)
    def list_all(self):
        return list(self.data)

Testing its methods would look something like:

def test_add():
    store = Store()
    store.add("item1")
    items = store.list_all() 
    assert len(items) == 1
    assert items[0] == "item1"

def test_list_all():
    store = Store()
    store.add("item1")
    items = store.list_all() 
    assert len(items) == 1
    assert items[0] == "item1"

Well these tests are awkward, they have literally the same body. To test the list_all method, I have to assume that add already works correctly, and to test add I have to use list_all to check the state of the Store. How do you test these kind of methods? Do you just write a single test case and say "this proves that both methods work fine"?

PS: It's a theoretical question. I am working on testing a complex system, and couldn't find where to start a bottom-up approach, because of such problems.

Tamas Hegedus
  • 28,755
  • 12
  • 63
  • 97

1 Answers1

2

You should never test a method by calling another method. The purpose of the test_add and test_list_all methods should be to perform a Unit Test, which means, to check the correctness of a single unit of software (in this example, a single method).

So you should find a different way to test the validity of your methods. Ideally, Unit Tests should be as simple as possible, use direct statements, and not rely on external methods (which can be subject to change).

Then you can also write an Integration Test, where you call different methods and check if they work well with each other.

lukas84
  • 428
  • 3
  • 16
  • So you say I cannot unit-test this small class, only integration test? Or can I call this test a unit-test that actually tests the whole class, not just a method? – Tamas Hegedus Jan 25 '17 at 10:41
  • @TamasHegedus You can decide that the entire class is the unit, and test it as a whole. But ideally, the unit should be the smallest testable part of the application; so that, if the test fails, you know exactly where to look for the error. – lukas84 Jan 25 '17 at 10:56