我在测试(模拟方法的值) 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/