我有 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;
}
我想测试将key-value
对放入内存和缓存的 CPU 方法put(String key, String value)
。我想确保缓存的 put 方法和内存的 put 方法在 CPU 的内部放置方法中调用。我正在这样测试(使用 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)
我怎样才能做到这一点?
您应该在
最后验证您的模拟。
public void test() {
CPU cpu = new cpu();
DataAccessCache cache = mock( DataAccessCache.class );
DataAccessMemory memory = mock( DataAccessMemory.class );
cpu.setDataAccessCache( cache );
cpu.setDataAccessMemory( memory );
cpu.put("key", "value");
verify( cache ).put("key", "value");
verify( memory ).put("key", "value");
}
像这样尝试:
public void test() {
CPU cpu = new cpu();
DataAccessCache cache = spy( new DataAccessCache() );
DataAccessMemory memory = spy( new DataAccessMemory() );
//when( cache.put("key", "value") ).thenReturn(true);
doReturn(true).when(cache).put(eq("key"), eq("value"));
//when( memory.put("key", "value") ).thenReturn(true);
doReturn(true).when(memory).put(eq("key"), eq("value"));
cpu.setDataAccessCache( cache );
cpu.setDataAccessMemory( memory );
cpu.put("key", "value");
verify( cache ).put("key", "value");
verify( memory ).put("key", "value");
}
我还没有把它放到 IDE 中,只是从我的头顶上输入它,但我认为我做对了。试试吧。