Writing and Executing Tests

Familiarize yourself with the preferred practices for writing both the unit, and integration tests. Learn how to use JUnit tenant to execute tests.

Writing Unit Tests

When developing new software, a key programming practice is to write small, loosely coupled classes, with each one concentrating on one area of responsibility. Such classes are commonly referred to as Plain Old Java Objects, or POJOs. The Servicelayer follows this coding principle, and therefore consists of many POJOs. Each POJO implements an interface, and is wired to other POJOs using Spring's Dependency Injection. This approach enables you to easily isolate a class for testing by replacing dependent POJOs with mocks as described below.

Unit tests each focus on single POJOs. Consider the three POJOs as seen in the example below - POJO1, POJO2, and POJO3:

The Unit tests for POJO1 should test and demonstrate the behavior of POJO1 for expected and unexpected input. The Unit tests should not reference other dependent POJOs, such as POJO2 and POJO3. These POJOs should be mocked, which means they should be simulated with correct behavior. By focusing the tests on POJO1, the tests are able to:

  • Avoid false positives, for example, when a method in POJO1 has an error, but an error in POJO2 compensated for it and thus hid the error.

  • Avoid false negatives, for example, when POJO1 is working correctly, but an error in POJO2 causes the test to fail.

  • Run quickly, as POJO2 or POJO3 might have long-running methods, or even worse, require a SAP Commerce environment boot-up in which to run.

The main focus of Unit tests is to test the programmed code, and the content of the java class. The tests should check:

  • Each public method of the class with valid parameters

  • The same methods with illegal parameters, like NULL or negative values or values where exceptions are expected

  • If possible the test should cover all possible values accepted in the method body. For example if the method contains an if-then-else statement then if clause should be tested with a true and a false value, to make sure it covers the then clause and the else clause.

Other conventions to keep in mind include:

  • The Unit test class should be in the same package as POJO1, but is located in the test folder, typically /testsrc

  • The class name should be called POJO1Test

  • Each method should focus on testing one use-case, for example testFindUserWithNull(), testFindUserWithIncorrectCase()

  • The test code, variable names, and method names are intuitively named in order for commenting not to be necessary.

Mockito should be used to help to isolate a POJO for Unit testing. Mockito is a test framework that enables you to mock entire interfaces, entire classes, and parts of classes. In the example below, you can see how Mockito enables you to modify the behavior of a class without touching the class itself.

package de.hybris.mockito;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.LinkedList;

import org.junit.Test;

public class MockedLinkedList
{
	@Test
	public void testMockito()
	{
		// In this example mock the behaviour of LinkedList.
		// First step is to get a reference to a mocked LinkedList, by calling Mockito's mock method.
		final LinkedList mockedList = mock(LinkedList.class);

		// Tell mockito that if at a later stage mockedList.get(0) is called,
		// the real implementation should NOT called,
		// but instead the value "first" should be returned
		when(mockedList.get(0)).thenReturn("first");

		// Tell mockito that if at a later stage mockedList.get(1) is called,
		// the real implementation should NOT called,
		// but instead a RuntimeException should be thrown/
		when(mockedList.get(1)).thenThrow(new RuntimeException());

		// Now if you call mockedList.get(0), you will get the value "first"
		assertEquals("The call to LinkedList.get(0) is mocked and returns 'first'", "first", mockedList.get(0));
		System.out.println(mockedList.get(0));

		try
		{
			mockedList.get(1);
			fail("The call to LinkedList.get(1) is mocked and should have thrown a RuntimeException");
		}
		catch (final RuntimeException rte)
		{
			// The call to LinkedList.get(1) is mocked and threw a RuntimeException
		}

		// Call the method mockedList.get(999), which has not been stubbed,
		// and therefore calls the LinkedList's "real" get(999)
		assertEquals("The call to LinkedList.get(999) is not mocked so calls the genuine method", null, mockedList.get(999));
	}
}

Stubbing

To help you focus on testing a single POJO, you can replace any POJO on which it depends with stub implementation. A stub object is used to replace more heavy-weight objects on which an object under test usually depends. You could, for example, mock a method in POJO2 or POJO3 and simply return hard-wired responses. This enables you to speed up tests due to removing a dependency on slow POJOs, and to avoid the necessity to connect to the database. For example, if you fake a DAO finder method in POJO2. Stubbing is state verification, because it verifies if the state of the POJO is as expected.

