Expand my Community achievements bar.

How to mock CommerceHelper.findCurrentProduct(currentPage)

Avatar

Level 4

Hi Team,

How can we mock below piece of code-

        CommerceService commerceService = setCommerceService(requestContext.getSlingRequest());

        HybrisSession hybrisSession = setCommerceSession(requestContext.getSlingRequest(), response, commerceService);

        PageManager pageManager = resourceResolver.adaptTo(PageManager.class);

        com.day.cq.wcm.api.Page currentPage = setCurrentPage(requestContext.getSlingRequest(), pageManager);

        Product baseProduct = CommerceHelper.findCurrentProduct(currentPage).adaptTo(Product.class);

baseProduct is coming as null tried below piece of code  -

  @Mock

  protected CommerceService commerceService;

  @Mock

  protected HybrisSession commerceSession;

  @Mock

  private HttpSession sessionStore;

    @Mock

    private Node node;

  private RequestContext requestContext;

  @Mock

  Product hybrisProduct;

  @Before

  public void setup() throws Throwable {

  initMocks(this);

  requestContext = new RequestContext(request);

  when(componentContext.getPage()).thenReturn(page);

  when(requestContext.getSlingRequest().getResource()).thenReturn(resource);

  when(requestContext.getSlingRequest().getResourceResolver()).thenReturn(resourceResolver);

  when(request.getSession()).thenReturn(sessionStore);

  when(resource.adaptTo(CommerceService.class)).thenReturn(commerceService);

  when(commerceService.login(request, response)).thenReturn(commerceSession);

  when(resourceResolver.adaptTo(PageManager.class)).thenReturn(pageManager);

  when(pageManager.getContainingPage(request.getResource())).thenReturn(page);

  when(resource.adaptTo(Node.class)).thenReturn(node);

  when(hybrisProduct.getSKU()).thenReturn("1234");

  Resource resource = mockResource("/content/en/products/product",

  mockValueMap("cq:commerceType", "product"));

  when(resource.adaptTo(Product.class)).thenReturn(hybrisProduct);

  when(page.getContentResource()).thenReturn(resource);

}

  private ValueMap mockValueMap(final String key, final String value) {

  ValueMap valueMap = mock(ValueMap.class);

  when(valueMap.containsKey(key)).thenReturn(true);

  when(valueMap.get(key)).thenReturn(value);

  return valueMap;

  }

  private Resource mockResource(final String resourcePath, final ValueMap valueMap) {

  Resource resource = mock(Resource.class);

  when(resource.getPath()).thenReturn(resourcePath);

  when(resourceResolver.getResource(resourcePath)).thenReturn(resource);

  when(resource.getValueMap()).thenReturn(valueMap);

  return resource;

  }

Regards

0 Replies