【发布时间】:2021-03-13 11:02:51
【问题描述】:
我在从控制器中测试(模拟方法的值)我的删除方法时遇到问题。在普通模式下它可以正常工作,但在我测试时却不行。
这是我的代码。
我的控制器
@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);
}
我的帖子道
@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)。为什么以及如何解决这个问题?
【问题讨论】:
-
您刚刚创建了服务的本地模拟,但您的控制器不会自动使用它。您需要以某种方式注入模拟。
-
但是我不知道怎么做;(
标签: java spring spring-boot testing mocking