oitathi
oitathi

Reputation: 175

How to mock a map in mockito?

I have two maps that have the same arguments. I would like to mock one of them to test my class. But I don't know a reason that it's not working

this is my class

public class A {
    private Map<String, Foo> map1;
    private Map<String, Foo> map2;

    public A() { 
       this.map1 = new HashMap<String,Foo>();
       map1.put("one",new Foo());

       this.map2 = new HashMap<String, Foo>();
       map2.put("two", new Foo());
    }

    public void doSomenthing(String str){
        Foo foo = map1.get(str)
        //other actions
    }

}

and this is my test class:

public class ATest{

    @InjectMocks
    private A a;

    @Mock
    private  HashMap<String, Foo> mapTest;

    @Before
    public void initialize() throws Exception {
        when(mapTest.get(Mockito.anyString())).thenReturn(new Foo());
    }

    @Test
public void testSomething() throws Exception {
       a.doSomething("blabla");
    }
}

Upvotes: 0

Views: 17015

Answers (3)

oitathi
oitathi

Reputation: 175

You need the same name and same type in the two classes:

//main class
private  HashMap<String, Foo> map;

//test class
@Mock
private  HashMap<String, Foo> map;

Upvotes: 0

Samiron
Samiron

Reputation: 5317

@InjectMocks tries to inject the dependencies in following ways

  1. By using construtor first.
  2. Then property setter.
  3. Then field injection.

#3 is probably the way for you. Try the following:

  • Remove map initialization from constructor to their setter function.
  • Change the variable name mapTest to map1 in your test class.
  • also define map2 similarly.
  • Then InjectMocks should find a matching field to inject.

Share more parts fo the code for a more precise answer.

Upvotes: 1

X.walt
X.walt

Reputation: 563

Before you jump in mock the Map, is that necessary to mock a map? Mock is used to replace other part of your code that you don't want to be involved in your unit test. While Map is easy enough to initiate in unit test.

Upvotes: 0

Related Questions