JUnit How to test a Map

摘要: Forget about JUnit assertEquals(), to test a Map, uses the more expressive IsMapContaining class from hamcrest-library.jar

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.

MapTest.java
package com.mkyong;
import org.hamcrest.collection.IsMapContaining;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
public class MapTest {
    @Test
    public void testAssertMap() {
        Map<String, String> map = new HashMap<>();
        map.put("j", "java");
        map.put("c", "c++");
        map.put("p", "python");
        map.put("n", "node");
        Map<String, String> expected = new HashMap<>();
        expected.put("n", "node");
        expected.put("c", "c++");
        expected.put("j", "java");
        expected.put("p", "python");
        //All passed / true
        //1. Test equal, ignore order
        assertThat(map, is(expected));
        //2. Test size
        assertThat(map.size(), is(4));
        //3. Test map entry, best!
        assertThat(map, IsMapContaining.hasEntry("n", "node"));
        assertThat(map, not(IsMapContaining.hasEntry("r", "ruby")));
        //4. Test map key
        assertThat(map, IsMapContaining.hasKey("j"));
        //5. Test map value
        assertThat(map, IsMapContaining.hasValue("node"));
Note
Try IsMapContaining, before you create your own methods to test a Map.

References

  1. Hamcrest official site
  2. IsMapContaining JavaDoc
  3. JUnit – How to test a List

上一篇: Intellij IDEA How to build project automatically
下一篇: JUnit How to test a List
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

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

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

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