【问题标题】:unit testing in spring boot giving error when exception thrown in serviceSpring Boot中的单元测试在服务中抛出异常时会出错
【发布时间】:2018-12-06 05:08:42
【问题描述】:

所以,我需要运行这个单元测试。

@MockBean
private AppServiceImpl appService;


@Test
public void shouldThrowExceptionWhenAppIdIsNull() throws Exception {
    File inputFile = this.getJsonFile();
    RequestDto requestDto = objectMapper.readValue(inputFile.getAbsoluteFile(),
            RequestDto.class);
    AppData appData = requestDto.getAppData();
    appData.setAppId(null);
    requestDto.setAppData(appData);
    when(appService.getUrl(requestDto, "header")).thenThrow(new RequestNotValidException());
    String payload = objectMapper.writeValueAsString(requestDto);
    this.mockMvc.perform(post(Base_URL + "app/requesturl")
            .contentType(contentType).content(payload).header(this.Header, "header"))
            .andExpect(status().is4xxClientError());
}

服务接口:

所以当我运行这个测试时,它会抛出一个异常并且实际上并没有在这里断言测试。

我在RequestNotValidException 之上添加了@ResponseStatus(HttpStatus.BAD_REQUEST),它扩展了RunTimeException

在第二个测试用例中,我得到空响应。我用 Postman 尝试了这个 API,我得到了响应。那里一切正常。

@Test
public void getCardRegistration() throws Exception {
    File inputFile = this.getJsonFile();
    RequestDto requestDto = objectMapper.readValue(inputFile.getAbsoluteFile(), RequestDto.class);
    ResponseDto responseDto = new ResponseDto();
    responseDto.setURL(AuthUtils.randomStringToken(35));
    given(appService.getRegistrationUrl(requestDto, "header")).willReturn(responseDto);
    String payload = objectMapper.writeValueAsString(requestDto);
    MvcResult mvcResult = this.mockMvc.perform(post(Base_URL + "app/requesturl")
            .contentType(contentType).content(payload).header(this.Header, "header"))
            .andReturn();
    String contentAsString = mvcResult.getResponse().getContentAsString();
}

控制器内容:

    @Autowired
    IAppService appService;

    @RequestMapping(value = "/app/requesturl", method = RequestMethod.POST)
public ResponseDto getCardsRegistration(@RequestBody @Valid RequestDto requestDto, @RequestHeader(value="X-App-Name", required = true) String header) throws RequestNotValidException, JsonProcessingException {
    log.info("Request received in controller: "+ mapper.writeValueAsString(cardRegistrationRequestDto));
    log.info("Header value: "+ header);

    return this.appService.getRegistrationUrl(requestDto, header);
}

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AppRestControllerTest {

    protected String Base_URL = "/app";

    protected String Header = "X-App-Name";

    protected MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    @Autowired
    protected MockMvc mockMvc;

    protected ObjectMapper objectMapper = new ObjectMapper();

    @MockBean
    private AppServiceImpl appService;

    @Mock
    private AppRegistrationRepository appRegistrationRepository;


        @Before
    public void setUp() throws Exception {
        MapperFacade mapperFacade = new DefaultMapperFactory.Builder().build().getMapperFacade();
        appService = new AppServiceImpl(appRegistrationRepository, mapperFacade);
    }

我错过了什么?

【问题讨论】:

  • 第一种情况下你试过'@Test(expected = RequestNotValidException.class)'吗?
  • 另外,您可以寻找这个问题(stackoverflow.com/questions/18336277/…),看起来它可以帮助您进行测试。 (寻找“.andExpect”方法
  • 啊,是的。有用。我以前没有想到。我在第二个测试用例中遗漏了什么?
  • 我可以看看你的完整配置吗?请更新帖子
  • 哪些配置?

标签: java spring unit-testing spring-boot


【解决方案1】:

尝试使用

@RunWith(SpringRunner.class)
@WebMvcTest(YourController.class)
public class AppRestControllerTest {

或者

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class AppRestControllerTest {

在你的测试中

【讨论】:

  • 第一个块,所有的测试用例都失败了。当我添加第二个块时没有任何变化。
  • 无法加载ApplicationContext
  • 加载失败是什么原因?
  • java.lang.IllegalStateException: 无法加载 ApplicationContext
  • RestController 的内容会一直为空吗?
猜你喜欢
  • 2020-06-02
  • 2013-01-21
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
相关资源
最近更新 更多