2

如何使用 ExpectedException 检查是否引发了具有特定参数的异常。假设我有 AcmeException,它根据参数返回不同的错误消息:AcmeException(One) 返回一个,而 AcmeException(One,two,three) 返回三个。我对他们在测试时的返回消息不感兴趣,而是对它的参数列表的确切例外感兴趣。

@Rule
public ExpectedException exception = ExpectedException.none();
@Test
@Verifies(value= "should fail with AcmeException", method = "acmeMethod(String, String, String)")
public void acmeMethod_shouldFailWithAcmeException()
        throws Exception {
    //TODO auto-generated
    //Set some global paramater

    //Here only the generic exception type is checked
    exception.expect(AcmeException.class);
    exception.expectMessage("Some Message returned by AcmeException");
    new acmeMethod_shouldFailWithAcmeException();

异常(ShortPasswordException):

/**
* Password exception when the length is less than the minimum allowed.
* <p>

* @since 1.5
*/
public class ShortPasswordException extends PasswordException {

private static final long serialVersionUID = 31620091002L;

public ShortPasswordException() {
    super("error.password.length");
}

public ShortPasswordException(String message) {
    super(message);
   }
 }

上面的异常在这里被调用:

if (StringUtils.isNotEmpty(lengthGp) && password.length() < minLength) {

        if ("true".equals(caseGp) && "true".equals(digitGp) && "true".equals(nonDigitGp)) {
            throw new ShortPasswordException(getMessage("error.password.length.case_digit_nondigit", lengthGp));
        } else if ("true".equals(digitGp) && "true".equals(nonDigitGp)) {
            throw new ShortPasswordException(getMessage("error.password.length.digit_nondigit", lengthGp));
        } else if ("true".equals(caseGp) && "true".equals(nonDigitGp)) {
            throw new ShortPasswordException(getMessage("error.password.length.case_nondigit", lengthGp));
        } else if ("true".equals(caseGp) && "true".equals(digitGp)) {
            throw new ShortPasswordException(getMessage("error.password.length.case_digit_nondigit", lengthGp));
        } else if ("true".equals(nonDigitGp)) {
            throw new ShortPasswordException(getMessage("error.password.length.nondigit", lengthGp));
        } else if ("true".equals(digitGp)) {
            throw new ShortPasswordException(getMessage("error.password.length.digit", lengthGp));
        } else if ("true".equals(caseGp)) {
            throw new ShortPasswordException(getMessage("error.password.length.case", lengthGp));
        } else {
            throw new ShortPasswordException(getMessage("error.password.length", lengthGp));
        }
    }

现在在测试时我想知道什么时候

ShortPasswordException(getMessage("error.password.length.case_digit_nondigit", lengthGp));

或者

ShortPasswordException(getMessage("error.password.length.case_digit_nondigit", lengthGp))

在更改全局属性的值后抛出。

4

0 回答 0