The path to continuous integration-unit test at the service layer

Source: Internet
Author: User

After completing the units at the data access layer, let's take a look at how to write a unit test at the service layer. The service layer should be the top priority of the entire system. The strict business logic design ensures the stable operation of the system, so the unit tests at this layer should also take a large proportion. Although unit tests should usually use mock to strip dependencies, the data access layer of the current project does not contain much logic because the spring-data framework is used, therefore, I put the service layer and data access layer in a pseudo unit test.

1. unit testing of general logic.

The method used here is almost the same as the data access layer, mainly including three steps:

1. Use @ databasesetup to specify the test Dataset

2. Execute the tested method

3. query the data verification result from the database through Dao

Assume that the code to be tested is as follows:

@ Service @ transactional (readonly = true) public class shopserviceimpl extends baseservice implements shopservice {private logger = loggerfactory. getlogger (shopserviceimpl. class); @ transactional (readonly = false) Public floor addfloor (string buildingname, int floornum, string layout) {// if the corresponding floor information already exists, an existing exception is thrown. Floor floor = floordao. findbybuildingnameandfloornum (buildingname, floornum); If (Floor! = NULL) {Throw new onlineshopexception (exceptioncode. shop_floor_existed);} // if the corresponding mall information does not exist, add the new mall building = buildingdao. findbyname (buildingname); If (Building = NULL) {building = new building (); Building. setname (buildingname); buildingdao. save (Building) ;}// add and return floor information floor = new floor (); floor. setbuilding (Building); floor. setfloornum (floornum); floor. setmap (layout); floordao. save (floor); Return floor ;}}

The corresponding interface is:

public interface ShopService {    public Floor addFloor(String buildingName, int floorNum, String layout);}

This logical code is very simple and straightforward, so the unit test to be written must contain all the branches:. the mall and floor information both exist, and an exception B is thrown. the mall exists, the floor does not exist, and the floor information is added. C. The mall and floor do not exist. All are added. The first case is used as an example to prepare test data:

<?xml version="1.0" encoding="UTF-8"?><dataset>    <building id="1" name="New House"/>    <floor id="1" building="1" floor_num="2"/></dataset>

Next, write a test case. Note that you must note that you must not forget:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:applicationContext-test.xml")@Transactional@TestExecutionListeners({        DependencyInjectionTestExecutionListener.class,        DirtiesContextTestExecutionListener.class,        CustomTransactionDbUnitTestExecutionListener.class,        ForeignKeyDisabling.class})public class ShopServiceTest {    @Autowired    private ShopService shopService;    @Test    @DatabaseSetup("shop/ShopService-addFloorExistException-dataset.xml")    public void testAddFloorExistException(){        try {            shopService.addFloor("New House", 2, "");            fail();        } catch(Exception e){            assertTrue(e instanceof OnlineShopException);            assertEquals(ExceptionCode.Shop_Floor_Existed.code(), ((OnlineShopException)e).getCode());        }    }}

This test is similar to the data access layer test.

2. Use mock objects to isolate third-party Interfaces

Software development usually involves integration with third parties, such as calling Sina certification and Baidu map. When writing tests, generally, these remote APIs are not called based on efficiency considerations (of course, other tests can detect changes to third-party interfaces in a timely manner ), it is assumed that they will always return the expected results. In this case, you need to use the mock object to simulate these APIs and generate corresponding results.

Here, I use mockito, which is very convenient to use. If a user needs to go to a third-party system for verification when logging on, let's take a look at how to test this scenario. Let's first look at the method to be tested:

private boolean validateUser(String inputName, String inputPassword) {        return thirdPartyAPI.authenticate(inputName, inputPassword);}

Thirdpartyapi is an API used by a third party for authentication. The test code is as follows:

Public class userservicetest {@ autowired private userservice; private thirdpartyapi mockthirdpartyapi = mock (thirdpartyapi. class); @ test public void testlogin () {// specifies the returned result when (mockthirdpartyapi of the specific operation of the mock object. authenticate ("jiml", "jiml ")). thenreturn (true); // use setter to replace the third-party dependency (userserviceimpl) userservice) initialized by spring with the mock object ). setthirdpartyapi (mockthirdpartyapi); Boolean loginstatus = userservice. login ("jiml", "jiml"); asserttrue (loginstatus );}}

In fact, there are not many new things to test the service layer. The most critical issue is how to test all the branches in the logic so that the test can truly safeguard the software quality.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.