Using Mockito you can stub out entire interfaces, entire classes, and parts of classes. The following code snippet presents different examples from Mockito:

// Two methods of the LinkedList class are mocked
// If you call any other method of LinkedList, it will call the original method, as stubs are provided only for only get(0) and get(1)
LinkedList mockedList = mock(LinkedList.class);

// Provide a stub, such that when mockedList.get(0) is called, the real implementation is NOT called,
// but instead directly returns the value "first"
when(mockedList.get(0)).thenReturn("first");

// Provide a stub, such that when mockedList.get(1) is called, the real implementation is NOT called,
// but instead directly throws RuntimeException
when(mockedList.get(1)).thenThrow(new RuntimeException());

// Call mockedList.get(0), which will invoke the stub and return "first"
System.out.println(mockedList.get(0));

// Call mockedList.get(1), which will invoke the stub and throw the RuntimeException
System.out.println(mockedList.get(1));

// Call the method mockedList.get(999), which has not been stubbed,
// and therefore calls the LinkedList's "real" get(999)
System.out.println(mockedList.get(999));

BDD Way of Stubbing

Behavior-driven development (BDD) focuses on obtaining a clear understanding of desired software behavior through discussion with stakeholders. It extends Test-driven development (TDD) by writing test cases in a natural language that non-programmers can read. Behavior-driven developers use their native language in combination with the ubiquitous language of domain driven design to describe the purpose and benefit of their code. Mockito provides a nice interface to write BDD-oriented tests with simple given/when/then scenarios. Below is sample test written in this manner. Notice the self-explanatory name of the test method with the prepending word, should.

@Test
public void shouldCreateSimpleDateFormatObjectOfGivenFormatForCurrentLocale()
{
	// given
	final String format = "yyyy-mm-dd";
	given(i18nService.getCurrentLocale()).willReturn(new Locale("en"));

	// when
	final DateFormat result = factory.createDateTimeFormat(format);

	// then
	assertThat(result).isNotNull();
	assertThat(result).isInstanceOf(SimpleDateFormat.class);
	verify(i18nService, times(1)).getCurrentLocale();
}

The idea of writing BDD tests is to write small test cases that cover one behavior.

Mocking

Mocking helps to verify a conversation. For example, if the sequence of methods calls between POJO1 and its dependent POJOs is as expected. It is usually done hand-in-hand with stubbing.

Mocking is a behavioral verification because it verifies if the behavior of the POJO is as expected. To use Mockito framework to perform the verification, follow the basic steps below:

  1. Create the POJO2 mock and then wire this mock instead of the original POJO2 in to POJO1.

  2. Call method A from POJO1, which you expect to call methods B and C from POJO2.

  3. Verify that POJO1 did call methods B and C from POJO2.

An example of verifying that calls to a mocked object are made:

import static org.mockito.Mockito.*;

// Create a mock of List interface
List mockedList = mock(List.class);
mockedList.add("one");
mockedList.clear();

// Verify that add and clear methods from List are called
verify(mockedList).add("one");
verify(mockedList).clear();

Mockito makes it easy to combine mocking and stubbing, which also enables you to perform state and behavioral tests on your services. See, for example, DefaultCompetitionServiceTest.java from the cuppy extension.

DefaultCompetitionServiceTest

package de.hybris.platform.cuppy.services;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import de.hybris.platform.cuppy.daos.CompetitionDao;
import de.hybris.platform.cuppy.model.CompetitionModel;
import de.hybris.platform.cuppy.services.impl.DefaultCompetitionService;
import de.hybris.platform.servicelayer.model.ModelService;

