Java 模拟存储库调用的返回实体返回null
代码段根据参数检索实体Java 模拟存储库调用的返回实体返回null,java,spring-boot,spring-data-jpa,mockito,mockmvc,Java,Spring Boot,Spring Data Jpa,Mockito,Mockmvc,代码段根据参数检索实体 public void updateNotification(String status, Entity entity ) { Entity entity1 = null; try { switch (status) { case "AX": entity1 = this.Repository.findByTypeAndParams(
public void updateNotification(String status, Entity entity ) {
Entity entity1 = null;
try {
switch (status) {
case "AX":
entity1 = this.Repository.findByTypeAndParams(
1, entity.getParam1(), entity.getParam2(),
entity.getParam3());
if (entity1!= null) {
entity1.setCurrentStatusKey("SET");
updateEntity(entity1);
} else {
LOGGER.debug("");
}
break;
上述代码的测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
public class ServiceTest {
@InjectMocks
CVService cVServiceMock;
@Mock
RepositoryMock repositoryMock;
@Test
public void testUpdateOut() {
Entity entity1 = new Entity ();
entity1.setType(2);
Mockito.when(repositoryMock.findByTypeAndParams(any(Integer.class), any(String.class),
any(String.class), any(String.class))).thenReturn(entity1);
cVServiceMock.updateNotification("AX", entity1);
}
从测试用例执行时,entity1始终为null,而不是模拟实体,
我做错了什么?正如另一篇文章所说:
在Mockito上使用
[……]
更多信息:
存储库的一个实例了:
// In your test method
PowerMockito.mockStatic(Repository.class);
不要忘记向测试类添加注释:
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class) // Since you are using SpringBoot
@PrepareForTest(Repository.class)
@PowerMockIgnore({"javax.management.*", "javax.net.ssl.*", "javax.security.*"}) // Avoid certain classloading related issues, not mandatory
在我的示例中,Mockito.when()
替换为PowerMockito.doReturn(…).when(…)
。它可能如下所示:
@Test
public void testUpdateOut() {
Entity entity1 = new Entity ();
entity1.setType(2);
PowerMockito.mockStatic(Repository.class);
PowerMockito.doReturn(entity1).when(
Repository.class,
"findByTypeAndParams", // The name of the method
Mockito.anyInt(), // The arguments
Mockito.anyString(),
Mockito.anyString(),
Mockito.anyString()
);
// Your test
notificationServiceMock.updateNotification("AX", entity1);
// And at the end of the test:
PowerMockito.verifyStatic(); // It will verify that all statics were called one time
}
请注意,我将您的any(Integer.class)
和any(String.class)
分别替换为anyInt()
和anyString()
我希望这会有帮助 考虑添加一个或至少一个完整的测试(包括mock创建和其他注释)以及被测试类的相关部分(方法签名、相关字段、构造函数)。您能说明notificationServiceMock是如何初始化的吗?最好粘贴所有服务和测试类。同时请说明如何创建RepositoryMock
。我认为Repository.findByTypeAndParams
不是静态方法。只是OP没有使用Java约定来命名他的字段。@其次,也许你是对的,在这种情况下,mockStatic()
和verifyStatic()
是无用的。我等他的回答。