如何用零行代码为接口的默认方法编写junit测试用例

nszi6y05  于 2022-11-11  发布在  其他
关注(0)|答案(2)|浏览(158)

我如何用如下所述的零行代码为接口的默认方法编写一个junit测试用例:

public interface A{
    default void method1(){
    }
}
zz2j4svz

zz2j4svz1#

如果要检查是否调用了该方法,可以使用Mockito的verify()

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

  @Test
  void testMethod() {
    dependent.methodWhereMethod1IsInvoked();
    verify(instanceOfA, atLeastOnce()).method1();
  }
}
r7knjye2

r7knjye22#

您应该单独测试该方法。以下是一些步骤:

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.

下面是一些示例代码:

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

相关问题