hawarden_
hawarden_

Reputation: 2160

Mockito: how to test method that changes private field value?

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!

Upvotes: 3

Views: 5636

Answers (3)

second
second

Reputation: 4259

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");
    }
}

Upvotes: 0

Frank Neblung
Frank Neblung

Reputation: 3165

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

Upvotes: 0

Carmine Ingaldi
Carmine Ingaldi

Reputation: 976

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

Upvotes: 1

Related Questions