所以我在 Spring Boot 中进行了第一次测试,但遇到了一个问题。当我执行我的测试时,这些值实际上被删除了。我更愿意模拟这个,这样这些值就不会被删除。
我的测试班: @SpringBootTest @AutoConfigureMockMvc
公共类 PartyEndpointTest {
@Autowired
private MockMvc mockMvc;
@Test
@DisplayName("Should Not give access to endpoint")
public void ShouldNotGiveAccess() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/parties"))
.andExpect(MockMvcResultMatchers.status().is(401));
}
@Test
@WithMockUser("JLardinois")
@DisplayName("Should respond with not found request")//is 401 because first authorized then check if its found
public void shouldNotFindRequest() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/partyy")).andExpect(MockMvcResultMatchers
.status().is(404));
}
@Test
@WithMockUser("JLardinois")
public void ShouldFindRequest() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/parties")).andExpect(MockMvcResultMatchers
.status().isOk());
}
@Test
@WithMockUser("JLardinois")
public void DeleteParty() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.delete("/parties/4")).andExpect(MockMvcResultMatchers
.status().isOk());
}
在这个测试类中,我的控制器中的删除方法得到了测试,但是当我运行它时,数据库中 ID 为 4 的实体被删除。我不想这样。 任何人都可以帮助我如何模拟这个,以便从我的数据库中删除任何内容? 提前致谢!
答案 0 :(得分:0)
首先,你不应该在你的真实数据库上运行测试。测试不应以任何方式与环境相关。如果你想和数据库进行集成测试,注意testcontainers,你可以选择你想要的框架和数据库。您的测试配置不应包含实际的基本值,如果没有,请创建测试配置(src/test/resources 中的 application.yaml)。
如果您不想进行集成测试,请模拟您的存储库:
@MockBean
private MyRepository myRepository;
@Before
public void init() {
Mockito.doNothing().when(myRepository).delete(any());
}