JUNIT中判断类中的属性是否存在

阅读更多
继续使用hamcrest-library来测试JAVA中类的属性,比较方便,
要使用JUnit 4.12 和 hamcrest-library 1.3

public class ClassPropertyTest {

//Single Object
    @Test
    public void testClassProperty() {

        Book obj = new Book("Mkyong in Action");

        assertThat(obj, hasProperty("name"));

        assertThat(obj, hasProperty("name", is("Mkyong in Action")));

    }

// List Objects
    @Test
    public void testClassPropertyInList() {

        List list = Arrays.asList(
                new Book("Java in Action"),
                new Book("Spring in Action")
        );

        assertThat(list, containsInAnyOrder(
                hasProperty("name", is("Spring in Action")),
                hasProperty("name", is("Java in Action"))
        ));

    }

    public class Book {

        public Book(String name) {
            this.name = name;
        }

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}

你可能感兴趣的:(JUNIT中判断类中的属性是否存在)