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 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 …

Read more

JUnit – How to test a Map

Forget about JUnit assertEquals(), to test a Map, uses the more expressive IsMapContaining class from hamcrest-library.jar 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> 1. IsMapContaining Examples All the below assertThat checks will be passed. …

Read more

JUnit – How to test a List

First, exclude the JUnit bundled copy of hamcrest-core, and include the useful hamcrest-library, it contains many useful methods to test the List data type. 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> 1. Assert List …

Read more

Hamcrest – How to assertThat check null value?

Try to check null value with the Hamcrest assertThat assertion, but no idea how? @Test public void testApp() { //ambiguous method call? assertThat(null, is(null)); } 1. Solution 1.1 To check null value, try is(nullValue), remember static import org.hamcrest.CoreMatchers.* //hello static import, nullValue here import static org.hamcrest.CoreMatchers.*; import org.junit.Test; //… @Test public void testApp() { //true, …

Read more

Gradle and JUnit example

In Gradle, you can declare the JUnit dependency like this: build.gradle apply plugin: ‘java’ dependencies { testCompile ‘junit:junit:4.12’ } By default, JUnit comes with a bundled copy of hamcrest-core $ gradle dependencies –configuration testCompile testCompile – Compile classpath for source set ‘test’. \— junit:junit:4.12 \— org.hamcrest:hamcrest-core:1.3 1. Gradle + JUnit + Hamcrest Normally, we need …

Read more