我正在创建一个集成测试:
@RunWith(CdiRunner.class)
@AdditionalClasses({FollowUpActivityRepository.class, SettingsPropertiesProducer.class})
public class FollowUpActivityFeaturesTest {
@Inject protected FollowUpActivityService fuaService;
@Test
public void DigitalInputTOFollowUpActivityFIELDS()
{
FollowUpActivityDTO dto = new FollowUpActivityDTO();
dto.setId("id");
dto.setTimestamp(Date.from(Instant.now()));
dto.setDueTimestamp(Date.from(Instant.now()));
dto.setClosingTimestamp(Date.from(Instant.now()));
dto.setMatter("matter");
dto.setComment("comment");
this.fuaService.createOrUpdate(dto);
}
}
createOrUpdate
就像:
public void createOrUpdate(FollowUpActivityDTO dto) throws RepositorySystemException
所以,我需要检查这个异常是否没有抛出。
我想优雅地做到这一点。
实际上,我使用的是 junit 4.12 和 hamcrest 2.0.0.0。
有什么想法吗?
示例
在 .NET 中,我使用 NSubstitute 来获得:
this.apiClient.Invoking(c => c.GrantAuthorization()).ShouldNotThrow();
最佳答案
编辑在你颠倒问题的意思之后:
如果您希望在抛出异常时测试失败,您只需在测试方法签名的 throws
部分声明一个异常即可(如果抛出的异常是某种 RuntimeException
,但你的显然不是):
public void DigitalInputTOFollowUpActivityFIELDS() throws Exception
无需指定任何类型的异常。无论如何,一旦抛出未处理的异常(这是您期望的行为),任何 jUnit 测试都会失败。
来自 this blog :
Test methods that declare that they throw one particular type of exception are brittle because they must be changed whenever the method under test changes.
旧答案:
只需像这样编写您的测试注释:
@Test(expected=RepositorySystemException.class)
这样,只要抛出这个异常,测试方法就会成功。
参见 javadoc .
在您的评论后编辑:
要针对任何异常验证测试,只需:
@Test(expected=Exception.class)
但正如 B. Dalton 所建议的那样,这似乎有点危险,因为此测试随后会通过任何异常,无论它是您期望的异常还是任何其他异常。
为了完整起见,您还可以这样做(基于 this answer ):
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void DigitalInputTOFollowUpActivityFIELDS()
{
FollowUpActivityDTO dto = new FollowUpActivityDTO();
dto.setId("id");
dto.setTimestamp(Date.from(Instant.now()));
dto.setDueTimestamp(Date.from(Instant.now()));
dto.setClosingTimestamp(Date.from(Instant.now()));
dto.setMatter("matter");
dto.setComment("comment");
thrown.expect(Exception.class);
thrown.expectMessage("something you can check"); // if needed
this.fuaService.createOrUpdate(dto);
}
这样,createOrUpdate
仍然能够通过抛出任何类型的异常来验证测试,但至少该方法的其余部分不会。
请参阅 ExpectedException 的 javadoc .
或者,当然,好的旧解决方案:
try {
this.fuaService.createOrUpdate(dto);
fail("this should throw an exception");
} catch (RepositorySystemException e){
// pass
} catch (Exception e){
// pass
}
这不太优雅,但允许您根据需要调整异常处理。
关于java - 不抛出测试异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33104390/