包括hamcrest-library
并使用hasProperty()
测试类属性及其值:
PS已通过JUnit 4.12和hamcrest-library 1.3测试
ClassPropertyTest.java
package com.mkyong;
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() {
List<Book> 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;
}
}
}
这是包含hamcrest-library
的Maven pom文件
pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- This will get hamcrest-core automatically -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
参考文献
翻译自: https://mkyong.com/unittest/junit-assert-if-a-property-exists-in-a-class/