我正在尝试对调用类“B”的静态方法的类“A”进行单元测试。类'B'本质上有一个谷歌番石榴缓存,它从给定键的缓存中检索值(对象),或使用服务适配器将对象加载到缓存中(以防缓存未命中)。服务适配器类又具有其他自动装配的依赖项来检索对象。
这些是用于说明目的的类:
A级
public class A {
public Object getCachedObject(String key) {
return B.getObjectFromCache(key);
}
}
B类
public class B {
private ServiceAdapter serviceAdapter;
public void setServiceAdapter(ServiceAdapter serAdapt) {
serviceAdapter = serAdapt;
}
private static final LoadingCache<String, Object> CACHE = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(30, TimeUnit.MINUTES)
.build(new MyCacheLoader());
public static Object getObjectFromCache(final String key) throws ExecutionException {
return CACHE.get(warehouseId);
}
private static class MyCacheLoader extends CacheLoader<String, Object> {
@Override
public Object load(final String key) throws Exception {
return serviceAdapter.getFromService(key)
}
}
}
服务适配器类
public class ServiceAdapter {
@Autowired
private MainService mainService
public Object getFromService(String key) {
return mainService.getTheObject(key);
}
}
我能够成功地进行集成测试并从(或加载到)缓存中获取(或加载)值。但是,我无法为 A 类编写单元测试。这是我尝试过的:
A类的单元测试
@RunWith(EasyMocker.class)
public class ATest {
private final static String key = "abc";
@TestSubject
private A classUnderTest = new A();
@Test
public void getCachedObject_Success() throws Exception {
B.setServiceAdapter(new ServiceAdapter());
Object expectedResponse = createExpectedResponse(); //some private method
expect(B.getObjectFromCache(key)).andReturn(expectedResponse).once();
Object actualResponse = classUnderTest.getCachedObject(key);
assertEquals(expectedResponse, actualResponse);
}
}
当我运行单元测试时,它在进行调用的 ServiceAdapter 类中出现 NullPointerException 失败: mainService.getTheObject(key) 。
如何在单元测试类 A 时模拟 ServiceAdapter 的依赖关系。我不应该只关心 A 类的直接依赖关系,即。B.
我确信我做的事情根本上是错误的。我应该如何为 A 类编写单元测试?