mockito 技巧合集

2019-11-05  本文已影响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);
        }
上一篇 下一篇

猜你喜欢

热点阅读