关于Mock Answer
上一篇文章,有介绍过关于Arguments Matche的使用,其实 Answer的作用与其比较类似,但是它比 Arguments Matcher 更加强大。
Arguments Matche
即传入不同的参数,返回不同的结果,重在入参的判断,在入参重写方法去判断
Answer
见名知意,即返回不同的结果,但是根据传入参数去判断,在返回处重写方法去判断,返回结果
模拟场景
根据学生名字查找邮箱,controller调service层
service层
具体代码示例如下:
package com.rongrong.powermock.answers;
/**
* @author rongrong
* @version 1.0
* @description:
* @date 2019/12/4 20:24
*/
public class StudentAnswerService {
public String getEmail(String userName){
throw new UnsupportedOperationException();
}
}
controller层
具体代码示例如下:
package com.rongrong.powermock.answers;
/**
* @author rongrong
* @version 1.0
* @description:
* @date 2019/12/4 20:24
*/
public class StudentController {
public String getEmail(String userName) {
StudentAnswerService studentAnswerService = new StudentAnswerService();
return studentAnswerService.getEmail(userName);
}
}
上面的代码的业务代码比较简单了,下面再来进行测试
具体示例代码如下:
package com.rongrong.powermock.answers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.fail;
/**
* @author rongrong
* @version 1.0
* @description:
* @date 2019/12/4 20:34
*/
@RunWith(PowerMockRunner.class)
//准备调用层的类
@PrepareForTest(StudentController.class)
public class TestStudentAnswerService {
@Test
public void testStudentAnswerService() {
StudentAnswerService studentAnswerService = PowerMockito.mock(StudentAnswerService.class);
PowerMockito.when(studentAnswerService.getEmail(Mockito.anyString())).then(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
String arg = (String) invocation.getArguments()[0];
if ("rr".equals(arg)) {
return "rongrong@qq.com";
} else if ("jqj".equals(arg)) {
return "jiuqujian@qq.com";
}
throw new NullPointerException();
}
});
try {
PowerMockito.whenNew(StudentAnswerService.class).withAnyArguments().thenReturn(studentAnswerService);
StudentController studentController = new StudentController();
String email = studentController.getEmail("rr");
assertEquals("rongrong@qq.com",email);
email = studentController.getEmail("jqj");
assertEquals("jiuqujian@qq.com",email);
email = studentController.getEmail("tony");
assertEquals("jiuqujian@qq.com",email);
} catch (Exception e) {
e.printStackTrace();
}
}
}
answer 接口中参数 InvocationOnMock使用
invocation.getArguments();(1)
invocation.callRealMethod();(2)
invocation.getMethod();(3)
invocation.getMock();(4)
(1)获取 mock 方法中传递的入参
(2)获取是那个真实的方法调用了该 mock 接口
(3)获取是那么 mock 方法被调用了
(4)获取被 mock 之后的对象
到此,关于mock中 Answer的使用介绍完,有兴趣的同学可以自己从上到下自己敲一遍。