Theodore
Theodore

Reputation: 67

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

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(){
    }
}

Upvotes: 0

Views: 1136

Answers (2)

DwB
DwB

Reputation: 38320

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");
    }
}

Upvotes: 0

Sergey Tsypanov
Sergey Tsypanov

Reputation: 4410

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();
  }
}

Upvotes: 1

Related Questions