我是使用Spring引导框架中的JUnit和Mockito进行单元测试的新手。 我想测试这种方法。如何测试POST请求方法:
// add Employee
@RequestMapping(method = RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
this.employeeService.addEmployee(employee);
}
提前谢谢
答案 0 :(得分:6)
正如@ 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对象上执行发布,并验证响应
您可以在调用表演时添加标题,授权
假设您使用JSON作为媒体类型,则可以使用任何json库将toJson()方法写入以将Employee对象转换为Json字符串格式
private String toJson(Employee emp) {
如果您使用的是XML,则可以对XML进行同样的操作
您可以使用链接的期望值来验证响应。 正确指出,请查看MockedMvc链接,该链接应该对您有帮助
答案 1 :(得分:1)
带有 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));
}
}
答案 2 :(得分:0)
通过下面的示例:
@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格式。