首页 > 解决方案 > 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. 由于它具有外部依赖项,因此在尝试对此进行测试时遇到了问题。我的服务类中也存在相同类型的记录器。我该如何测试这样的课程。我试过下面的东西

标签: javaspring-bootunit-testingjunitmockito

解决方案


推荐阅读