Create Project: springboot_test_mockmvc_pathvariable (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside controllers package)
Create Test Class: MyControllerTest.java
MyController.java
package com.ivoronline.springboot_test_mockmvc_pathvariable.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@GetMapping("/Hello/{FirstName}/{age}")
public String hello(
@PathVariable("FirstName") String name, //IF NAMES ARE DIFFERENT
@PathVariable String age //IF NAMES ARE THE SAME
) {
return name + " is " + age + " years old";
}
}
MyControllerTest.java
package com.ivoronline.springboot_test_mockmvc_pathvariable.controllers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest
class MyControllerTest {
@Autowired MockMvc mockMvc;
@Autowired MyController myController;
@Test
void hello() throws Exception {
//CREATE REQUEST
MockHttpServletRequestBuilder request = get("/Hello/John/20");
//PERFORM REQUEST
mockMvc.perform(request).andExpect(status().isOk());
}
}