10009---Trail ~ Testing the Services
发布日期:2021-06-28 19:53:01 浏览次数:2 分类:技术文章

本文共 11147 字,大约阅读时间需要 37 分钟。

Motivation

In this step we describe how the Stadium Service is developed using TDD (Test-Driven Development). The StadiumService should present 

business-level methods to other services and clients. In this example, the Service's role is simply to call the StadiumDAO to persist and retrieve data.

 Therefore, the integration test will be quite similar to the DAO's integration test as the use-cases being tested will be the same. 

However, in this step we will also be writing a unit test that focuses its tests specifically on the StadiumService implementation, 

and will use Mockito to mock-out the classes on which the service depends. 

The context of the StadiumService in relation to the other elements of the trail is illustrated in this diagram:

In these steps we will write an integration test for the StadiumService and resolve the problems that arise to make the test pass. 

We will then write a unit test for the service, using Mockito to mock-out the service's dependencies - in particular to mock-out the StadiumDAO.

Write the integration test

Create the file cuppytrail/testsrc/de/hybris/platform/cuppytrail/impl/DefaultStadiumServiceIntegrationTest.java

package de.hybris.platform.cuppytrail.impl; import static org.junit.Assert.assertEquals;import static org.junit.Assert.assertNotNull; import de.hybris.bootstrap.annotations.IntegrationTest;import de.hybris.platform.cuppytrail.StadiumService;import de.hybris.platform.cuppytrail.model.StadiumModel;import de.hybris.platform.servicelayer.ServicelayerTransactionalTest;import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException;import de.hybris.platform.servicelayer.model.ModelService; import java.util.List; import javax.annotation.Resource; import org.junit.Before;import org.junit.Test;  @IntegrationTestpublic class DefaultStadiumServiceIntegrationTest extends ServicelayerTransactionalTest{     @Resource    private StadiumService stadiumService;    @Resource    private ModelService modelService;     private StadiumModel stadiumModel;    private final static String STADIUM_NAME = "wembley";    private final static Integer STADIUM_CAPACITY = Integer.valueOf(12345);     @Before    public void setUp()    {        // This instance of a StadiumModel will be used by the tests        stadiumModel = new StadiumModel();        stadiumModel.setCode(STADIUM_NAME);        stadiumModel.setCapacity(STADIUM_CAPACITY);    }     @Test(expected = UnknownIdentifierException.class)    public void testFailBehavior()    {        stadiumService.getStadiumForCode(STADIUM_NAME);    }     /**     * This test tests and demonstrates that the Service's getAllStadium method calls the DAOs' getAllStadium method and     * returns the data it receives from it.     */    @Test    public void testStadiumService()    {        List
stadiumModels = stadiumService.getStadiums(); final int size = stadiumModels.size(); modelService.save(stadiumModel); stadiumModels = stadiumService.getStadiums(); assertEquals(size + 1, stadiumModels.size()); assertEquals("Unexpected stadium found", stadiumModel, stadiumModels.get(stadiumModels.size() - 1)); final StadiumModel persistedStadiumModel = stadiumService.getStadiumForCode(STADIUM_NAME); assertNotNull("No stadium found", persistedStadiumModel); assertEquals("Different stadium found", stadiumModel, persistedStadiumModel); } }

Key points to note:

  • this test requires the StadiumService interface in order to compile. This interface will be written next.
  • the test is quite similar to the StadiumDAO test as it is testing similar functionality. The service is simply forwarding calls made to it on to the DAO that it wraps.

Write the interface

To make the test above compile we need to create the StadiumService interface. Create a new file called cuppytrail/src/de/hybris/platform/cuppytrail/StadiumService.java with the following code:

package de.hybris.platform.cuppytrail; import de.hybris.platform.cuppytrail.model.StadiumModel; import java.util.List; public interface StadiumService{    /**     * Gets all stadiums of the system.     *     * @return all stadiums of system     */    List
getStadiums(); /** * Gets the stadium for given code. * * @throws de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException * in case more then one stadium for given code is found * @throws de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException * in case no stadium for given code can be found */ StadiumModel getStadiumForCode(String code); }

Key points to note:

  • the interface is almost identical to the StadiumDAO interface.

Write the implementation

Copy the following code to cuppytrail/src/de/hybris/platform/cuppytrail/impl/DefaultStadiumService.java

package de.hybris.platform.cuppytrail.impl; import de.hybris.platform.cuppytrail.StadiumService;import de.hybris.platform.cuppytrail.daos.StadiumDAO;import de.hybris.platform.cuppytrail.model.StadiumModel;import de.hybris.platform.servicelayer.exceptions.AmbiguousIdentifierException;import de.hybris.platform.servicelayer.exceptions.UnknownIdentifierException; import java.util.List; import org.springframework.beans.factory.annotation.Required; public class DefaultStadiumService implements StadiumService{    private StadiumDAO stadiumDAO;     /**     * Gets all stadiums by delegating to {@link StadiumDAO#findStadiums()}.     */    @Override    public List
getStadiums() { return stadiumDAO.findStadiums(); } /** * Gets all stadiums for given code by delegating to {@link StadiumDAO#findStadiumsByCode(String)} and then assuring * uniqueness of result. */ @Override public StadiumModel getStadiumForCode(final String code) throws AmbiguousIdentifierException, UnknownIdentifierException { final List
result = stadiumDAO.findStadiumsByCode(code); if (result.isEmpty()) { throw new UnknownIdentifierException("Stadium with code '" + code + "' not found!"); } else if (result.size() > 1) { throw new AmbiguousIdentifierException("Stadium code '" + code + "' is not unique, " + result.size() + " stadiums found!"); } return result.get(0); } @Required public void setStadiumDAO(final StadiumDAO stadiumDAO) { this.stadiumDAO = stadiumDAO; }}

