@Test(expected=InvalidPasswordException.class) 和测试方法中的 expectedEx.expectXxx() 方法是不能同时并存的 3. expectedEx.expectMessage() 中的参数是 Matcher 或 subString,就是说可用正则表达式判定,或判断是否包含某个子字符串 再就是有一点很重,把被测试方法写在 expectedEx.expectXxx() 方法后面,不然也...
@Test(expected=InvalidPasswordException.class) 和测试方法中的 expectedEx.expectXxx() 方法是不能同时并存的 3. expectedEx.expectMessage() 中的参数是 Matcher 或 subString,就是说可用正则表达式判定,或判断是否包含某个子字符串 4. 再就是有一点很重,把被测试方法写在 expectedEx.expectXxx() 方法后面,不...
thrown.expect(NullPointerException.class); student.canVote(0); } 或者可以设置预期异常的属性信息。 @TestpublicvoidcanVote_throws_IllegalArgumentException_for_zero_age(){ Student student =newStudent(); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("age should be +ve"); student....
none(); @Test public void test_for_npe_with_rule_at_last_moment() { CoolObject obj = new CoolObject(null); obj.doSomeSetupWork(42); thrown.expect(NullPointerException.class); obj.calculateTheAnswer(); // Any exceptions here will still cause the test to pass incorrectly } ...
@RulepublicExpectedExceptionthrown=ExpectedException.none(); 然后你可以使用更加简单的方式验证预期的异常。 @TestpublicvoidcanVote_throws_IllegalArgumentException_for_zero_age() { Studentstudent=newStudent(); thrown.expect(NullPointerException.class); student.canVote(0); } 或者可以设置预期异常的属性信息...
1. @Rule 注解的 ExpectedException 变量声明,它必须为 public 2. @Test 处,不能写成 @Test(expected=BizException.class),否则不能正确测试,也就是 @Test(expected=BizException.class) 和测试方法中的 expectedEx.expectXxx() 方法是不能同时并存的 ...
import org.junit.rules.ExpectedException; public class JUnit4TestException { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void test1() throws Exception { Foo foo = new Foo(); thrown.expect(Exception.class); thrown.expectMessage("Exception Message"); foo.foo()...
@Test public void ignoredBecauseOfFailedAssumption() { assumeTrue(false); // throws AssumptionViolatedException thrown.expect(NullPointerException.class); }AssertionErrorsJUnit uses AssertionErrors for indicating that a test is failing. You have to call assert methods before you set expectations of th...
thrown.expectMessage(startsWith("What")); throw new NullPointerException("What happened?"); } } 看到最后一个例子的时候,只能惊讶这个东西真是神奇。不过出于使用习惯,个人觉得还是@expect标记比较实用。不过无可非议,当我们对那些只会抛出同一个异常,但是message会根据出错的情况而发生变化的场合使用这个规则是...
publicclassExpectedExceptionRuleTest{@RulepublicExpectedExceptionthrown=ExpectedException.none();@Testpublicvoidtest(){thrown.expect(IllegalArgumentException.class);thrown.expectCause(isA(NullPointerException.class));thrown.expectMessage("This is illegal");thrownewIllegalArgumentException("This is illegal",new...