java - Spring Unit Test Rest Controller 通过设置私有字段
问题描述
我有一个简单的休息控制器如下
@RestController
public class HealthController {
private static final CustomLogger logger = CustomLogger.getLogger(HealthController.class.getName());
private HealthService healthService;
@Autowired
public HealthController(HealthService healthService) {
this.healthService = healthService;
}
@RequestMapping(value = "/health", method = RequestMethod.GET)
public ResponseEntity<?> healthCheck() {
return healthService.checkHealth();
}
}
服务等级如下
@Service
public class HealthService {
private static final CustomLogger logger = CustomLogger.getLogger(HealthController.class.getName());
public ResponseEntity<?> checkHealth() {
logger.info("Inside Health");
if (validateHealth()) {
return new ResponseEntity<>("Healthy", HttpStatus.OK);
} else {
return new ResponseEntity<>("Un Healthy", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
boolean validateHealth() {
return true;
}
}
控制器类对应的单元测试如下
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HealthController.class)
public class HealthControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private HealthService healthService;
@Test
public void checkHealthReturn200WhenHealthy() throws Exception {
ResponseEntity mockSuccessResponse = new ResponseEntity("Healthy", HttpStatus.OK);
when(healthService.checkHealth()).thenReturn(mockSuccessResponse);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/health").accept(
MediaType.APPLICATION_JSON);
MvcResult healthCheckResult = mockMvc
.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.OK.value(), healthCheckResult.getResponse().getStatus());
}
}
我遇到的问题是我的CustomLogger
. 由于它具有外部依赖项,因此在尝试对此进行测试时遇到了问题。我的服务类中也存在相同类型的记录器。我该如何测试这样的课程。我试过下面的东西
CustomLoggerForTest
在测试中创建了一个自定义类名。ReflectionTestUtils.setField(healthService, "logger", new CustomerLoggerForTest(HealthService.class.getName()));
中使用setUp
。但这并没有帮助。使用它我们无法设置静态字段,因此甚至尝试将它们转换为非静态- 尝试如下
嘲笑
CustomLogger
in 但没有运气。 有什么做错了导致这种情况吗?setup
mockStatic(CustomLogger.class); when(CustomLogger.getLogger(any())) .thenReturn(new CustomLoggerForTest(HealthController.class.getName()));
解决方案
推荐阅读
- javascript - 获取所有公会的所有用户 [Discord.js]
- node.js - 如何实现多领域的模糊搜索
- ios - Custom UIMenuController using button event error 只能有一个 UIMenuController 实例
- java - 从 SharedPreferences 检索字体大小到其他活动
- mysql - 如何将 MySQL 安装程序重置为默认启动
- git - Git状态变化
- postgresql - 如何取子字符串
- php - 如何通过服务帐号访问 G Suite 成员的日历
- java - Raspberry Pi3b+ 上嵌入的 JavaFX:在触摸屏上按几次后,激活了错误的按钮
- javascript - 如何使用适当的算法过滤数据?