JUnit - マップをテストする方法

JUnit –マップをテストする方法

JUnitassertEquals()を忘れて、Mapをテストするには、hamcrest-library.jarのより表現力豊かなIsMapContainingクラスを使用します

pom.xml

    
        
            junit
            junit
            4.12
            test
            
                
                    org.hamcrest
                    hamcrest-core
                
            
        
        
        
            org.hamcrest
            hamcrest-library
            1.3
            test
        
    

1. IsMapContainingの例

以下のすべてのassertThatチェックに合格します。

MapTest.java

package com.example;

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 map = new HashMap<>();
        map.put("j", "java");
        map.put("c", "c++");
        map.put("p", "python");
        map.put("n", "node");

        Map 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
マップをテストする独自のメソッドを作成する前に、IsMapContainingを試してください。