import java.util.Arrays;
import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class DefaultCompetitionServiceTest
{
	// The service under test..
	private DefaultCompetitionService competitionService;

	// Mock out the services/daos on which competition service depends using Mockito's mock annotation
	@Mock
	private PlayerService playerService;
	@Mock
	private ModelService modelService;
	@Mock
	private CompetitionDao competitionDao;

	@Before
	public void setUp()
	{
		// So that the @Mock annotations is recognised, you need the following line..
		MockitoAnnotations.initMocks(this);

		// Create the service and wire in the services/daos
		competitionService = new DefaultCompetitionService();
		competitionService.setPlayerService(playerService);
		competitionService.setModelService(modelService);
		competitionService.setCompetitionDao(competitionDao);
	}

	@Test
	public void testGetAllCompetitions()
	{
		// The purpose of this test is to check that..
		// CompetitionService's method getAllCompetitions makes a call to CompetitionDao's method findCompetitions
		// The value that  CompetitionService's method getAllCompetitions
		final CompetitionModel comp1 = new CompetitionModel();
		comp1.setCode("comp1");

		final CompetitionModel comp2 = new CompetitionModel();
		comp2.setCode("comp2");

		// Create a stub of competitionDao's method findCompetitions.  Should it be called, return a hard-wired response.
		// This helps you focus this test on CompetitionService, and not also on CompetationDAO, and also means you do not need
		// access to the persistence layer to test CompetitionService.

		when(competitionDao.findCompetitions()).thenReturn(Arrays.asList(comp1, comp2));  // <--- Example of Stubbing

		// Now call the service's method (which you expect to call findCompetitions)
		final List<CompetitionModel> result = competitionService.getAllCompetitions();
		// If it did call findCompeitions, then our hard-coded response will have been returned to the service.
		// and you can confirm that competiationService did what you expect with this hard-wired response
		assertEquals(2, result.size());
		assertEquals(comp1, result.get(0));
		assertEquals(comp2, result.get(1));
		
		// Finally confirm that the call to findCompetitions was made
		verify(competitionDao).findCompetitions(); // <--- Example of Behaviour Verification using Mocking
	}
}

Setting up Mocks Using Mockito

Mockito provides annotations that are helpful in making test classes simpler. For instance, if you have to test some service that is dependent on two other services and you want to test it in isolation, then you have to mock them. Instead of using setters on a tested service to provide mocked services, you can use @InjectMocks annotation like this:

@UnitTest
public class DefaultFormatFactoryTest
{
	@InjectMocks
	private final DefaultFormatFactory factory = new DefaultFormatFactory();
	@Mock
	private I18NService i18nService;
	@Mock
	private CommonI18NService commonI18NService;

	@Before
	public void setUp()
	{
		MockitoAnnotations.initMocks(this);
	}
}

Notice that the factory instance variable is initialized directly instead of doing it in the setUp() method. This speeds up whole test. The @InjectMock annotation injects all required mocks into the DefaultFormatFactory object in one call of MockitoAnnotations.initMocks(this), so there is no need to use set methods in setUp().

Code Coverage

Using stubbing and mocking gives the possibility to thoroughly test your POJOs. To know how complete the testing is, you need statistics of the code coverage. An easy way to determine this in the SpringSource Tool Suite using the EclEmma plugin:

  1. Download and install EclEmma.

  2. Right-click a test and run it by selecting Coverage As → JUnit Test.

  3. Select the class you are testing from the Coverage view, and spot the green covered code, and the red uncovered code.

The goal should be to maximize your test coverage, and this is much easier to do by Unit testing with mocks and stubs than by Integration tests only.

Writing Integration Tests

SAP Commerce provides the possibility to use a preconfigured, JUnit tenant where you can execute your JUnit tests isolated from other tenants. You can test your business functionality using real item instances.

Basic Mechanism

The easiest way to add specific functionality to your test class is to extend the ServicelayerTest class. In this way, you gain access to methods that create some very basic test items that can be used for testing. By extending the ServicelayerTest class, you may create instances of all basic SAP Commerce Models like language, currency, unit, and country using the createCoreData method. You may also import test data stored in a CSV file using the importCsv method, or import test data using the importStream() method. For more details, see the API documentation.

If you want to use other services in a test, you can inject them using the @Resource annotation. Use the @Before annotation to execute code or import data before each test method. Do not use the @Before annotation more than once in your test. All methods with this annotation are executed before each test method, but it is not clear in which order. For example, the Sun JDK executes them in 99% of all cases from top-to-down, whereas the IBM JDK executes them in an alphabetical order. To execute code or clean up data after each method, use the @After annotation. Do not use the @BeforeClass annotation as it is executed in a static way and is out of the test run scope. With this, a tenant is not set and changes are not reverted.

public class CreateUserTest extends ServicelayerTest 
{
  @Resource
  private ModelService modelService;

  @Resource
  private UserService userService;