And the spring configuration:

Write the unit test

The integration test above is useful for demonstrating the expected behaviour of classes that implement the StadiumService interface. However it is not truly testing the expected functionality of our particular DefaultStadiumService class. To do that we need to mock out the dependencies (the StadiumDAO) which we do by using Mockito. Copy the following code to cuppytrail/testsrc/de/hybris/platform/cuppytrail/impl/DefaultStadiumServiceUnitTest.java

package de.hybris.platform.cuppytrail.impl;import static org.junit.Assert.assertEquals;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when; import de.hybris.bootstrap.annotations.UnitTest;import de.hybris.platform.cuppytrail.daos.StadiumDAO;import de.hybris.platform.cuppytrail.model.StadiumModel; import java.util.Arrays;import java.util.Collections;import java.util.List; import org.junit.Before;import org.junit.Test;  /** * This class belongs to the Source Code Trail documented at https://wiki.hybris.com/display/pm/Source+Code+Tutorial * * This test file tests and demonstrates the behavior of the StadiumService's methods getAllStadium, getStadium and * saveStadium. * * We already have a separate file for testing the Stadium DAO, and we do not want this test to implicitly test that in * addition to the StadiumService. This test therefore mocks out the Stadium DAO leaving us to test the Service in * isolation, whose behavior should be simply to wraps calls to the DAO: forward calls to it, and passing on the results * it receives from it. */@UnitTestpublic class DefaultStadiumServiceUnitTest{    private DefaultStadiumService stadiumService;    private StadiumDAO stadiumDAO;     private StadiumModel stadiumModel;    private final static String STADIUM_NAME = "wembley";    private final static Integer STADIUM_CAPACITY = Integer.valueOf(12345);     @Before    public void setUp()    {        // We will be testing StadiumServiceImpl - an implementation of StadiumService        stadiumService = new DefaultStadiumService();        // So as not to implicitly also test the DAO, we will mock out the DAO using Mockito        stadiumDAO = mock(StadiumDAO.class);        // and inject this mocked DAO into the StadiumService        stadiumService.setStadiumDAO(stadiumDAO);         // This instance of a StadiumModel will be used by the tests        stadiumModel = new StadiumModel();        stadiumModel.setCode(STADIUM_NAME);        stadiumModel.setCapacity(STADIUM_CAPACITY);    }     /**     * This test tests and demonstrates that the Service's getAllStadiums method calls the DAOs' getStadiums method and     * returns the data it receives from it.     */    @Test    public void testGetAllStadiums()    {        // We construct the data we would like the mocked out DAO to return when called        final List
stadiumModels = Arrays.asList(stadiumModel); //Use Mockito and compare results when(stadiumDAO.findStadiums()).thenReturn(stadiumModels); // Now we make the call to StadiumService's getStadiums() which we expect to call the DAOs' findStadiums() method final List
result = stadiumService.getStadiums(); // We then verify that the results returned from the service match those returned by the mocked-out DAO assertEquals("We should find one", 1, result.size()); assertEquals("And should equals what the mock returned", stadiumModel, result.get(0)); } @Test public void testGetStadium() { // Tell Mockito we expect a call to the DAO's getStadium(), and, if it occurs, Mockito should return StadiumModel instance when(stadiumDAO.findStadiumsByCode(STADIUM_NAME)).thenReturn(Collections.singletonList(stadiumModel)); // We make the call to the Service's getStadiumForCode() which we expect to call the DAO's findStadiumsByCode() final StadiumModel result = stadiumService.getStadiumForCode(STADIUM_NAME); // We then verify that the result returned from the Service is the same as that returned from the DAO assertEquals("Stadium should equals() what the mock returned", stadiumModel, result); }}

Note that:
  1. We are using  to mock out the StadiumDAO implementation that the service would usually use.
  2. As this mocks out a real DAO, the test requires no access to the hybris' persistence layer, and therefore does not need to extend ServicelayerTransactionalTest. Instead it is a simple POJO and will run very quickly.
  3. We are testing that the expected calls are made from the StadiumService to the StadiumDAO interface.
  4. No implementation of the StadiumDAO is needed when mocking out the StadiumDAO interface.

转载地址:https://blog.csdn.net/xxxcyzyy/article/details/51045820 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:10030---5分钟了解Mockito
下一篇:10008---Trail ~ Testing the DAO

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月12日 20时19分58秒