如何使用Mockito和JUnit在Sping Boot 中测试POST方法

m4pnthwp  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(103)

我是在Sping Boot 框架中使用JUnit和Mockito进行单元测试的新手。我想测试一下这个方法。如何测试POST请求方法:

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

提前感谢您

jxct1oxe

jxct1oxe1#

正如@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并验证响应
您可以在调用perform时添加标头、授权
假设您使用JSON作为媒体类型,您可以使用任何JSON库编写toJson()方法,将Employee对象转换为JSON字符串格式

private String toJson(Employee emp) {

如果您正在使用XML,那么您可以对XML执行相同的操作
您可以使用期望以链式方式验证响应。正如正确指出的,请检查MockedMvc链接,这应该有助于您

8wtpewkr

8wtpewkr2#

看看下面这个例子:

@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格式。

ttcibm8c

ttcibm8c3#

  • 下面的示例使用JUnit 5、Mockito3.x、spring-boot 2.4.4和assertj3.x
  • 来自2.2.0版的spring-boot-starter-test依赖已经随Junit 5一起提供,并且还包含Hamcrest、assertj和Mockito库。
  • 在JUnit 5中,JUnit 4中提供的“Runner”扩展点被Extension API取代。
  • 您可以通过**@ExtendWith.**注册Mockito扩展。
  • 使用@Mock注解来注解MockitoAnnotations,因此不需要显式使用MockitoAnnotations#initMocks(Object)。
  • 从spring-boot 2.1开始,不需要使用annotation @ExtendWith加载SpringExtension,因为它作为元annotation包含在这些annotation中**@DataJpaTest,@WebMvcTest和@SpringBootTest。

使用Github链接的完整示例:https://github.com/jdamit/DemoSpringBootApp.git

**@WebMvcTest(controllers = UserController.class)**

public 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", "[email protected]", "sector 120"),
                new UserDto("Amit", "Kushwaha", "[email protected]", "sector 120"),
                new UserDto("Amit", "Kushwaha", "[email protected]", "sector 120"));
        user = new UserDto("Rahul", "Swagger", "[email protected]", "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));
    }
}

相关问题