How to write unit tests-based on spring

Source: Internet
Author: User
Tags addall

Unit Test

First unit testing really is a kind of "dirty live dirty", but I personally feel it is necessary, at least I recently began to write unit test still can find some "bug".

How to write unit tests

Requirements for unit Testing ... Online a lot. Let's share how I write unit tests. First of all, our project is generally MVC layered, and unit testing is written mainly on the DAO layer and service layer. From the project structure, the service layer is dependent on the DAO layer, but from the unit test point of view, all of the classes that he relies on should be mocks when a service is unit. The DAO Layer unit test is relatively simple (the following DAO layer takes JDBC as an example) and relies only on data in the database.

DAO Layer Unit Test.

DAO layer Unit test must be connected to the database, but do not need a local MySQL, you can use the H2 memory database to do a single test is sufficient.

Actual combat

First, give a generic template, that is, all the DAO layer unit tests will be used, note: ORM use MyBatis

@RunWith (Springrunner.class) @ContextConfiguration (Classes= {Xxxdaotest.mybatisscanconfiguration.class}) Public classXxxdaotest {@MapperScan ({"Com.xxx.xxx.mapper"}) @TestConfiguration @EnableTransactionManagement Public Static classmybatisscanconfiguration {@Bean Publicxxxdaotest Xxxdao () {return NewXxxdaoimpl (); } @Bean PublicDataSource H2datasource () {Embeddeddatabasebuilder builder=NewEmbeddeddatabasebuilder (); Embeddeddatabase Database=Builder.settype (EMBEDDEDDATABASETYPE.H2). Addscript ("Classpath:/xxx/init_table.sql")//Initialize the Build table statement at startup. Build (); returndatabase; } @Bean PublicSqlsessionfactory sqlsessionfactory (DataSource DataSource)throwsException {FinalSqlsessionfactorybean sessionfactory =NewSqlsessionfactorybean ();            Sessionfactory.setdatasource (DataSource); Pathmatchingresourcepatternresolver Resolver=NewPathmatchingresourcepatternresolver (); //load all SQL Mapper filesresource[] mapperlocations = resolver.getresources ("Classpath:com/xxx/xxx/xxxxmapper.xml");            Sessionfactory.setmapperlocations (mapperlocations); returnSessionfactory.getobject (); } @Bean PublicPlatformtransactionmanager Platformtransactionmanager (DataSource DataSource) {return NewDatasourcetransactionmanager (DataSource); } @Bean Publicjdbctemplate JdbcTemplate (DataSource DataSource) {return NewJdbcTemplate (DataSource); }    }         Public voidClearAll () {Jdbctemplate.execute ("DELETE from XXX"); }}

Some of these need to be slightly modified, I use "xxx" or "xxx", if the match with spring must know how to do. Where Init_table.sql is used to create database tables, it is not listed, the following need to note:

    1. H2 database Some syntax is not supported, such as insert ignore, and similar to when creating a database "Current_timestamp on UPDATE current_timestamp"
    2. If some SQL is not provided by Mapper, then you can use JdbcTemplate to perform, such as the ClearAll () method above
    3. After each unit test execution, it is recommended to delete the table used in the current unit test
    4. If the current DAO layer has other dependencies, it can actually be mock (you can refer to the unit test behind the service layer)
    5. If you see strange classes or methods, don't be surprised, I may not be sensitive.

General template After writing, you can follow different circumstances to write a single test, think is not very happy AH

@Test Public voidtestupdatexxx () {clearAll (); Long Testuserid= 1L; //1. When the data does not exist, return 0        inti = xxxdao.updatexxx (testuserid,1); Assert.asserttrue (i= = 0); //2. If there is a record, the status is completed return 0Domain domain = createby (testuserid, 0); //Insert a piece of datamapper.insertselective (domain); Assert.asserttrue (Xxxdao.updatexxx (Testuserid,1) = = 0); //3. If there is a record, the status is not completed return 1        ....    }

Service Layer Unit Test

To be honest, the service layer of the single test is the most troublesome, especially the kind of super big method. Unit testing of the service layer is the main mock of other dependent beans to complete various logic judgments.

Actual combat

or first give a template

@RunWith (Springrunner.class) @ContextConfiguration (Classes= Needtestservice.config.class) Public classneedtestservicetest {@TestConfiguration Public Static classConfig {//create a class to test directly here@Bean PublicNeedtestservice Needtestservice () {return NewNeedtestservice (); }    }        /** mock off the dependent bean*/@MockBeanPrivateX1dao X1dao; @MockBeanPrivateX1service X1service; //This is the class autowired needs to test.@AutowiredPrivateNeedtestservice Needtestservice; }

Generic templates on top, of course, it is possible to mock more than 10 beans if you encounter a disgusting class. Now it's fun to write unit tests, for example

@Test Public voidtestCalculateUserClaims1 () {Long Testuserid= 1L; Date Transtime= Dateutil.getstartdate (NewDate ()); Given (X1dao.insertinitignore (Testuserid, Transtime)). Willreturn (1); List<X2> list =lists.newarraylist (); List.addall (Createtendercell (1L, "100.00", 10)); List.addall (Createtendercell (2 L, "200.00", 5));        Collections.shuffle (list);                Given (X1dao.selectxxx (Testuserid, Transtime)). Willreturn (list); ... Change the case of various dependent method calls back to mock out,//the method that is tested is called directly hereResult result =Needtestservice.needtestmethod (...) Assert.asserttrue (Result!=NULL); //... Omit various Assert.           }

Of course, this is only a situation, there are a variety of situations that require you to test, good luck!

Summary

I also recently began to write unit tests, although very brain-free, but I personally think it is necessary, some very low-level errors can at least find out (if you write a little more carefully, rather than perfunctory). It's a lot better than being pointed out in code review. and writing unit tests is a kind of rest!

How to write unit tests-based on spring

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.