JUnit –プロパティがクラスに存在する場合にアサート
hamcrest-library
を含み、クラスプロパティとその値をhasProperty()
でテストします。
P.S Tested with JUnit 4.12 and hamcrest-library 1.3
ClassPropertyTest.java
package com.example; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.hasProperty; import static org.junit.Assert.assertThat; 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() { Listlist = 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; } } }
これがhamcrest-library
を含むMavenpomファイルです
pom.xml
junit junit 4.12 test org.hamcrest hamcrest-core org.hamcrest hamcrest-library 1.3 test