0

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");
    }
}
Samiron
  • 5,169
  • 2
  • 28
  • 55
oitathi
  • 153
  • 2
  • 3
  • 17
  • You're trying to mock the internal state of an object. `PowerMock` provides such functionality. See this reply to [similar question](https://stackoverflow.com/questions/48691837/how-do-i-mock-a-private-field-using-powermockito/48692275#48692275) – MartinBG Oct 10 '19 at 15:11
  • is this spring project? – Ryuzaki L Oct 10 '19 at 15:21

3 Answers3

1

@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.

Samiron
  • 5,169
  • 2
  • 28
  • 55
0

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.

X.walt
  • 483
  • 4
  • 6
0

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;
kbyrd
  • 3,321
  • 27
  • 41
oitathi
  • 153
  • 2
  • 3
  • 17