模拟与Mockito实现接口的2个类的适当方法是什么?

时间:2012-11-13 21:06:30

标签: java unit-testing junit tdd mockito

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

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

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

private DataAccessCache cache;
private DataAccessMemory memory;

要模拟这两个类,我有两个setter方法:

public void setDataAccessCache( DataAccessCache cache ) {
    this.cache = cache;
}

public void setDataAccessMemory( DataAccessMemory memory ) {
    this.memory = memory;
}

我想测试将put(String key, String value)对放入内存和缓存的CPU方法key-value。我想确保缓存的put方法和内存的put方法在CPU的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)

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分: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中,只是从头顶输入它,但我认为我做对了。试试吧。