English 中文(简体)
混合网.sf.ehcache.Cache(缓冲)和.put方法根(Mockito)
原标题:Mocking net.sf.ehcache.Cache (ehcache) with .put method stub (Mockito)

I m developing a simple cache functionality with EhCache. There is a generic base class that implements my cache interface (BECache):

public class EhCacheBase<K, V> implements BECache<K, V> {

private static CacheManager cacheManager;
private String cacheName;

public EhCacheBase(String cacheName) {
    this.cacheName = cacheName;
}

public void cache(K key, V value) {
    Cache cache = cacheManager.getCache(cacheName);
    if (cache == null) {
        throw new NullPointerException("Failed to obtain cache: " + cacheName);
    }
    Element element = new Element(key, value);
    cache.put(element);
}

目的是将缓存确定如下:

public class ObjectCache extends EhCacheBase<String, Object>{

    public ObjectCache (String cacheName) {
       super(cacheName);
    }
}

assuming cacheName is defined in ehcache.xml I get a nice class for caching certain objects.

I m trying to write a test for the EhCacheBase.cache(...) method that ensures a cache is retrieved and a value is put (using Mockito):

private static final String CACHE_NAME = "testCache";
@Mock
private CacheManager cacheManager;
@Mock
private Cache cache;
private EhCacheBase<String, Object> ehCacheBase;

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
    ehCacheBase = new EhCacheBase<String, Object>(CACHE_NAME);
    EhCacheBase.setCacheManager(cacheManager);
}

@Test
public void shouldRetrieveCacheAndPutOneValueInIt() {
    //given
    Object o = new Object();
    when(cacheManager.getCache(CACHE_NAME)).thenReturn(cache);

    //when
    ehCacheBase.cache("KEY", o);

    //then
    verify(cacheManager, times(1)).getCache(CACHE_NAME);
    verify(cache, times(1)).put(any(Element.class));
}

当我做测试时,我得到的是:

java.lang.NullPointerException
    at net.sf.ehcache.Cache.checkStatus(Cache.java:2731)
    at net.sf.ehcache.Cache.putInternal(Cache.java:1440)
    at net.sf.ehcache.Cache.put(Cache.java:1417)
    at net.sf.ehcache.Cache.put(Cache.java:1382)
    at org.fxoo.bookingengine.dao.dataproviders.caches.EhCacheBase.cache(EhCacheBase.java:24)
    at org.fxoo.bookingengine.dao.dataproviders.caches.EhCacheBaseTest.shouldCacheOneValue(EhCacheBaseTest.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:35)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:115)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:97)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.booter.ProviderFactory$ClassLoaderProxy.invoke(ProviderFactory.java:103)
    at $Proxy0.invoke(Unknown Source)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:150)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcess(SurefireStarter.java:91)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:69)

It seems like the put method in cache mock is calling some others methods. But as you can read in Mockito docs:

Use doNothing() for setting void methods to do nothing. Beware that void methods on mocks do nothing by default! However, there are rare situations when doNothing() comes handy:

By the way, I tried: doNothing().when(cache).put(any(Element.class)); and it didn t help either.

有什么想法吗?

最佳回答

缓存. put 是最终的, 所以您需要使用 < a href=" http://code.google.com/ p/ p/ powermock/wiki/MockitoUsage13" > PowerMock 来嘲笑它 。

你的测试看起来会是这样的:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Cache.class)
public class EhCacheBaseTest {
    private static final String CACHE_NAME = "testCache";
    private CacheManager cacheManager;
    private Cache cache;
    private EhCacheBase<String, Object> ehCacheBase;

    @Before
    public void init() {
        // You can statically import mock method, but left it this way 
        // for clarity
        cacheManager = PowerMockito.mock(CacheManager.class);
        cache = PowerMockito.mock(Cache.class);
        ehCacheBase = new EhCacheBase<String, Object>(CACHE_NAME);
        EhCacheBase.setCacheManager(cacheManager);
    }

    @Test
    public void shouldRetrieveCacheAndPutOneValueInIt() {
        //given
        Object o = new Object();
        when(cacheManager.getCache(CACHE_NAME)).thenReturn(cache);

        //when
        ehCacheBase.cache("KEY", o);

        //then
        verify(cacheManager, times(1)).getCache(CACHE_NAME);
        verify(cache, times(1)).put(any(Element.class));
    }
}
问题回答

我向Mockito Google Google Group(这里)提出了一个类似的问题。我收到了Eric Lefevre-Ardant的快速答复,其中解释了所有问题。网络.sf.ehcache.Cache.Cache.put的方法是最终的,因此它不能被粘住——Mockito没有提供自己的执行。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签