How to write unit test for Hybris OCC controllers

浪子不回头ぞ 提交于 2020-12-15 03:43:23

问题


We are writing unit test for commerce webservices (OCC) controllers, for example CartsControllers, UsersController etc. Almost all the methods within these controllers return web service DTO i.e the ones that ends with *WsDTO. This object conversion is done by dataMapper which is part of spring web application context. The challenge we are facing is unit test or integration tests cannot access web application context and fetch the bean from there. 90% of commerce webservices (OCC) controller methods are not testable without this since they all return DTOs. Mocking dataMapper itself will not achieve anything since that will defeat the purpose of writing test.

Please help!!


回答1:


I can give some points on how you can start writing testcases for OCC controllers.

Lets say you want to test CartsControllers -> getCart method which you have written in your custom customlswebservices extension.

@RequestMapping(value = "/{cartId}", method = RequestMethod.GET)
@ResponseBody
public CartWsDTO getCart(@RequestParam(required = false, defaultValue = DEFAULT_FIELD_SET) final String fields)
{
    // CartMatchingFilter sets current cart based on cartId, so we can return cart from the session
    return getDataMapper().map(getSessionCart(), CartWsDTO.class, fields);
}

Integration Test :

import static org.fest.assertions.Assertions.assertThat;

@NeedsEmbeddedServer(webExtensions = { "customlswebservices", "oauth2" })
@IntegrationTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CartWebServiceIntegrationTest extends AbstractCoreIntegrationTest
{

   private WsSecuredRequestBuilder wsSecuredRequestBuilder;

   @Before
   public void beforeTest() throws Exception
   {
       wsSecuredRequestBuilder = new WsSecuredRequestBuilder() //
            .extensionName("customlswebservices") //
            .path("v2") //
            .client("trusted_client", "secret") //
            .grantClientCredentials();
   }

   @Test
   public void testGetCart()
   {
        final Response wsResponse = wsSecuredRequestBuilder //
            .path("electronics") // Put your custom wcms site here
            .path("users") //
            .path("test@test.com") // Add current user id here
            .path("carts") //
            .path("100038383") // Cart ID
            .queryParam("fields", "DEFAULT") //
            .build() //
            .get(); //

       assertThat(wsResponse).isNotNull();
       assertThat(wsResponse.getStatus()).isEqualTo(HttpServletResponse.SC_OK);

       final CartWsDTO cartWsDTO = wsResponse.readEntity(CartWsDTO.class);
       assertThat(cartWsDTO).isNotNull();
    }

  }

Hope this may help you.



来源:https://stackoverflow.com/questions/49860746/how-to-write-unit-test-for-hybris-occ-controllers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!