JUnit Assert if a property exists in a class

摘要: Includes hamcrest-library and test the class property and its value with hasProperty() :

Includes hamcrest-library and test the class property and its value with hasProperty() :

P.S Tested with JUnit 4.12 and 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;

Here’s the Maven pom file to include the hamcrest-library

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>

References

  1. Hamcrest – HasProperty JavaDoc
  2. Maven + JUnit + Hamcrest
  3. JUnit – How to test a List

上一篇: JUnit Categories Test
下一篇: Java Custom Exception Examples
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号