[英]Not able to inject Map into the object while testing with Mockito
I am trying to test a method of hashMap using Mockito but its not working as expected.我正在尝试使用 Mockito 测试 hashMap 的方法,但它没有按预期工作。 My Class
我的 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我的测试 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.它给出0L而不是2L。
Only reflection can help with private static field:只有反射可以帮助私有 static 字段:
@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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.