簡體   English   中英

如何使用 Mockito 和 JUnit 在 Spring Boot 中測試 POST 方法

[英]How to test POST method in Spring boot using Mockito and JUnit

我是在 Spring 引導框架中使用 JUnit 和 Mockito 進行單元測試的新手。 我想測試這個方法。 如何測試 POST 請求方法:

// add Employee
@RequestMapping(method = RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
    this.employeeService.addEmployee(employee);
}

先感謝您

正如@merve-sahin 正確指出的那樣,您可以使用@WebMvcTest 來實現這一點。

看下面的例子:

@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
public class YourControllerTest {

    @Autowired MockMvc mvc;
    @MockBean EmployeeService employeeService;

    @Test
    public void addEmployeeTest() throws Exception {

        Employee emp = createEmployee();

        mvc.perform(post("/api/employee")
            .contentType(MediaType.APPLICATION_JSON)
            .content(toJson(emp)))
            .andExpect(status().isOk());
    }
}

在上面的代碼中,您可以使用 @MockBean 模擬您的依賴服務。 該測試將對您的自定義 Employee 對象執行 post 並驗證響應

您可以在調用執行時添加標題,授權

假設您使用 JSON 作為媒體類型,您可以使用任何 json 庫編寫 toJson() 方法將 Employee 對象轉換為 Json 字符串格式

private String toJson(Employee emp) {

如果您使用的是 XML,那么您可以對 XML 執行相同的操作

您可以以鏈式方式使用期望來驗證響應。 正如正確指出的那樣,請查看 MockedMvc​​ 鏈接,它應該可以幫助您

通過以下示例:

@RunWith(SpringJUnit4ClassRunner.class)
public class ApplicationControllerTest {

    @Mock
    EmployeeService employeeService;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
        YourController controller = new YourController(employeeService);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void addEmployee() throws Exception {
        Employee emp = new Employee("emp_id","emp_name");//whichever data your entity class have

        Mockito.when(employeeService.addEmployee(Mockito.any(Employee.class))).thenReturn(emp);

        mockMvc.perform(MockMvcRequestBuilders.post("/employees")
                .content(asJsonString(emp))
                .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"));
    }

    public static String asJsonString(final Object obj) {
        try {
            return new ObjectMapper().writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

在上面給出的示例中模擬您的服務類,它需要將數據發布到您的 Employee 實體類。 我假設您是通過控制器執行此操作,因此您首先需要初始化@Before 注釋下的控制器。

通過執行上面的示例,您將能夠將數據發布為 JSON 格式。

  • 以下示例使用 J Unit5、Mockito3.x、spring-boot2.4.4 和 assertj3.x
  • 版本 2.2.0 中的 spring-boot-starter-test 依賴項已經隨 Junit 5 一起提供,並且還包含 Hamcrest、assertj 和 Mockito 庫。
  • 在 JUnit 5 中,JUnit 4 中可用的“Runner”擴展點被擴展 API 取代。
  • 您可以通過@ExtendWith注冊 Mockito 擴展
  • 初始化用 @Mock 注釋注釋的模擬,以便不需要顯式使用 MockitoAnnotations#initMocks(Object)。
  • 從 spring-boot 2.1 開始,不需要使用注釋 @ExtendWith 加載 SpringExtension,因為它作為元注釋包含在這些注釋@DataJpaTest、@WebMvcTest 和 @SpringBootTest 中。

帶有 Github 鏈接的完整示例: https : //github.com/jdamit/DemoSpringBootApp.git

@WebMvcTest(controllers = UserController.class)

公共類 UserControllerTest {

@Autowired
private MockMvc mockMvc;

@Autowired
private ObjectMapper mapper;

@MockBean
private UserServiceImpl userService;

private List<UserDto> users;

private UserDto user;

private String URI = "/users";

@BeforeEach
void setUp(){
    users = List.of(new UserDto("Amit", "Kushwaha", "jdamit2027@gmail.com", "sector 120"),
            new UserDto("Amit", "Kushwaha", "jdamit2027@gmail.com", "sector 120"),
            new UserDto("Amit", "Kushwaha", "jdamit2027@gmail.com", "sector 120"));
    user = new UserDto("Rahul", "Swagger", "rahul.swagger@gmail.com", "sector 120");
}

@Test
//@Disabled
void getUsersTest() throws Exception {

    Mockito.when(userService.getUsers()).thenReturn(users);

    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get(URI)
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn();

    Assertions.assertThat(result).isNotNull();
    String userJson = result.getResponse().getContentAsString();
    Assertions.assertThat(userJson).isEqualToIgnoringCase(mapper.writeValueAsString(users));
}

@Test
//@Disabled
void createUserTest() throws Exception {

    Mockito.when(userService.createUser(Mockito.any(UserDto.class))).thenReturn(user);

    MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post(URI)
            .contentType(MediaType.APPLICATION_JSON)
            .content(mapper.writeValueAsString(user).getBytes(StandardCharsets.UTF_8))
            .accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn();

    Assertions.assertThat(result).isNotNull();
    String userJson = result.getResponse().getContentAsString();
    Assertions.assertThat(userJson).isNotEmpty();
    Assertions.assertThat(userJson).isEqualToIgnoringCase(mapper.writeValueAsString(user));
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM