I am trying to unit-test a class 'A' which calls a static method of a class 'B'. Class 'B' essentially has a google guava cache which retrieves a value(Object) from the cache given a key, or loads the object into the cache (in case of a cache-miss) using a service adapter. The service-adapter class in turn has other autowired dependencies to retrieve the object.
These are the classes for illustration purposes:
Class A
public class A {
public Object getCachedObject(String key) {
return B.getObjectFromCache(key);
}
}
Class 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)
}
}
}
Service-Adapter Class
public class ServiceAdapter {
@Autowired
private MainService mainService
public Object getFromService(String key) {
return mainService.getTheObject(key);
}
}
I am able to do the integration test successfully and fetch (or load) the value from (or into) the cache. However, I am unable to write the unit-test for class A. This is what I have tried:
Unit-Test for Class 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);
}
}
When I run the unit-test, it fails with a NullPointerException at ServiceAdapter class where the call: mainService.getTheObject(key) is made.
How do I mock the dependency of ServiceAdapter while unit-testing class A. Shouldn't I be just concerned about the immediate dependency that class A has, viz. B.
I am sure I am doing something fundamentally wrong. How should I write the unit-test for class A?