  @Test
  public void testCreateUser()
  {
    //create a user
    final EmployeeModel user = new EmployeeModel();
    user.setUid("testUser");
    modelService.save(user);

    //test creation
    assertNotNull(userService.getUserForUID("testUser"));
  }

Pay attention to the static import of the Assert class of the JUnit framework, which makes all assert methods available in your test class. The listed import of the SAP Commerce de.hybris.platform.testframework.Assert class provides additional assert methods written by SAP Commerce. Extending a test class is not always suitable, for example, when already extending another class. In this case, you can easily add the functionality of the SAP Commerce test class using annotations, as done by the HybrisJUnit4Test too.

import static org.junit.Assert.*;
import static de.hybris.platform.testframework.Assert.*;

import de.hybris.platform.testframework.*;
import de.hybris.platform.jalo.ConsistencyCheckException;
import de.hybris.platform.servicelayer.i18n.commonI18NService;

import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(HybrisJUnit4ClassRunner.class)
@RunListeners({ ItemCreationListener.class, LogRunListener.class, PlatformRunListener.class })
public class MyTestClass
{
	@Test
	public void countryTest()
	{
		//because this class does not extend the ServicelayerTest class, 
		//Spring wiring does not work; you must get the service
		//over the registry application context
		CommonI18NService commonI18NService = Registry.getApplicationContext().getBean(CommonI18NService.class);
		
		CountryModel myCountry = commonI18NService.getCountry("en");
		assertNotNull(myCountry);
	}
}

All the additional logic is implemented using JUnit RunListener classes. Unfortunately, these listeners cannot be registered easily to the test process. Instead, you can use the HybrisJUnit4ClassRunner class, which has to be registered using the JUnit @RunWith annotation. This runner registers all listeners specified using the @RunListeners annotation. When using the ItemCreationListener class, all created items are removed after a test is finished. This kind of proprietary transaction system has several flaws. All creations of items are written persistent to the database and then removed, so you have no isolation in concurrent processing. Furthermore, only a creation of an item is registered, not a modification of an item. If you modify a standard meta item in your test, for example, if you change the write flag of an AttributeDescriptor, it will not be reverted at the end of the test. For more details about all available listeners and their usage, see the API documentation.

Preferred Mechanism

The preferred way of writing tests is to extend the ServicelayerTransactionalTest class. This class adds transaction-based isolation logic to your tests by registering the TransactionRunListener listener. Before the @Before method of your test is called, a new transaction is started. After the @After method of your test is called, a transaction rollback is performed. This assures complete isolation of your test. The ServicelayerTransactionalTest class extends the ServicelayerTest class, and therefore also provides the variables and methods of this class.

The following example demonstrates how to test a modification of the admin user. As the admin user already exists before the test starts, the modifications are not reverted when using the direct ServicelayerTest class, as only newly created items are tracked. By using the ServicelayerTransactionalTest class, all changes are reverted. Be aware that for testing logic using transactions with this test class can cause problems.

public class ModifyAdminTest extends ServicelayerTransactionalTest
{
        @Resource
        private ModelService modelService;

        @Resource
        private UserService userService;

	@Test
	public void modifyAdminTest() 
	{
		UserModel admin = userService.getAdminUser();
                admin.setName("test");
                modelService.save(admin);
                assertEquals("test",admin.getName());
	}
}

You also can add the transaction logic using annotations in the same way as described in Basic Mechanism section:

@RunWith(HybrisJUnit4ClassRunner.class)
@RunListeners({TransactionRunListener.class, ItemCreationListener.class, LogRunListener.class, PlatformRunListener.class })
@Transactional
public class MyTestClass
{
      // ...
}

The additional TransactionRunListener listener is registered. This listener enables the transaction support if the annotation @Transaction is found. The @Transactional annotation can be specified on a class or method level, so you can enable the transaction support for separate methods. This is also the reason for registering the ItemCreationListener. If no transactional support is enabled, because the @Transactional annotation is missing or the underlying database does not support transactions, the proprietary mechanism is used.

Be aware that if you want to test transaction functionality, for example, assuring the correctness of a rollback, you cannot use the transactional support.

Annotations

The table below presents available class annotations for inclusion in Java test files. They are used as labels to help generate Bamboo scripts that automatically select and run tests of particular types.

Annotation

Usage

@IntegrationTest

Tests that are to be executed inside an application server environment, like Apache Tomcat or WebSphere.

@DemoTest

Typically well or self-documented Integration tests for inclusion in SAP Commerce Wiki and available to partners.

@UnitTest

Tests that do not require a SAP Commerce environment in which to run, and are therefore fast. Unless your test needs the SAP Commerce environment, for example, because of the persistence layer, then you should consider writing a unit test instead with mocked-out dependencies.

@PerformanceTest

A performance test can be configured to run under different circumstances, for example:

