Abhishek Abhishek - 4 months ago 29
Java Question

How to Mock repository Items in ATG

I am trying to create a Mock class for droplet. I am able to mock the repository calls and

req.getParameter
but need help on how to mock the repository item list from the repository. Below is the sample code.

for (final RepositoryItem item : skuList) {
final String skuId = (String) item.getPropertyValue("id");
final String skuType = (String) item.getPropertyValue("skuType");
if (this.isLoggingDebug()) {
this.logDebug("skuType [ " + skuType + " ]");
}
final String skuActive = (String) item.getPropertyValue("isActive");
if EJSD.equalsIgnoreCase(skuType) && (skuActive.equals("1"))) {
eSkuList.add(item);
skuCode = (String) item.getPropertyValue(ESTConstants.SKU_MISC1);
} else (PJPROMIS.equalsIgnoreCase(skuType) && skuId.contains("PP") && (skuActive.equals("1"))) {
personalSkuList.add(item);
String tmp = "";
if (skuId.lastIndexOf("-") > -1) {
tmp = skuId.substring(skuId.lastIndexOf("-") + 1);
tmp = tmp.toUpperCase();
if (this.getDefaultDisplayNameMap() != null) {
String val = this.getDefaultDisplayNameMap().get(tmp);
if (StringUtils.isNotEmpty(val)) {
displayNameMap.put(skuId, val);
} else {
val = (String) item.getPropertyValue("displayName");
displayNameMap.put(skuId, val);
}
} else {
final String val = (String) item.getPropertyValue("displayName");
displayNameMap.put(skuId, val);
}
}

}
}

Answer

There are a multitude of ways to 'mock' the list. I've been doing it this was as I feel it is more readable.

    @Mock private RepositoryItem   skuMockA;
    @Mock private RepositoryItem   skuMockB;

    List<RepositoryItem> skuList = new ArrayList<RepositoryItem>();

    @BeforeMethod(groups = { "unit" })
    public void setup() throws Exception {
        testObj = new YourDropletName();
        MockitoAnnotations.initMocks(this);

        skuList = new ArrayList<RepositoryItem>();
        skuList.add(skuMockA);
        skuList.add(skuMockB);


        Mockito.when(skuMockA.getPropertyValue("id")).thenReturn("skuA");
        Mockito.when(skuMockA.getPropertyValue("skuType")).thenReturn(ActiveSkuDroplet.EJSD);
        Mockito.when(skuMockA.getPropertyValue(ESTConstants.SKU_MISC1)).thenReturn("skuCodeA");
        Mockito.when(skuMockA.getPropertyValue("displayName")).thenReturn("skuADisplayName");

        Mockito.when(skuMockB.getPropertyValue("id")).thenReturn("skuB-PP");
        Mockito.when(skuMockB.getPropertyValue("skuType")).thenReturn(ActiveSkuDroplet.PJPROMIS);
        Mockito.when(skuMockB.getPropertyValue(ESTConstants.SKU_MISC1)).thenReturn("skuCodeB");
        Mockito.when(skuMockB.getPropertyValue("displayName")).thenReturn("skuBDisplayName");
    }

So when you then call this within a test it will be something like this:

Mockito.when(someMethodThatReturnsAList).thenReturn(skuList);

So the key really is that you are not mocking the List but instead the contents of the List.