EasyMock

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EasyMock相关的知识,希望对你有一定的参考价值。

逻辑类:

 1 @Service
 2 public class Service {
 3 
 4     @Autowired
 5     private AppRemoteService appRemoteService;
 6 
 7     public String get(String userId){
 8         ReturnData returnData = new ReturnData();
 9 
10         String data = appRemoteService.get(userId);
11         if(null == data || 0 == data.length()){
12             return "error";
13         }
14         try {
15             AppData appData = JsonSerialize.deSerialize(data, AppData.class);
16             returnData.setUserId(appData.getUserId());
17         }catch(JsonSyntaxException ex){
18             return "error";
19         }
20 
21         return JsonSerialize.serialize(returnData);
22     }
23 }

Unit Test:

 1 public class ServiceTest {
 2 
 3     @Test
 4     public void TestService(){
 5 
 6         String userId = "599760";
 7         String originData = ...;
 8         String expectData = ...;
 9 
10         AppRemoteService mock = EasyMock.createMock(AppRemoteService.class);
11         EasyMock.expect(mock.get(userId)).andReturn(originData);
12         EasyMock.replay(mock);
13 
14         Service service = new Service();
15         ReflectionTestUtils.setField(service, "appRemoteService", mock);
16 
17         String realData = service.get(userId);
18         Assert.assertEquals(expectData, realData);
19     }
20 }

使用了Spring框架中的ReflectionTestUtils类将mock实例inject到Service类的属性。

 

以上是关于EasyMock的主要内容,如果未能解决你的问题,请参考以下文章

Mockito 比 EasyMock 更受欢迎? [关闭]

使用 EasyMock 测试方法的异常

EasyMock:如何在没有警告的情况下创建泛型类的模拟?

PowerMock、EasyMock 和 Mockito 框架有啥区别? [复制]

模拟无效方法的try catch块并使用EasyMock或Mockito捕获异常

EasyMock vs Mockito:设计 vs 可维护性? [关闭]