10009---Trail ~ Testing the Services
2016-04-02 22:51
537 查看
Motivation
In this step we describe how the Stadium Service is developed using TDD (Test-Driven Development). The StadiumService should presentbusiness-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.javapackage 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; @IntegrationTest public 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<StadiumModel> 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<StadiumModel> 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.javapackage 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<StadiumModel> 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<StadiumModel> 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:
<alias name="defaultStadiumService" alias="stadiumService"/> <bean id="defaultStadiumService" class="de.hybris.platform.cuppytrail.impl.DefaultStadiumService"> <property name="stadiumDAO" ref="stadiumDAO"/> </bean>
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 needto 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. */ @UnitTest public 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<StadiumModel> 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<StadiumModel> 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:
We are using Mockito to mock out the StadiumDAO implementation that the service would
usually use.
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.
We are testing that the expected calls are made from the StadiumService to the StadiumDAO interface.
No implementation of the StadiumDAO is needed when mocking out the StadiumDAO interface.
相关文章推荐
- 217. Contains Duplicate
- 理解支持向量机(四)LibSVM工具包的使用
- 10008---Trail ~ Testing the DAO
- 分类模型的性能评估——以SAS Logistic回归为例(3): Lift和Gain
- hdu 2476 String painter 区间dp 难
- tail -f -F是个好东西
- idea修改文件名后出现main method should be static错误
- Design Pattern Explained 读书笔记二——设计模式序言
- 【POJ1765】November Rain——扫描线+线段树
- LeetCode. Container With Most Water
- IBM openblockchain学习(三)--Ledger源码分析
- 【LeetCode】220. Contains Duplicate III
- error: command 'gcc' failed with exit status 1 的解决办法
- RAID5工作原理介绍
- 219. Contains Duplicate II
- LeetCode 336. Palindrome Pairs
- DrawableContainer
- lintcode-medium-Number of Airplanes in the Sky
- 使用MacBook Air的4项基本技巧
- Xenomai on the Beaglebone Black in 14 easy steps ---fwqlzz love is for ever