我有 2 个实现一个接口的类。
public interface DataAccess { /*....*/ }
public class DataAccessCache implements DataAccess { /*...*/ }
public class DataAccessMemory implements DataAccess { /*...*/ }
现在我有另一个名为CPU
封装DataAccessCache
和DataAccessMemory
(都是私有实例变量)的类,例如:
private DataAccessCache cache;
private DataAccessMemory memory;
为了模拟这两个类,我有 2 个 setter 方法:
public void setDataAccessCache( DataAccessCache cache ) {
this.cache = cache;
}
public void setDataAccessMemory( DataAccessMemory memory ) {
this.memory = memory;
}
我想测试put(String key, String value)
将key-value
配对放入内存和缓存的 CPU 方法。我想确保在 CPU 的 put 方法中调用缓存的 put 方法和内存的 put 方法。我正在这样测试(使用 Mockito):
public void test() {
CPU cpu = new cpu();
DataAccessCache cache = mock( DataAccessCache.class );
DataAccessMemory memory = mock( DataAccessMemory.class );
when( cache.put("key", "value") ).thenReturn(true);
when( memory.put("key", "value") ).thenReturn(true);
cpu.setDataAccessCache( cache );
cpu.setDataAccessMemory( memory );
cpu.put("key", "value");
verify( cache ).put("key", "value");
verify( memory ).put("key", "value");
}
但是,测试结果表明存在错误:
java.lang.NullPointerException
at CPU.put(Unknown Source)
at CPUTest.test(Unknown Source)
我怎样才能做到这一点?