  • 6000 times in a row,

  • with 1 mio items,

  • under heavy load

    It is designed for helping to examine performance characteristics.

@ManualTest

Some tests require external software, for example the CyberSource tests. These tests should not be executed during automated testing.

Testing Exceptions

Follow the rules below when writing tests:

  1. Do not use @Test(expected). This feature can potentially make a few tests cleaner, but is really error-prone:

    @Test(expected=Exception.class)
    public void testSomething() {
      //line 1: throws NullPointerException
      //lines 2-30: some test code
    }

    If due to some bug in the setup, the test method breaks in the first line, most of the test code is not even executed. The expected exception hides this issue and the test is green, so it is completely useless.

  2. If you violate the rule above, then at least the exception should be very specific. For example:

    @Test(expected=BreadOutOfStockException.class)
    public void shouldBuyBread() {}

    Even if you use a specific exception, the test does not document exactly where the exception is thrown. Sometimes it may lead to subtle bugs. Therefore, if the test method has multiple lines, do not violate the #1 rule. Instead, you can simply write:

    @Test
    public void shouldBuyBread() throws Exception {
      //given
      me.goToBakery(bakery);
      bakery.setBreadAmount(0);
    
      try {
        //when
        me.buyBread();
        //then
        fail("BreadOutOfStockException to be thrown");
      } 
      catch (BreadOutOfStockException e) {
         //ok here, we expect this exception here
      }
      catch (Exception e) {
        fail(" caught unexpected exception: "+e);
      }
    }

Executing Tests

Use JUnit tenant to execute tests. When you update to the newer version of SAP Commerce, you also should configure new extensions for the JUnit tenant. Follow the steps below to make sure that all needed extensions are enabled, and to initialize JUnit tenant:

  1. Open the SAP Commerce Administration Console.

  2. Go to the Platform tab and select Tenants option.

  3. The Tenants Overview page displays a list of existing tenants. Click the View button next to the JUnit tenant.

  4. On the Edit Tenant page, check if all extensions are enabled.

  5. Now initialize the JUnit tenant. Click the Initialize button.

  6. The JUnit tenant activates and Initialization page displays.

  7. Click the Initialize button.

Furthermore, you can initialize SAP Commerce by calling ant yunitinit from the command prompt or calling the Initialization.initializeTestSystem() within a standalone class. All three variants initialize the test system with a minimum data containing no essential data and no project data of installed extensions. If you want to set up essential or project data of a specific extension in your @Before method, you can execute the following code:

// creating essential data of MyExtension
MyExtensionManager.createEssentialData(Collections.EMPTY_MAP, null);
// creating project data of MyExtension
MyExtensionManager.createProjectData(Collections.EMPTY_MAP, null);

For creating essential data of the core extension, you should execute:

new CoreBasicDataCreator().createEssentialData(Collections.EMPTY_MAP, null);

You are not able to use ImpEx on the initialized test system because of missing encodings. You can install them by creating essential data of the core extension or by installing the encodings directly:

new CoreBasicDataCreator().createSupportedEncodings();

There are three different ways of executing tests:

  • Using Eclipse

  • Using Ant

  • Using the Test Servlet

Eclipse

To execute a test using the Eclipse, follow below instructions:

  1. Right-click your test class.

  2. From the context menu, select Run As, and click JUnit Test

You may get:

  • Warnings like below:

