gemfire cacheclosedexception尚未创建缓存

时间:2015-10-28 14:44:14

标签: unit-testing caching mockito gemfire spring-data-gemfire

我正在尝试为使用缓存实例的方法编写单元测试,如下所示

public void method(String abc) {
....
....
Cache cache = CacheFactory.getAnyInstance();
....
....
}

我知道mocking是解决缓存依赖性的方法。我是嘲笑和使用mockito的新手,并且不确定如何将模拟缓存传递给方法。

@Mock
Cache cache;

@Test
public void testMethod(){

   doReturn(cache).when(CacheFactory.getAnyInstance());
   method("abc");

}

以上就是我尝试过并得到错误。

2 个答案:

答案 0 :(得分:0)

如果您正在测试调用CacheFactory.getAnyInstance()的应用程序组件中的某些代码路径(例如method("abc")?),那么您必须确保该方法以另一种方式获取对模拟Cache的引用不能在类上模拟静态方法(即getAnyInstance() on CacheFactory),至少在没有像PowerMock这样的框架的帮助下。例如......

public class ExampleApplicationComponent {

  public void methodUnderTest(String value) {
    ...
    Cache hopefullyAMockCacheWhenTesting = CachFactory.getAnyInstance();
    ...
    // do something with the Cache...
  }
}

当然,这会失败。所以你需要重新调整你的代码......

public class ExampleApplicationComponent {

  public void methodUnderTest(String value) {
    ...
    Cache cache = fetchCache();
    ...
    // do something with the (mock) Cache...
  }

  Cache fetchCache() {
    return CacheFactory.getAnyInstance();
  }
}

然后在测试类的测试用例中......

public class ExampleApplicationComponentTest {

  @Mock
  private Cache mockCache;

  @Test
  public void methodUsesCacheProperly() {
    ExampleApplicationComponent applicationComponent = 
        new ExampleApplicationComponent() {
      Cache fetchCache() {
        return mockCache;
      }
    };

    applicationComponent.method("abc");

    // assert appropriate interactions were performed on mockCache
  }
}

正如您所看到的,您可以在测试用例中覆盖匿名ExampleApplicationComponent子类中的fetchCache()方法,以返回模拟高速缓存。另请注意,fetchCache()方法是故意制作的"包装私密"限制它对主要测试类的可访问性(因为测试类通常和应该与被测试的类位于同一个包中)。这可以防止fetchCache方法转义并成为API的一部分。虽然同一个包中的其他类可以访问ExampleApplicationComponent类的实例的方法,但至少会重新训练对该用法的控制(当然,不能替代好的文档)。

要在实践中查看其他示例,请查看 Spring Data GemFire CacheFactoryBeanTest class(适用于instancespecifically) ,这完全是我上面描述的使用Mockito。

希望这有帮助。

干杯! -John

答案 1 :(得分:0)

我在PowerMockito的帮助下做到了这一点,下面是代码

mockStatic(CacheFactory.class);
when(CacheFactory.getAnyInstance()).thenReturn(cache);

method("abc");

verifyStatic();
CacheFactory.getAnyInstance();
相关问题