Home > Enterprise >  Not able to inject Map into the object while testing with Mockito
Not able to inject Map into the object while testing with Mockito

Time:09-24

I am trying to test a method of hashMap using Mockito but its not working as expected. My Class

import java.util.HashMap;
import java.util.Map;
public class Fun {

    private static Map<String,Long> map1= new HashMap<>();
    public long foo(final String test){
        if(!map1.containsKey(test)){
            return 0L;
        }
        return map1.get(test);
    }
}

My test class

import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;


public class FunTest {

    private static Map<String,Long> map1 = new HashMap<>();
    private Fun classUndertest = new Fun();
    @Test
    public void testfoo(){
        map1.put("test",2L);
        long value = classUndertest.foo("test");
        Assert.assertEquals(2L, value);
    }
}

Its giving 0L instead of 2L.

CodePudding user response:

Only reflection can help with private static field:

@ExtendWith(MockitoExtension.class)
public class FunTest {

  private Fun classUndertest = new Fun();

  @Test
  public void testfoo() throws NoSuchFieldException {
    Map<String, Long> test = Map.of("test", 2L);
    FieldSetter.setField(classUndertest, Fun.class.getDeclaredField("map1"), test);

    long value = classUndertest.foo("test");

    Assertions.assertEquals(2L, value);
  }
}
  • Related