Home > Net >  Can a unit test use more than one method of the class being tested?
Can a unit test use more than one method of the class being tested?

Time:11-29

Consider you implemented a Stack data structure and you are writing a test for the push and peek operations.

@Test
fun `push an element in the stack`() {
    stack.push("A")
    stack.push("B")
    assertEquals("B", stack.peek())
}

@Test
fun `peek from an non empty stack`() {
    stack.push("A")
    stack.push("B")
    stack.push("C")
    assertEquals("C", stack.peek())
}

The test for the push operation requires to also peek from the stack to make the assertion, and similarly the test for the peek operation requires to push into the stack to peek from.

Let's say for the push test case, if the test fails how one can know if the push method failed or the peek method.

So, is it a bad practice to use more than one method in a single unit test from the test class.

CodePudding user response:

is it a bad practice to use more than one method in a single unit test from the test class

It is really NOT a bad practice. People too often believe that they should write unit tests for each method of the class, but that is really not the case.

Unit tests are here to test the behaviors of your class against expected behaviors. This may very well require several method calls for a proper setup and assertions.

Even in the simplest cases, it is quite common to use some method to setup some state, and then use another one to query the state. Your example is a very good one, you need to push some data, and then query it. Nothing wrong in that.

I think the conceptual problem in your current test design is apparent in the naming of your tests. Both of your tests are actually testing the same behaviour: peek on non-empty stack should return the last pushed element. You can't (and shouldn't) have one test for push and one test for peek. Instead, you can only test how they interact with each other.

Conversely, a single method can be used in many unit tests, to test different cases (in particular, edge cases). So it's also ok to use push and peek in multiple unit tests.

if the test fails how one can know if the push method failed or the peek method

The test failure is not supposed to tell you which exact piece of code is broken, it's supposed to tell you what behavior doesn't respect the specifications (anymore). It's the developer's job to investigate where the bug is (if it's not obvious). Usually if you have nice focused tests (which doesn't mean single-method tests), it's really not that hard to find where things went wrong. If you struggle, you can use a debugger to help you check intermediate states at different points in time.

  • Related