由于spring boot团队使用Mockito作为mock库,所以果断弃了Jmockit, 关于Jmockito的简单使用可以参考
Jmockit Mocking库初体验
本文由javacoder.cn整理,转载注明处理
待测对象和Jmockit Mocking库初体验中的一样
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class ClassUnderTest { private DependencyAbc abc; public void doSomething() { int n = abc.intReturningMethod(); if (n == 0) { System.out.println("from ClassUnderTest.doSomething, n = 0"); return; } for (int i = 0; i < n; i++) { String s = abc.stringReturningMethod("xyz" + i); System.out.println("in ClassUnderTest.doSomething() s=" + s); } } public static String staticMethod(String str) { return str + "staticMethod"; } public void print() { System.out.println("from concrete"); } public static interface DependencyAbc { public int intReturningMethod(); public String stringReturningMethod(String p1); } } |
增加了print()方法便于测试spy partial mocking功能
测试类改动如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
public class MockitoTest { final String msg = "i'm exception"; @InjectMocks private ClassUnderTest cut; @Mock private ClassUnderTest.DependencyAbc abc; AutoCloseable autoCloseable; MockedStatic mockedStatic; @BeforeEach public void before() { autoCloseable = MockitoAnnotations.openMocks(this); mockedStatic = mockStatic(ClassUnderTest.class); } @AfterEach public void teardown() throws Exception { autoCloseable.close(); mockedStatic.close(); } @Test public void test() { //when() verify都是Mockito类的静态方法 when(abc.intReturningMethod()).thenReturn(3); when(abc.stringReturningMethod(anyString())) .thenReturn("javacoder.cn", "helloWorld") .thenThrow(new RuntimeException(msg)); String retMsg = null; try { cut.doSomething(); } catch (Exception e) { retMsg = e.getMessage(); } Assertions.assertEquals(msg, retMsg); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); verify(abc, atLeastOnce()).stringReturningMethod(argument.capture()); Assertions.assertEquals("xyz2", argument.getValue()); } @Test public void testSpy() { ClassUnderTest _cut = spy(cut); doAnswer(invocation-> { System.out.println("-------from spy"); return null; }).when(_cut).print(); _cut.doSomething(); _cut.print(); } @Test public void testStaticMethod() { //需要导入org.mockito:mockito-inline 依赖 mockedStatic.when(()->ClassUnderTest.staticMethod(anyString())).thenReturn("mocked"); String str = ClassUnderTest.staticMethod("hello"); Assertions.assertEquals(str, "mocked"); } } |
@InjectMocks 标识需要依赖注入的类
@Mock 标识需要生成mock的类或者接口
触发对注解的处理有三种方式
1)
MockitoAnnotations.openMocks(this);
2)when(abc.intReturningMethod()).thenReturn(3);
表示录入一个期望(Expectation), 当调用intReturningMethod()
时返回3
spy(cut);
为了生成partial mocking, 录入期望(Expectation)的格式有点不一样。详细的见testSpy()
中的doAnswer(Answer).when(_cut).print();
语句
Posted in: java基础
Comments are closed.