    WARN  [Utilities] cannot load extension storefoundation because:
    java.lang.ClassNotFoundException: ystorefoundationpackage.jalo.YStoreFoundationManager
    WARN  [Utilities] If you receive this error while starting from eclipse,
    you need to add the project that
    WARN  [Utilities] contains the storefoundation extension to the java build path of your project from where you have
    WARN  [Utilities] started this class. (project->right click->properties->build path->tab Projects.
    WARN  (junit) [ComposedTypeEJBImpl] missing jalo class
    'de.hybris.platform.xprint.jalo.PurgeGettersJob' for item type 'XPurgeGettersJob' - trying supertype class instead
  • Exceptions like below:

    java.lang.ClassNotFoundException:
    de.hybris.platform.webfoundation.jalo.workflow.orderprocess.OrderProcessingBatchJob

If this is the case, you probably do not have all configured extensions of your localextensions.xml file registered at the classpath of the Eclipse JUnit test configuration. To fix it, perform the following steps:

  1. Open the Run menu click Run Configurations to open Run Configurations dialog box.

  2. In the Run Configurations dialog box, select your test configuration.

  3. Navigate to the Classpath tab.

  4. Select the platform folder.

  5. Click the Add Projects button. In the Project Selection dialog box, select all extensions you have configured in the localextensions.xml file.

If your Spring configuration does not get bootstrapped at the startup of the Platform, the Spring file is probably not a part of test classpath. This can either be caused by a missing project at the classpath, or by not including your resources folder in the Eclipse classpath at all. Assure that your .classpath file contains the following line:

<classpathentry exported="true" kind="lib" path="resources"/>

Ant

All ant targets can be executed in the platform folder or in the specific extension directory. If you execute a target inside an extension directory, the extension filter is added automatically for the current extension.

Ant Targets

List of available ant targets:

Ant Call

Description

ant alltests

Executes all tests found by testClassesUtil.getAllTestClasses()

ant unittests

Executes all tests found by testClassesUtil.getAllUnitClasses()

ant demotests

Executes all tests found by testClassesUtil.getAllDemoClasses()

ant integrationtests

Executes all tests found by testClassesUtil.getAllIntegrationClasses()

ant performancetests

Executes all tests found by testClassesUtil.getAllPerformanceClasses()

ant manualtests

Executes all tests found by testClassesUtil.getAllManualClasses()

Commandline Modifiers

If you want to specify an ant target a bit more, you can pass one or more of these properties to the ant call:

Modifier

Example

Description

testclasses.extensions

ant unittests -Dtestclasses.extensions=basecommerce,core

executes all tests from given extensions

testclasses.annotations

ant alltests -Dtestclasses.annotations=demotests,unittests,manualtests

executes tests with given annotations

testclasses.packages

ant unittests -Dtestclasses.packages=de.hybris.platform.payment.*

executes tests from given package

testclasses.split

ant alltests -Dtestclasses.split=1-3

Divides the number of tests by the second number, and executes the part indicated by the first number. For example, a split=1-5 executes the first 20% of the tests.

-Dtestclasses.suppress.junit.tenant

ant unittests -Dtestclasses.suppress.junit.tenant=true

switches off starting up of Platform for every test

Like all other ant properties, these properties are set once and cannot be modified anymore. If you call ant demotests -Dtestclasses.annotations=unittests, all UnitTests are executed.

Including and Excluding Tests

For more information, see -Dtestclasses.packages in Customizing Test Execution.

WebServices Tests

Use the ant target -allwebtests to run all tests inside the web/testsrc folder.

Ant Callbacks

If you want to provide custom logic before or after test execution, or initialization, you can write a buildcallback in buildcallbacks.xml of your extension:

Callback Name

When it is Performed

(extension_name)_before_yunit

Performed right before test execution

(extension_name)_after_yunit

Performed right after test execution, if tests succeed

(extension_name)_before_yunitinit

Performed right before the test framework is initialized

(extension_name)_after_yunitinit

Performed right after the test framework is initialized

An example below creates essential data of core extension right after the initialization of the test system. It uses the yrun macro that starts the Platform and executes the given code as BeanShell command. The first line of the code sets the tenant of test system, the second call creates the essential data of core, and last statement shuts down the Platform.

<macrodef name="(extension_name)_after_yunitinit">
  <sequential>
   <yrun>
    de.hybris.platform.core.Registry.setCurrentTenantByID("junit");
    new de.hybris.platform.jalo.CoreBasicDataCreator().createEssentialData(null,null);
    de.hybris.platform.util.RedeployUtilities.shutdown();
   </yrun>
  </sequential>
 </macrodef>

Test Servlet

For information on SAP Commerce JUnitEE TestRunner, see The SAP Commerce Testweb Front End.