简体   繁体   中英

How to mock a delete test in controller?

So I am making my first tests in spring boot and I came across a problem. When I execute my tests, the values are actually getting deleted. I would prefer to mock this so that the values do not get deleted.

My test class: @SpringBootTest @AutoConfigureMockMvc

public class 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());
}

In this test class, my delete method from my controller gets tested, but the entity with ID 4 in my database gets deleted when I run this. I do not want this. Can anyone help me how to mock this, so that nothing gets deleted from my database? Thanks in advance!

Firstly, you should not run tests on your real database. Tests should not be related to the environment in any way. If you want integration tests with database, pay attention to testcontainers , you can choose framework and database what you want. Your test configuration should not contain the actual base values, create test configuration (application.yaml in src/test/resources) if you don't have it.

If you don't want integration test, mock your repository:

 @MockBean
 private MyRepository myRepository;
 @Before
 public void init() {
    Mockito.doNothing().when(myRepository).delete(any());
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM