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



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

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

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

@ExtendWith(MockitoExtension.java)
class Test {
@Mock
A instanceOfA;
@InjectMocks
ClassWithInjectedA dependent;
@Test
void testMethod() {
dependent.methodWhereMethod1IsInvoked();
verify(instanceOfA, atLeastOnce()).method1();
}
}

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

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

相关内容

  • 没有找到相关文章

最新更新