在写单元测试时总会碰到一些静态类和静态方法,EasyMock无法处理这些方法,所以我们需要使用PowerMock。
1、在pom.xml中添加powermock的依赖
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
2、访问memecached服务器的静态方法类
package com.example.common;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;
public class XMemcacheClient {
protected static MemcachedClient connectMem() throws IOException {
String memURL = SysProperties.MEMCACHED_SERVER + ":" + SysProperties.MEMCACHED_PORT;
MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(memURL));
MemcachedClient memcachedClient = builder.build();
return memcachedClient;
}
protected static void close(MemcachedClient memcachedClient) throws IOException {
if (memcachedClient != null) {
memcachedClient.shutdown();
}
}
public static boolean set(String key, int exp, Object o) throws IOException, TimeoutException, InterruptedException, MemcachedException {
MemcachedClient memcachedClient = null;
try {
memcachedClient = connectMem();
return memcachedClient.set(key, exp, o);
} finally {
close(memcachedClient);
}
}
public static Object get(String key) throws IOException, TimeoutException, InterruptedException, MemcachedException {
MemcachedClient memcachedCl