【发布时间】:2015-06-12 10:46:28
【问题描述】:
我有一个使用 Mockito 和 MockMvc 的控制器单元测试。
在一个 POST 请求之后,POSTed 对象被正确解析,但我的存储库模拟没有被触发。
这是模拟代码:
Date mydate = new Date();
Notification not = new Notification();
not.setId(-1L);
not.setUserid("BaBlubb");
not.setTimestamp(mydate);
not.setContent("MyContent");
Notification not2 = new Notification();
not2.setId(1L);
not2.setUserid("BaBlubb");
not2.setTimestamp(mydate);
not2.setContent("MyContent");
when(notificationRepository.save(not)).thenReturn(not2);
所以这真的应该模拟一个对象的保存(设置 ID 并从中生成路由)。
不幸的是,存储库总是返回 null,因此我的代码稍后在尝试从 null 返回新创建的 Route 时失败。
模拟已正确注入并可以为例如字符串比较,或者如果我只检查函数是否被调用,我就是无法让它在对象上触发。
同样的问题发生在
verify(notificationRepository, times(1)).save(not);
它不会触发。
问题是: 1.) 为什么模拟没有触发?我想它不会检查对象中的值是否相等,而是检查对象标识符,因为对象在两者之间是序列化和反序列化的,所以它们是不一样的。
2.) 我怎样才能得到一个通用的模拟?例如每当调用 repository.save() 时,无论参数如何,它总是应该执行特定的方式,例如而不是
when(notificationRepository.save(not)).thenReturn(not2);
我想要
when(notificationRepository.save()).thenReturn(not2);
附:如果出于某种原因您需要其余代码,这里是提交的部分,object 是通知的 json 表示(使用 jackson)
mockMvc.perform(post("/api/notification").content(object)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON));
这里是Controller头,对象反序列化完美,值1:1相同
@RequestMapping(method=RequestMethod.POST)
public ResponseEntity<?> postNotification(@RequestBody Notification n) {
logger.debug("Saving userid "+n.getId());
感谢您的帮助。
【问题讨论】:
-
看看 Matchers:site.mockito.org/mockito/docs/current/org/mockito/Matchers.html 他们可以帮助您在此类调用中匹配某些参数。让我知道它是否对您有所帮助,如果没有帮助,我们如何解决问题。
标签: spring unit-testing mocking mockito mockmvc