java Spring通过设置私有字段对Rest控制器进行单元测试
我有一个简单的Rest控制器,如下所示
@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
。但这没有帮助。使用这种方法,我们无法设置静态字段,因此甚至尝试将它们转换为非静态字段 - 试着模仿
setup
中的CustomLogger
,如下所示mockStatic(CustomLogger.class); when(CustomLogger.getLogger(any())) .thenReturn(new CustomLoggerForTest(HealthController.class.getName()));
但运气不好
是不是我做错了什么导致了这一切李>
共 (0) 个答案