使用Junit

时间:2015-09-06 08:43:33

标签: java exception junit expected-exception

如何使用ExpectedException检查是否抛出了具有特定参数的异常。假设我有AcmeException,它根据参数返回不同的错误消息:AcmeException(一)返回一,而AcmeException(一,二,三)返回三。我对测试时的返回消息不感兴趣,而是使用它的参数列表确切的异常。

@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))

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

0 个答案:

没有答案