Advertisement
keenan-v1

Abstract Testing

Apr 23rd, 2023
944
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | Source Code | 0 0
  1. @RunWith(SpringRunner.class)
  2. @SpringBootTest
  3. @AutoConfigureMockMvc
  4. public abstract class AbstractCrudControllerTest {
  5.  
  6.     @Autowired
  7.     protected MockMvc mockMvc;
  8.  
  9.     // Define abstract methods for creating, updating, and deleting entities
  10.     protected abstract Object createEntity();
  11.     protected abstract Object updateEntity(Object entity);
  12.     protected abstract String getEndpoint();
  13.     protected abstract Long getEntityId(Object entity);
  14.  
  15.     @Test
  16.     public void testCreateEntity() throws Exception {
  17.         Object entity = createEntity();
  18.  
  19.         mockMvc.perform(post(getEndpoint())
  20.                 .contentType(MediaType.APPLICATION_JSON)
  21.                 .content(JsonUtils.toJson(entity)))
  22.                 .andExpect(status().isCreated())
  23.                 .andExpect(jsonPath("$.id").isNotEmpty());
  24.     }
  25.  
  26.     @Test
  27.     public void testGetEntity() throws Exception {
  28.         Object entity = createEntity();
  29.         mockMvc.perform(get(getEndpoint() + "/" + getEntityId(entity)))
  30.                 .andExpect(status().isOk());
  31.     }
  32.  
  33.     @Test
  34.     public void testUpdateEntity() throws Exception {
  35.         Object entity = createEntity();
  36.         Object updatedEntity = updateEntity(entity);
  37.  
  38.         mockMvc.perform(put(getEndpoint() + "/" + getEntityId(entity))
  39.                 .contentType(MediaType.APPLICATION_JSON)
  40.                 .content(JsonUtils.toJson(updatedEntity)))
  41.                 .andExpect(status().isOk());
  42.     }
  43.  
  44.     @Test
  45.     public void testDeleteEntity() throws Exception {
  46.         Object entity = createEntity();
  47.         mockMvc.perform(delete(getEndpoint() + "/" + getEntityId(entity)))
  48.                 .andExpect(status().isNoContent());
  49.     }
  50.  
  51. }
  52.  
Tags: Java
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement