AssertJ:对于Pojo,如何在一个链式句子中检查每个嵌套的Property / Field

时间:2017-12-25 15:33:27

标签: junit assertj

拥有POJO,例如:

public class ClientWebRequest {

    private URI uri;
    private HttpMethod httpMethod;

    private final Header header;
    private final Body body;


    public ClientWebRequest(){
        header = new Header();
        body = new Body();
    }

    //getters and setters

关于JUnit使用AssertJ,以下内容有效,@Test方法传递:

    assertThat(clientWebRequest).isNotNull();

    assertThat(clientWebRequest.getHeader()).isNotNull()
    assertThat(clientWebRequest.getHeader().getAccept()).isNotNull();
    assertThat(clientWebRequest.getHeader().getAcceptLanguage()).isNull();
    assertThat(clientWebRequest.getHeader().getContentType()).isNull();

    assertThat(clientWebRequest.getBody()).isNotNull();
    assertThat(clientWebRequest.getBody().getBody()).isNull();

即使它起作用,也会以某种方式冗长。

我想知道是否可能只用一个句子重写所有上述内容,检查每个嵌套的属性/字段。因此,我尝试了以下例子:

    assertThat(clientWebRequest.getHeader()).isNotNull()
                                           .hasFieldOrProperty("accept").isNotNull()
                                           .hasFieldOrProperty("acceptLanguage").isNull();

但失败并显示以下错误消息:

org.junit.ComparisonFailure: expected:<null> 
but was:<Header [accept=[application/json;charset=UTF-8], acceptLanguage=null, contentType=null]>
        at

我的主要目标是为isNotNull

的每个属性/字段使用isNullPOJO

Alpha :感谢Joel的建议,以下内容有效:

assertThat(clientWebRequest).isNotNull()
                            .extracting("header.accept")
                            .doesNotContainNull();

assertThat(clientWebRequest).isNotNull()
        .extracting("header.acceptLanguage", "header.contentType")
       .containsNull();

从上面(两个街区)如果我尝试以下(一个街区):

assertThat(clientWebRequest).isNotNull()
                            .extracting("header.accept")
                            .doesNotContainNull();
       .extracting("header.acceptLanguage", "header.contentType")
       .containsNull();

失败了。只是好奇是否可以应用一个块。

1 个答案:

答案 0 :(得分:6)

我认为最好的方法是extract所有属性/字段,然后检查它不包含null。

示例:

TolkienCharacter frodo = new TolkienCharacter("Frodo", 33, HOBBIT);

// support nested properties: 
assertThat(frodo).extracting("name", "age", "race.name")
                 .doesNotContainNull()
                 .containsExactly("Frodo", 33, "Hobbit");

请注意,您也可以使用测试对象中的lambdas to extract values

assertThat(frodo).extracting(TolkienCharacter::getName,
                             character -> character.age,
                             character -> character.getRace().getName())
                 .containsExactly("Frodo", 33, "Hobbit");