28 Aralık 2020 Pazartesi

SpringTest MockMvcRequestBuilders Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
get metodu
Örnek
Şöyle yaparız
@Test
public void testGenerateStudent() throws Exception {

  Student student = new Student();
  student.setName("TestStudent");
  Mockito.when(studentService.getRandomStudent()).thenReturn(student);

  mockMvc.perform(MockMvcRequestBuilders.get("/generate-student"))
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andDo(print())
    .andExpect(MockMvcResultMatchers.jsonPath("$.name").isNotEmpty());

}
multipart metodu
Örnek
Şöyle yaparız
MockMultipartFile file1 = ...
MockMultipartFile file2 = ...

MvcResult result = mvc.perform(
  MockMvcRequestBuilders.multipart("/api/files")
    .filefile1)
    .file(file2))
  .andDo(print())
  .andExpect(status().isCreated())
  .andReturn();
param metodu
@RequestParam için gereken veriyi gönderir

Örnek
Elimizde şöyle bir kod olsun
@RestController @RequiredArgsConstructor @Slf4j public class LinksController { private final LinksService linksService; @GetMapping("/validateLink-url") public UrlSafety validateLink(@RequestBody String link, @RequestParam("directSearch") boolean isDirectSearch) { ... } }
Şöyle yaparız
@WebMvcTest public class LinksControllerIntegrationTest { @Autowired private MockMvc mockMvc; @MockBean private LinksService linksService; @Test public void testValidateLinkDirectSearchTrue_WhenUrlExists_ShouldReturnValid() String url = "http://safe-url.com"; when(linksService.isSafeUrlByDirectSearch(url)).thenReturn(true); mockMvc.perform(get("/validateLink-url") .param("directSearch", "true") .content(url) .contentType(MediaType.TEXT_PLAIN) .accept(MediaType.APPLICATION_PROBLEM_JSON)) .andExpect(status().isOk()) .andExpect(content().string("\"" + UrlSafety.VALID.getValue() + "\"")); verify(linksService, times(1)).isSafeUrlByDirectSearch(url); }

post metodu
Post isteğine karşılık sonuç olarak döndürülen json'ı beklenen json ile karşılaştırmak için şöyle yaparız
@Test
void listFoods() {
  String expectedResponse = "...";
  mockMvc.perform(MockMvcRequestBuilders.post("/graphql")
    .content("{\"query\":\"{ foods { id name isGood } }\"}")
    .contentType(MediaType.APPLICATION_JSON)
    .accept(MediaType.APPLICATION_JSON))
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andExpect(MockMvcResultMathers.content().json(expectedResponse))
    .andReturn();
}

Hiç yorum yok:

Yorum Gönder