繁体   English   中英

Mockito模拟接口在Before中返回null

[英]Mockito mock interface returning null in Before

我正在尝试使用Mockito API运行JUnit测试。

我有以下CacheTest类

public class CacheTest {

    public static final String KEY_1 = "key1";
    public static final long VALUE_1 = 1L;
    public static final long VALUE_2 = 2136L;
    private static final String KEY_2 = "key2";
    private Cache<String, Long> objectUnderTest;

    @Mock
    private CacheLoader<String, Long> cacheLoader;

    @Before
    public void setUp() {
        objectUnderTest = new Cache<>(1000L, cacheLoader); //cacheLoader is null here
        when(cacheLoader.load(Matchers.eq(KEY_1))).thenReturn(VALUE_1); //nullpointer when trying to load from null
        when(cacheLoader.load(Matchers.eq(KEY_2))).thenReturn(VALUE_2);
    }

    @Test
    public void shouldLoadElement() {
        // when
        Long value = objectUnderTest.get(KEY_1);

        // then
        assertThat(value).isEqualTo(VALUE_1);
        verify(cacheLoader, Mockito.times(1)).load(Matchers.eq(KEY_1));
    }
}

CacheLoader界面

public interface CacheLoader<KEY, VALUE> {

    VALUE load(KEY key);
}

缓存类将模拟的cacheLoader作为参数接收

public class Cache<K,V> {

    private long evictionTimeMillis;

    private CacheLoader<K,V> cacheLoader;

    public Cache(final long evictionTimeMillis, final CacheLoader<K, V> cacheLoader) {
        this.evictionTimeMillis = evictionTimeMillis;
        this.cacheLoader = cacheLoader;
    }

    public V get(K key) {
        // TODO
        return this.cacheLoader.load(key);
    }


    public void cleanUp() {
        //TODO
    }

}

和CacheLoader实现

public class CacheLoaderImpl implements CacheLoader<String, Long>{

    private HashMap<String,Long> map = new HashMap<String, Long>() {
        /**
         * 
         */
        private static final long serialVersionUID = -7591912310318794715L;

        {
            map.put("key1", 1L);
            map.put("key2", 2136L);
        }
    };

    @Override
    public Long load(String key) {
        return map.get(key);
    }

}

问题是,正如CacheTest类中的注释所示,执行@Before方法时,模拟接口为null,因此,当我尝试加载时,会得到nullpointer异常。

我是Mockito的新手,如果这是一个noobie错误,请原谅。

我在SO中也看到过类似的问题,但没有一个问题能真正回答我的特殊情况。

我希望我的问题很清楚,否则请告诉我如何改善它。

您需要使用@RunWith(MockitoJUnitRunner.class)注释测试类。 股票JUnit运行程序不会初始化模拟。 另请参见@RunWith(MockitoJUnitRunner.class)与MockitoAnnotations.initMocks(this)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM