0

我有 2 个实现一个接口的类。

public interface DataAccess { /*....*/ }
public class DataAccessCache implements DataAccess { /*...*/ }
public class DataAccessMemory implements DataAccess { /*...*/ }

现在我有另一个名为CPU封装DataAccessCacheDataAccessMemory(都是私有实例变量)的类,例如:

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)

我怎样才能做到这一点?

4

2 回答 2

0

你应该在最后验证你的模拟。

   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");
}
于 2012-11-13T21:21:58.757 回答
0

试试这样:

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 中,只是从头顶输入,但我认为我做对了。试试看。

于 2012-11-13T21:35:00.040 回答