在JUnit中验证具体的异常详细信息

pep*_*uch 2 java junit unit-testing

要验证异常消息,我可以使用ExpectedMessage对象,但如果我想验证concreate异常及其详细信息,该怎么办?例如,我有异常类TerribleWindException,有一些额外的方法,如getWindSpeed()在和junit测试方法,我想检查getWindSpeed()结果.看看这个例子:

// pseudo implementation

public class TerribleWindException extends Exception {

    private Integer windSpeed = 0;

    public TerribleWindException(final Integer windSpeed) {
        this.windSpeed = windSpeed;
    }

}

public class WalkService {

    private Integer windSpeed = 0;

    public WalkService(final Integer windSpeed) {
        this.windSpeed = windSpeed;
    }

    public void goForAWalk() throws TerribleWindException {
        if  (windSpeed>10) {
            throw new TerribleWindException(windSpeed);
        }
    }

}

// test

public class WalkServiceTest {

    @Test
    public void testGoForAWalkWhenSpeedIsToPowerfulShouldThrowTerribleWindException throws TerribleWindException {
        WalkService ws = new WalkService(100);
        goForAWalk(); // this will throw TerribleWindException. The only way to check it's exception details is to use try {} catch() {} ?
    }

}
Run Code Online (Sandbox Code Playgroud)

检查异常详细信息的唯一方法是使用try {} catch(){}?

Ste*_*ner 6

您可以将JUnit的ExpectedException规则与Hamcrest匹配器一起使用.

public class WalkServiceTest {
  @Rule
  public final ExpectedException thrown = ExpectedException.none();

  @Test
  public void testGoForAWalkWhenSpeedIsToPowerfulShouldThrowTerribleWindException throws TerribleWindException {
    WalkService ws = new WalkService(100);
    thrown.expect(TerribleWindException.class);
    thrown.expect(Matchers.hasProperty("windSpeed", Matchers.equalTo("expected speed")));
    ws.goForAWalk(); // this will throw TerribleWindException. The only way to check it's exception details is to use try {} catch() {} ?
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Java 8,那么您可以将Vallado库与Hamcrest一起使用.

public class WalkServiceTest {
  @Test
  public void testGoForAWalkWhenSpeedIsToPowerfulShouldThrowTerribleWindException throws TerribleWindException {
    WalkService ws = new WalkService(100);
    when(() -> ws.goForAWalk())
      .thenA(TerribleWindException.class)
      .that(hasProperty("windSpeed", equalTo("expected speed")))
      .isThrown();
  }
}
Run Code Online (Sandbox Code Playgroud)