Is my way of reusing methods in JUnit tests bad?

666 views Asked by At

Lets say I have a JUnit class called Test.class. Test.class has around 50 JUnit tests and on 30 JUnit tests, this line of code always appears:

Note: I'm using Mockito/PowerMock

when(ConnectionHandler().getConnection()).thenReturn(connection);

I'm planning to create a utility class called TestUtils.class and create a private method for the line above like:

public static stubConnection(Connection connection) {
    when(ConnectionHandler().getConnection()).thenReturn(connection);
}

So instead of writing down when(ConnectionHandler().getConnection()).thenReturn(connection); every time, I could just go for TestUtils.stubConnection(connection);

Is this advised? I just see a lot of repetitive code in my JUnit tests. If it helps, I'm testing really a class that has very low cohesion and is very tightly coupled.

1

There are 1 answers

3
StuPointerException On BEST ANSWER

Is this advised? I just see a lot of repetitive code in my JUnit tests.

Absolutely. The fact that this is a unit test is (almost) not relevant, it's still code that you or someone else has to maintain. Encapsulating it into a util or service class is definitely a step in the right direction.