【问题标题】:How to mock HashMap methods using Mockito如何使用 Mockito 模拟 HashMap 方法
【发布时间】:2022-09-23 01:16:17
【问题描述】:

我正在尝试使用 Mockito 测试一种 hashMap 方法,但它没有按预期工作。 我的课

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);
    }
}

我的测试班

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);
    }
}

它给出0L而不是2L。

  • Foo 对象不使用测试中的 map1 - 新创建的对象使用自己的私有 map1。您可以模拟地图类: Map mock = mock(Map.class); when(mock.containsKey()).thenReturn(true);
  • @notAPPP 仍然面临同样的问题,您可以尝试使用编辑器
  • 是的,现在我看到您无法将地图注入您的对象

标签: java unit-testing junit hashmap mockito


【解决方案1】:

只有反射可以帮助私有静态字段:

@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);
  }
}

【讨论】:

    猜你喜欢
    • 2020-12-08
    • 2020-03-20
    • 2011-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多