mockito 技巧合集

打桩类的私有变量

ReflectionTestUtils.setField(xxxService, "field", "value");

在@InjectMocks对象的fields里面,使用@InjectMocks对象

// AService.java
public class AService {
    @Autowired
    private BSerivce bSerivce;
    @Autowired
    private CService cSerivce;
}
// Test.java
...
public class Test {
    @Mock
    private BSerivce bSerivce;
    @InjectMocks
    ASerivce aSerivce = new AService();
    @InjectMocks
    CService cService = new CService();
    @Before
    public void before() {
        ReflectionTestUtils.setField(AService, "cService", cService);
    }
   // do test
}

Method method = XXXClass.class.getDeclaredMethod("methodName", Param.class);
method.setAccessible(true);
Object result = method.invoke(XXXClassInstance, param);

使用PowerMock@spy可以打桩私有方法
个人体会:在@spy对象里面打桩私有方法没什么实际用处,原因见下一条

@RunWith(PowerMockRunner.class)
@PrepareForTest(XXService.class)
@PowerMockIgnore(value = {"javax.net.ssl.*", "javax.management.*"})
public class XXServiceTest {
// ...
@Test
public void test(){
    XXSerivce spy = PowerMockito.spy(new XXSerivce());
    when(spy, method(XXSerivce.class, "dosomething", Param1.class, Param2.class))
                   .withArguments(any(), any())
                    .thenReturn(new Object());
  }
}

起因:测试InjectMocks的Service的A方法,A方法调用了一个逻辑复杂的private B方法,想直接打桩这个方法。
调查结果:无法在InjectMocks对象里面打桩私有方法
https://www.baeldung.com/mockito-annotations

测试方法抛出的异常

 try {
            this.XXService.doSomething(param, Lists.newArrayList());
            fail();
        } catch (Exception e) {
            Assert.assertEquals(expect, actual);
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容