[英]How to unit test both cases of a void validate method?
I am writing a void validate method like this one: 我正在写一个像这样的无效验证方法:
void validate(SomeObject someObject) {
if (check someObject with constraints) {
throw new SomeException();
}
}
To unit test this method, I would like to test both legal and illegal input: 为了对该方法进行单元测试,我想同时测试合法和非法输入:
Legal in this case means that the validation completes without exceptions. 在这种情况下,合法的意味着验证无例外地完成。 To test it you just need to call validate.
要对其进行测试,只需调用validate。
@Test
public void testLegal() throws SomeException {
validator.validate(/* some legal object*/);
}
This test will fail only if an exception is thrown during validation. 仅在验证期间引发异常时,此测试才会失败。
1st Test Case : 第一个测试用例:
@Test
public void testOK() throws Exception {
validate(someObject);
// At Least 1 assertion
}
2nd Test Case : 第二个测试用例:
@Test(expected=SomeException.class)
public void testException() throws Exception {
try {
validate(someObject);
} catch(SomeException e) {
// At Least 1 assertion
throw e;
}
}
In this 2nd test case, if the exception is not thrown, the test will fail because it expects SommeException.class. 在第二个测试用例中,如果未引发异常,则测试将失败,因为它期望使用SommeException.class。
At least 1 assertion is mandatory because you must verify that the exception that has been thrown is well the one you were expected. 至少有1个断言是强制性的,因为您必须验证抛出的异常是否与预期的一样。
To test the case where someObject
is legal, just call validate
in a try
block. 要测试
someObject
合法的情况,只需在try
块中调用validate
。 If an exception is thrown, fail the test. 如果抛出异常,则测试失败。 If no exception is thrown, let the test end normally and pass, since that is the expected behavior.
如果没有抛出异常,则使测试正常结束并通过,因为这是预期的行为。
Example would look something like: 示例如下所示:
@Test
public void myTest() {
try {
validate(new SomeObject());
} catch (Exception e) {
fail("expected no exception, but one was thrown.");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.