OCC controllers in SAP Commerce are rarely covered by tests that run them with their real configuration. For that reason a misconfigured data mapper or a broken controller mapping shows up only after the server is started and a real request is sent. SAP Commerce already ships test support, which runs this whole chain inside a JUnit test, and below is a recipe for using it.
Problem Description
Regular tests do not reach an OCC controller due to the way SAP Commerce splits its Spring contexts. A regular @IntegrationTest without an embedded server runs on the core application context of the platform, which holds services and facades. Controllers, the DataMapper and its field level mappings are defined in the web application context of commercewebservices, which is loaded from WEB-INF/config/v2 and from the occ/v2/*occ/web/spring/*-web-spring.xml files of custom extensions. For that reason the deepest point such a test reaches is the facade. A unit test can create a controller, but it has to mock the DataMapper, and the mock replaces exactly the configuration, which needs to be tested.
The most common OCC bug in my experience lives right there, in the configuration of the data mapper. WsDTO properties live in *-beans.xml, while field level mappings, field mappers and converters live in Spring XML, and no build step checks that these files agree. If a mapping entry is missing, nothing fails: the field is just absent from the response, and a wrong type fails only when a request is mapped. Suppose a new property is added to CartWsDTO, and the populator sets it correctly, but the property is not listed in the FULL level of the cart field level mapping. Then ?fields=FULL returns the response without it, and the bug looks identical to a persistence failure, so debugging starts in the wrong place. For Spartacus-based projects such a missing field breaks a page of the storefront, because Spartacus reads the exact shape of the response.
Next come mistakes in the mapping of controllers, which are found just as late as a misconfigured data mapper. An OOTB endpoint is overridden via @RequestMappingOverride, and if the annotation is forgotten, the OCC servlet fails to start with an ambiguous mapping error. If its priority is too low, the OOTB controller keeps handling the request without any error. A clash of class names is even harder to spot, because OOTB controllers and custom ones are loaded into two different Spring contexts. A custom controller with the same simple class name as an OOTB one, for example PaymentModesController, gets the same bean name, and Spring raises no conflict across the two contexts. In my case the OOTB bean hid the custom one, so the endpoints of the custom controller returned 404 with UnknownResourceError and no error in the logs. Broken OAuth2 configuration and a custom BaseSiteFilter, which rejects a valid request, fail in the same chain, even before the controller is reached. All of them are found only by a real request against a started server.
For such failures SAP Commerce already has an answer in the test support of the webservicescommons extension. It starts an embedded Tomcat inside a JUnit test and sends real HTTP requests to it, and the platform uses it for the tests of its own web services.
Technical Solution
The main idea is to start an embedded Tomcat with the commercewebservices and oauth2 web extensions, send a real HTTP request to an OCC endpoint and assert on the response. Such a test loads the web application context and runs the full chain of a real request: routing, security filters, the controller, the data mapper and serialization.
For that purpose de.hybris.platform.webservicescommons.testsupport package provides:
@NeedsEmbeddedServer: annotation, which starts and stops embedded Tomcat around the test classWsRequestBuilder: builds plain HTTP requests for public endpointsWsSecuredRequestBuilder: builds OAuth2-secured HTTP requests (resource owner password or client credentials)WebservicesAssert: asserts on HTTP status codes and security headers
Test class extends ServicelayerTest to get access to createCoreData() and importCsv() helpers, what allows to load required impex data inside @Before. External dependencies, which require a running server (Solr, payment gateways), are stubbed via ReflectionTestUtils after the server has started.
Implementation Details
Test class skeleton
|
|
@NeedsEmbeddedServer accepts a list of web extensions. For OAuth-secured endpoints OAuth2Constants.EXTENSIONNAME (which resolves to oauth2) must be included, otherwise token endpoint would not be available. The annotation is not inherited, so it must be declared on every concrete test class. On an abstract base class it is silently ignored, and the first request fails with Connection refused.
Web extension name passed into WsRequestBuilder must match the deployed servlet, not the extension, in which the controller class lives. In modern OCC projects all custom controllers are deployed under commercewebservices via component scan, so this value stays the same regardless of the extension, in which the controller is located. Webroot resolves to /occ, so endpoint paths start with v2/{baseSiteId}/....
Required test data
Embedded Tomcat does not magically populate the database. All data, which is required by request handling chain, must be created in @Before. Bare minimum for any OCC test is:
BaseSite: resolves{baseSiteId}path variableBaseStore: linked to the base site, drives currency and language resolutionCatalogandCatalogVersion: many OOTB interceptors expect a default product catalog to exist
|
|
For Solr-dependent endpoints SolrIndexedType entries must be created. For OAuth-secured endpoints additional records are required, which are described below.
Public endpoint test
For unsecured endpoints WsRequestBuilder is enough. It produces JAX-RS Invocation.Builder, which can be used to issue any HTTP method and assert on the response:
|
|
response.bufferEntity() is mandatory before any further reads, otherwise the second access to the entity stream would fail. WebservicesAssert.assertResponse checks both HTTP status and presence of standard SAP Commerce security headers: X-FRAME-Options, X-XSS-Protection, X-Content-Type-Options, Strict-Transport-Security. This helps to catch misconfigured headers in custom filters or web.xml.
OAuth2-secured endpoint test
For secured endpoints WsSecuredRequestBuilder performs the OAuth2 dance before the actual request. Resource owner password credentials grant is most common for customer-facing endpoints:
|
|
Required impex data for OAuth2-secured tests:
|
|
Two points of this data are not obvious. First, authorizedGrantTypes must include password for resource owner credentials, and also client_credentials, if any client-only endpoints are tested. Second, customer password must be set as a regular column (no & prefix), because &password is an impex attribute alias and does not actually persist the value.
Asserting on persisted state
Some controllers accept input and persist data, returning only an identifier. To verify the actual persisted state, Registry.getApplicationContext() can be used to retrieve any service bean and load the entity from DB:
|
|
Such two-level assertion catches cases, when controller returns success status, but populator skipped a critical field, what would result in a broken record in DB. The HTTP status alone says nothing about such a field, and the response holds only the fields of its level mapping, so the record in DB is the only place where the outcome of the request is fully visible.
Stubbing external services
External dependencies, like Solr behind the suggestions endpoint above or payment gateways, can not be hit from an integration test. Standard Mockito approach with @InjectMocks does not work, because @NeedsEmbeddedServer starts the server before @Before runs, so all controller fields are already injected with real beans at that point.
Bean alias replacement via loadBeanDefinitions also does not affect already-injected controller fields. The only working approach is to mutate state on existing singleton beans at the right depth.
For Solr autocomplete pipeline this means replacing solrAutoSuggestService field inside the existing autocompleteService bean via ReflectionTestUtils. Such approach keeps facade and autocomplete logic intact, only the actual Solr call is stubbed:
|
|
Original implementation must be restored in @After, because singleton bean state survives between test classes. Without restoration the next test class would inherit the stub and fail in confusing ways.
Stub itself implements the same interface and returns a static map of inputs to expected responses:
|
|
Running the tests
Tests are executed with regular ant integrationtests target:
|
|
Test results are written to core-customize/hybris/log/junit/TESTS-TestSuites.xml. Embedded server adds noticeable startup overhead per test class, so it is preferable to group related tests into a single class instead of creating separate class per endpoint.
P.S. -Dtestclasses.suppress.junit.tenant=true flag does not work for @NeedsEmbeddedServer tests. It is intended for unit tests, which do not need DB. Embedded server requires full platform startup, including DB and tenant initialization.
P.P.S. Each call to WsSecuredRequestBuilder.build() performs a full OAuth2 token request against the embedded server. There is no token caching inside the builder. For tests with many requests as the same user, the Invocation.Builder returned by build() should be reused, otherwise every assertion pays the cost of a fresh OAuth round trip.
P.P.P.S. For controllers, which depend on the current cart, custom CartRestorationStrategy implementations may interfere with the standard DefaultCartLoaderStrategy flow. If CommerceCartParameter.allowRestoration is false, the session cart is never set, and checkCartExpiration always reports the cart as expired. Such behavior must be either fixed in production code or worked around in test setup by directly setting the cart on the session.