0

How can I write a junit test case for default methods of interface with zero lines of code as mentioned below :

public interface A{
    default void method1(){
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Theodore
  • 57
  • 1
  • 7
  • 2
    seeing as there is nothing to test ... not really? – Stultuske Sep 23 '22 at 07:05
  • 2
    It's pretty hard to test if nothing really did nothing at all. You would have to make sure **everything** has **not** changed… – deHaar Sep 23 '22 at 07:13
  • 1
    Pro tip: when asking questions, try to avoid "Can anyone help me" or "Who can help me". The task is yours to do, and it helps enormously if you can indicate you are not giving the work to volunteers on the internet. Even when you get assistance here, make it clear to readers (and yourself!) that you expect to do most of it. – halfer Sep 23 '22 at 18:09

2 Answers2

1

If you want to check whether the method was called you could use Mockito's verify():

@ExtendWith(MockitoExtension.java)
class Test {
  @Mock
  A instanceOfA;
  @InjectMocks
  ClassWithInjectedA dependent;

  @Test
  void testMethod() {
    dependent.methodWhereMethod1IsInvoked();
    verify(instanceOfA, atLeastOnce()).method1();
  }
}
Sergey Tsypanov
  • 3,265
  • 3
  • 8
  • 34
0

You should test the method in isolation. Here are some steps:

1. Create a JUnit test.
2a. Create a spy of the interface or
2b. Create a nested class that implements the interface and create a spy of that class.
3. test the method.
4. verify that the method was called, however makes sense.

Here is some sample code:

public interface Blam
{
    default void kapow()
    {
        System.out.println("kapow");
    }
}

@ExtendWith(MockitoExtension.class)
public class TestBlam
{
    public static class BlamForTest implements Blam
    {
    }

    @Spy
    private Blam classToTest;

    @Spy
    private BlamForTest classToTestToo;

    private PrintStream livePrintStream;

    @Mock
    private PrintStream mockPrintStream;

    @AfterEach
    void afterEach()
    {
        System.setOut(livePrintStream);
    }

    @BeforeEach
    void beforeEach()
    {
        livePrintStream = System.out;

        System.setOut(mockPrintStream);
    }

    @Test
    void kappw_useVerifyOfTheEffectOfCallingTheMethod_success()
    {
        classToTest.kapow();


        verify(mockPrintStream).println("kapow");
    }

    @Test
    void kapow_useTheNextedClass_success()
    {
        classToTestToo.kapow();


        verify(mockPrintStream).println("kapow");
    }
}

DwB
  • 37,124
  • 11
  • 56
  • 82