JUnit – Assert if a property exists in a class

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


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
    public void testClassProperty() {

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

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

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


	// List Objects
    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


		<!-- This will get hamcrest-core automatically -->


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


Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by