Java Mockito 无法模拟方法的结果

标签 java spring spring-boot testing mocking

我在测试(模拟方法的值) Controller 中的删除方法时遇到问题。在普通模式下它工作正常,但在我测试时却不行。

这是我的代码。

我的 Controller

@RestController
@RequestMapping("/")
public class MainController {

    @DeleteMapping(value = "/deletePost/{id}")
public ResponseEntity<String> deletePost(@PathVariable int id) throws SQLException {
    boolean isRemoved = postsService.deletePost(connection, id);

    if (!isRemoved)
        return new ResponseEntity<>("Post with given id was not found", HttpStatus.NOT_FOUND);
    else {
        modifiedPostsService.insertModificationData(connection, new ModificationData(id, "deletion"));
        return new ResponseEntity<>("Post with given id has been deleted.", HttpStatus.OK);
    }
}
}

我的帖子服务

    public boolean deletePost(Connection connection, int id) throws SQLException {
    return postsDao.deletePost(connection, id);
}

我的帖子Dao

    @Override
public boolean deletePost(Connection connection, int id) throws SQLException {
    boolean isPostExists = isPostExist(connection, id);
    PreparedStatement ps;
    ps = connection.prepareStatement("delete from POSTS where ID = " + id);
    ps.executeUpdate();
    return isPostExists;
}

最后是我的测试

@WebMvcTest(MainController.class)
class MainControllerTests {

@Autowired
private MockMvc mockMvc;

@MockBean
private Connection connection;

@MockBean
private PostsService mockPostsService;

@Test
void testIfDeletePostUrlIsOk() throws Exception {
    Mockito.when(mockPostsService.deletePost(connection, 1)).thenReturn(true);
    mockMvc.perform(MockMvcRequestBuilders
            .delete("/deletePost/1")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}

}

testIfDeletePostUrlIsOk() 返回 404 而不是 200 (我猜模拟值 - true 不起作用,而是 false)。为什么以及如何解决这个问题?

最佳答案

@SpringBootTest
@AutoConfigureMockMvc
public class TestingWebApplicationTest {

 @Autowired
 private MockMvc mockMvc;

 @MockBean     
 Connection mockConnection;

 @MockBean
 PostsService mockPostsService;

 @Test
 void testIfDeletePostUrlIsOk() throws Exception {
 Mockito.when(mockPostsService.deletePost(any(), anyInt())).thenReturn(true);
 mockMvc.perform(MockMvcRequestBuilders
        .delete("/deletePost/1")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());
 }
}

您需要将模拟注入(inject) Controller ,注释@SpringBootTest和@MockBean将完成这项工作

关于Java Mockito 无法模拟方法的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66612694/

相关文章:

java - Gson 无法使用自定义序列化程序进行反序列化

java - EmailValidator GetInstance本地吗?

java - Android 工具栏项目 OnClickListener

javascript - Chrome 中 ajax Restful ws 调用期间访问 CORS

java - 在 Spring Security 中获取用户请求的 url

java - 从缓存中删除 log4j 1.2.12

java - 为什么 ArrayList.set() 留下一个方法没有任何异常?

spring - 谁能比较 Google Guice 和 Spring DI?

java - 使用 spring boot 实现 2 路 SSL

gradle - Gradle构建Spring Boot应用程序与有效配置文件进行 war