junit测试失败条件出错,出现自定义异常

zbq4xfa0  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(254)

我正在为rest控制器编写一个错误条件的测试用例,当我将expected exception设置为exception.class时,测试将无错误运行。当我将预期的异常更改为customexception.class时,测试失败并出现Assert错误
这是我的控制器类:

@RestController
public class CustomController<CustomFieldRequest customFieldRequest, CustomField customField> {
    @PutMapping(path = "/{customFieldId}",
            consumes = MediaType.APPLICATION_JSON_VALUE, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_ATOM_XML_VALUE})
    public CustomField updateCustomField(@PathVariable String customFieldId, @RequestBody CustomFieldRequest customFieldRequest) throws CustomException {
        customFieldRequest.setAuthorId(getUser());
        customFieldRequest.setId(customFieldId);
        return CustomService.updateCustomeField(customFieldRequest);
    }
}

这是我的服务课程:

@Service
public class CustomServiceImpl implements CustomService {
    @Override
    public CustomField updateCustomeField(CustomFieldRequest customFieldRequest) throws CustomException {

    }
}

这是我的自定义异常类:

public class CustomException extends Exception {
    public CustomException(final String  message) {
        super(message);
    }

    public CustomException(final String  message, final Throwable cause) {
        super(message, cause);
    }
}

这是我的测试课:

public class CustomControllerTest {
    private CustomService customService = Mockito.mock(CustomService.class);

    @Test(expected=Exception.class)
    public void updateCustomFieldThrowsException() throws CustomException {
        //exception.expect(Exception.class);
        CustomFieldRequest request = getRequest();

        when(customService.updateCustomeField(request)).thenThrow(Exception.class);
        //customController.updateCustomField(request.getId(), request);
    }
}

如上所述,如果在测试中将预期异常更改为customexception.class,如下所示:

@Test(expected=CustomException.class)
    public void updateCustomFieldThrowsException() throws CustomException {
        //exception.expect(Exception.class);
        CustomFieldRequest request = getRequest();

        when(customService.updateCustomeField(request)).thenThrow(CustomException.class);
        //customController.updateCustomField(request.getId(), request);
    }

我看到考试失败了 java.lang.AssertionError . 我尝试了@rule注解(如上所示)。

wqlqzqxt

wqlqzqxt1#

您需要的默认构造函数 CustomException 或者在测试中创建如下异常: new CustomException("")

相关问题