以下为springboot项目中对public以及private方法的junit测试的方法总结:
1.单独对public方法的测试:
@Runwith(mockitoJunitRunner.class)
@springBootTest
public class xxx{
@spy
@InjectMocks
XXXXXservice xxxservice;
@mock
测试类中的调用类
@Test
public void test1(){
//无返回值的方法
Mockito.doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return "called with arguments: " + args;
}
}).when(对象).方法名();
//有返回值
when (对象.方法 (参数)).thenReturn (方法的返回值);
}
}
2.单独对private(protected方法也可)方法的测试:
@Runwith(springRunner.class)
@springBootTest
public class xxx{
@InjectMocks
XXXXXservice xxxservice;
@mock
测试类中的调用类
@Test
public void test1(){
Sample sample = new Sample();
Method method = Sample.class.getDeclaredMethod("方法名", int.class, 引数型2...);
method.setAccessible(true);
int n = 2;
int actual = (戻り値の型)method.invoke(xxxservice,2,引数2...);
}
}
3.对public方法中调用的private以及public方法进行Mock的:
@Runwith(springRunner.class)
@springBootTest
public class xxx{
@AutoWired
XXXXXservice xxxservice;
@Test
public void test1(){
new MockUp<测试类> {
@mock
private String XXX(){
return "";
}
@mock
public String xxx(){
return "";
}
@mock
public Int xxx(){
return x;
}
}.getInstance()
AssertEqual(xxx, xxxservice.XXX());
//防止被mock的方法再被调用的时候出现干扰
Mockup.teardown();
}
4.prameter的Mock方法:
①泛型类作为参数时,举例:User.java,Mockito.any(User.class)即可;
②string作为参数时,Mockito.anyString()可;
③NULL作为参数时,Mockito.any()可(Mockito.any()或许也可用于其他的很多类型参数);
④int和Integer类,Mockito.anyInt(); Mockito.any(int.class) ?
以上均是回忆的内容,可能出现偏差,实际为主。