使用EhCache3进行JUnit测试

时间:2016-12-27 19:22:18

标签: java caching mockito junit4 ehcache

我创建了简单的缓存应用程序,如下所示:

import org.ehcache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.cache.CacheException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class JsonObjectCacheManager {
    private static final Logger logger = LoggerFactory.getLogger(JsonObjectCacheManager.class);
    private final Cache<String, JsonObjectWrapper> objectCache;

    //setting up cache
    public JsonObjectCacheManager() {
        CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
                .withCache("jsonCache",
                        CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, JsonObjectWrapper.class,
                                ResourcePoolsBuilder.newResourcePoolsBuilder()
                                        .heap(100, EntryUnit.ENTRIES)
                                        .offheap(10, MemoryUnit.MB))
                                .withExpiry(Expirations.timeToLiveExpiration(Duration.of(5, TimeUnit.MINUTES)))
                                .withValueSerializingCopier()
                                .build())
                .build(true);

        objectCache = cacheManager.getCache("jsonCache", String.class, JsonObjectWrapper.class);
    }

    public void putInCache(String key, Object value) {
        try {
            JsonObjectWrapper objectWrapper = new JsonObjectWrapper(value);
            objectCache.put(key, objectWrapper);
        } catch (CacheException e) {
            logger.error(String.format("Problem occurred while putting data into cache: %s", e.getMessage()));
        }
    }

    public Object retrieveFromCache(String key) {
        try {
            JsonObjectWrapper objectWrapper = objectCache.get(key);
            if (objectWrapper != null)
                return objectWrapper.getJsonObject();
        } catch (CacheException ce) {
            logger.error(String.format("Problem occurred while trying to retrieveSpecific from cache: %s", ce.getMessage()));
        }
        logger.error(String.format("No data found in cache."));
        return null;
    }

    public boolean isKeyPresent(String key){
        return objectCache.containsKey(key);
    }

}

JsonObjectWrapper只是一个封装Object的包装类,因此可以对其进行序列化。

@Getter
@Setter
@ToString
@AllArgsConstructor
public class JsonObjectWrapper implements Serializable {
    private static final long serialVersionUID = 3588889322413409158L;
    private Object jsonObject;
}

我已经编写了JUnit测试,如下所示:

import org.junit.*;
import org.mockito.*;

import java.util.*;

import static org.junit.Assert.*;

@RunWith(MockitoJUnitRunner.class)
public class JsonObjectCacheManagerTest {

    private JsonObjectCacheManager cacheManager;

    private Map<String, Object> names;

    @Before
    public void setup(){
        /*names = new HashMap(){
            {
                    put("name1", "Spirit Air Lines");
                    put("name2", "American Airlines");
                    put("name3", "United Airlines");
                }
            };*/

        //edited as per Henri's point and worked
        names = new HashMap();
        names.put("name1", "Spirit Air Lines");
        names.put("name2", "American Airlines");
        names.put("name3", "United Airlines");
           cacheManager = new JsonObjectCacheManager();
        }
    @Test
    public void isPresentReturnsTrueIfObjectsPutInCache() throws Exception {
        //put in cache
        cacheManager.putInCache("names",names);
        assertTrue(cacheManager.isKeyPresent("names"));
    }

    @Test
    public void cacheTest() throws Exception {
        //put in cache
        cacheManager.putInCache("names",names);

        //retrieve from cache
        Map<String, Object> namesFromCache = (Map<String, Object>) cacheManager.retrieveFromCache("names");
        //validate against the cached object
//        assertEquals(3, namesFromCache.size());
//        assertEquals("American Airlines", namesFromCache.get("name2"));

    }
}

我收到断言错误,说缓存中没有密钥。这意味着没有将对象添加到缓存中。

有没有办法对此进行junit测试?谢谢你的帮助。

修改 嘿伙计们,@ Henri指出我的错误,它解决了我的问题。 :)

2 个答案:

答案 0 :(得分:2)

问题是你的HashMap。实例化它的方式会创建一个匿名内部类。它保留了对外部类实例的引用。哪个是测试类。测试类不可序列化。

如果您使用以下代码,则所有测试都会很好地通过。

    names = new HashMap();
    names.put("name1", "Spirit Air Lines");
    names.put("name2", "American Airlines");
    names.put("name3", "United Airlines");

答案 1 :(得分:0)

@Test
public void cacheTest() throws Exception {
    cacheManager = Mockito.mock(JsonObjectCacheManager.class);

你必须嘲笑被测试的课程。