负面单元测试是指测试用例目标是验证程序中错误或异常情况的处理。以下是一个针对Spring Boot控制器类的负面单元测试案例,以及解决方法的代码示例。
假设我们有一个控制器类 UserController,其中包含一个登录接口 loginUser。我们的目标是测试在用户提供无效凭据时控制器的行为。
@RestController
public class UserController {
@PostMapping("/login")
public ResponseEntity loginUser(@RequestBody UserCredentials credentials) {
// 验证用户凭据逻辑
if (credentials.getUsername().equals("admin") && credentials.getPassword().equals("password")) {
return ResponseEntity.ok("登录成功");
} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
}
}
}
负面单元测试案例 - 用户提供无效凭据时的测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerNegativeUnitTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testLoginUserWithInvalidCredentials() throws Exception {
UserCredentials invalidCredentials = new UserCredentials("admin", "wrong_password");
mockMvc.perform(post("/login")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(invalidCredentials)))
.andExpect(status().isUnauthorized())
.andExpect(content().string("用户名或密码错误"));
}
// 辅助方法:将对象转换为JSON字符串
private static String asJsonString(final Object obj) {
try {
final ObjectMapper mapper = new ObjectMapper();
final String jsonContent = mapper.writeValueAsString(obj);
return jsonContent;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
在上述测试案例中,我们使用了Spring Boot的MockMvc
来模拟HTTP请求,并使用asJsonString
辅助方法将对象转换为JSON字符串进行请求体的设置。
通过编写这样的负面单元测试,我们可以验证控制器类在用户提供无效凭据时是否正确地返回了预期的HTTP状态码和响应消息。