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

本文共 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月23日 05时41分44秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

安卓app开发环境搭建!Android最强保活黑科技的最强技术实现,完整PDF 2019-04-29
安卓app软件开发教程!免费Android高级工程师学习资源,值得收藏! 2019-04-29
安卓chrome插件开发!Android架构师教你如何突破瓶颈,跳槽薪资翻倍 2019-04-29
安卓rom开发教程!跟Android初学者分享几点经验,写给正在求职的安卓开发 2019-04-29
原理解析!2021年教你增加拿到BAT等大厂offer几率,offer拿到手软 2019-04-29
原生安卓开发!驱动核心源码详解和Binder超系统学习资源,实战篇 2019-04-29
大牛手把手带你!2021年Android进阶者的新篇章,完整PDF 2019-04-29
太牛了!Android程序员最大的悲哀是什么?面试真题解析 2019-04-29
作为字节跳动面试官,BAT这种大厂履历意味着什么?赶快收藏备战金九银十! 2019-04-29
大牛深入讲解!Android面试中常问的MMAP到底是啥东东?再不刷题就晚了! 2019-04-29
太赞了!你会的还只有初级安卓工程师的技术吗?3面直接拿到offer 2019-04-29
腾讯Android开发面试记录,安卓系列学习进阶视频 2019-04-29
阿里P8架构师的Android大厂面试题总结,醍醐灌顶! 2019-04-29
阿里、腾讯大厂Android面试必问知识点系统梳理,满满干货指导 2019-04-29
阿里大神最佳总结Flutter进阶学习笔记,内容太过真实 2019-04-29
阿里巴巴内部Jetpack宝典意外流出!送大厂面经一份! 2019-04-29
阿里正式启动2021届春季校招!字节跳动Android面试凉凉经,实战解析 2019-04-29
阿里珍藏版Android框架体系架构手写文档,原理+实战+视频+源码 2019-04-29
零基础也能看得懂!2021中级Android开发面试解答,附赠课程+题库 2019-04-29
震惊!靠着这份面试题跟答案,复习指南 2019-04-29