Reputation: 175
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
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
Reputation: 5317
@InjectMocks
tries to inject the dependencies in following ways
#3 is probably the way for you. Try the following:
mapTest
to map1
in your test class.map2
similarly. Share more parts fo the code for a more precise answer.
Upvotes: 1
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