0

I have a single method which is really comprehensive. Within this method couple of other methods are called and each method depends on the previous one.

My question is: What is the best approach to test this complex method using JUnit?

Can I just create one single @Test Method and calling the other methods within this method? For example:

@Test
public void testRun(){
    testMethod1();
    testMethod2();
    ...
}

testMethod1(){
assertNotEquals();
...
}

I can´t believe that it is that easy. Wouldn´t it be better to test each method on their own? But how can I implement that? Are their any best practises?

But maybe this is the right way.

Thanks for any suggestions !:)

Jannik
  • 90
  • 10
  • What makes you think you cannot test each method on their own? It should be possible to set a certain state before and check the outcome after it. – Rob Audenaerde Nov 16 '17 at 08:01
  • 1
    Your methods should not be too complex. Keep your methods [as short as possible](https://softwareengineering.stackexchange.com/a/146274/32666). Then it will be easier to test them and maintain your codebase. –  Nov 16 '17 at 08:01
  • 1
    I guess they are private. But yes, when you are having difficoulties writing a test, then it's a singal that the code might not be high quality – Pijotrek Nov 16 '17 at 08:02
  • First of all you should ask yourself why it is so complex, and if you can split it. Then, usually the "other methods" are private, so you cannot test them directly. If you can, for sure you should. – marco Nov 16 '17 at 08:03
  • @RobAu: But for example my first method initialises a variable and the second method uses this variable. How can I set a certain state therefore? Without method 1 I do not know how this value could be? – Jannik Nov 16 '17 at 08:05
  • The methods are short as possible but they depend on each other. In a test case I could declare them as public that might not be a problem but I will rethink it! Thanks :) That sound like it is possible.. – Jannik Nov 16 '17 at 08:10
  • 1
    It shouldn't matter if your method is complex, or invokes lots of other methods internally: test the return value and/or relevant side effects of invoking it. – Andy Turner Nov 16 '17 at 08:24
  • @AndyTurner: That is a great hint! So if there are some private methods I can test if there return statements are as expected. So I do not need to test the private method directly! Thanks – Jannik Nov 16 '17 at 08:30

1 Answers1

1

You have to refactor the comprehensive method first.

You've implied that the inner methods depend on each-other. That ussually means they share and update the same 'state'.

Try to extract this state into an object, and use this object as a parameter of each inner method.

This will allow you to test the inner methods seperately.

Tom Van Rossom
  • 1,440
  • 10
  • 18