【发布时间】:2023-02-22 18:01:58
【问题描述】:
我正在尝试测试一种服务方法。该方法接收信息,使用该信息创建对象。比它保存这个对象。比它返回该对象的 ID。
当我尝试对此进行测试时,我的测试一直失败,并指出返回的对象为空。我想知道如何测试这个。在这 我正在尝试使用返回 1L 的 getId() 来模拟生成的对象。比我让保存方法返回模拟对象。这似乎也行不通。
我真的可以使用一些帮助我应该如何正确地测试这个方法。
示例方法:
public long addNotification(ObjectWithInformation objectWithInformation){
NewObject newObject = // retrieve information based on objectWithInformation
repository.save(newObject);
repository.flush();
return newObject.getId();
}
我目前如何尝试测试(测试编译,getId() 仍然返回 nullvalue):
@Test
void addNotification(){
NewObject newObjectmock = mock(NewObject.class);
Mockito.when(newObjectmock.getId()).thenReturn(1L);
when(repository.save(Mockito.any(NewObject.class))).thenReturn(newObjectmock);
service.addNotification(ObjectWithInformation objectWithInformation);
//verify methods, which I cannot reach due to getId() returning null in the service method.
}
【问题讨论】:
-
您遗漏了示例方法中最重要的部分:
// retrieve information based on objectWithInformation中到底发生了什么??在测试中,您没有将与模拟对象相关的任何内容放入objectWithInformation中,那么您的方法addNotification将如何获得该模拟?它是否使用new运算符创建newObject?
标签: java testing junit mockito