2

I have a method void create(File file); which creates data structure (map) in a class, which will instantiate and put data into the private field:

private Map<String> myMap

of the class.

Now I want to unit test the method create, how could I do it ? Thanks!

hawarden_
  • 1,904
  • 5
  • 28
  • 48

3 Answers3

1

You could access to you property with reflection (see here for instance) but the fact that you need to hack your class to check the outcome of a function execution sounds like a design smell. Unit testing should check the behaviour from end to end of your unit. Mutating the internal state of your object is a side effect that should be checked against an expectation that some mutation method has been invoked from your unit under test.....In practice, you can try to mock the Map.put() and verify that has been called instead of inspect the map itself

Carmine Ingaldi
  • 856
  • 9
  • 23
  • 1
    Yes GhostCat , I admit that is a little a poor solution, If we knew that there is a method which lets observe the state of that map, we could use its return value to make an assert (eg. empty list -> test method that we know will insert just one item -> assert that getItemsCount == 1) or rather inject map with constructor – Carmine Ingaldi May 28 '19 at 12:23
0
class MyClass {
    private final Map<K, V> map;

    MyClass() {
        // production ctr
        this(new HashMap<>();
    }

    MyClass(Map<K, V> map) {
        // visible for testing
        this.map = map;
    }

    void create...

This way your test can inject the map and assert that create causes the expected side effects

Frank Neblung
  • 3,047
  • 17
  • 34
0

You can use the @InjectMocks & @Mock annotation.

Here is a example for JUnit 5 with the latest Mockito version (v2.27).

class SomeClass {

    private Map<String, String> myMap = new HashMap<>();

    public boolean doSomething(String fileName) {
        return myMap.containsKey(fileName);
    }
}

@ExtendWith(MockitoExtension.class)
class SomeClassTest {

    @InjectMocks
    SomeClass someClass;

    @Mock
    Map<String, String> map;

    @Test
    public void test() {

        Mockito.when(map.containsKey("test")).thenReturn(true);

        Assert.assertTrue(someClass.doSomething("test"));

        Mockito.verify(map, Mockito.times(1)).containsKey("test");
    }
}
second
  • 4,069
  • 2
  • 9
  • 24