我正在寻找一些建议或最佳实践来实施Spring Boot应用程序的单元测试。
我有多个单元测试类,在每个类中,我需要添加如下配置:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootApplication.class)
public class ServiceRequestControllerTest{
...
}
因此,当我运行目标Maven测试(mvn clean test
)时,弹簧配置会多次加载。例如,我有五个单元测试类,因此它将五次加载配置,这减慢了项目的构建速度。
问题:对于所有单元测试类,有什么方法可以一次加载此配置吗?
答案 0 :(得分:2)
使用@ContextConfiguration
注释。它的默认行为是在测试之间重用上下文。
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringBootApplication.class)
public class ServiceRequestControllerTest{
...
}
答案 1 :(得分:1)
我们必须始终处理异常,因为它使我们可以更好地控制应变。还必须始终使用JSON作为Rest响应的基础,因此我们将具有以下内容:
@RestController
public class ControllerAddress {
@PostMapping("/address")
public ResponseEntity<?> postAddress(@RequestBody String address) {
Map<String, Object> response = new HashMap<>();
try {
response.put("state", true);
return new ResponseEntity<>(response, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
response.put("message", e.getMessage());
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
但是,如果您不想使用JSON并且希望布尔变量true / false直接响应,则可以更改以下行:
response.put("state", true);
return new ResponseEntity<>(response, HttpStatus.OK);
针对:
return new ResponseEntity<>(true, HttpStatus.OK);