美文网首页
mockito 技巧合集

mockito 技巧合集

作者: 鸡熟了 | 来源:发表于2019-11-05 15:11 被阅读0次

打桩类的私有变量

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

相关文章

网友评论

      本文标题:mockito 技巧合集

      本文链接:https://www.haomeiwen.com/subject/wlzsbctx.html