Getting Started with SPRING+JUNIT4 unit testing

Source: Internet
Author: User
Tags assert

(i). JUnit Introduction

JUnit is the most well-known unit testing framework in Java, and most Java development environments have integrated JUnit as a unit test tool. Good unit testing can greatly improve development efficiency and code quality.

Maven Imports JUnit, sprint-test, Json-path related test packages, and configures Maven-suerfire-plugin plug-ins, editing pom.xml

    <Dependencies>        <!--Test Unit -        <Dependency>            <groupId>Junit</groupId>            <Artifactid>Junit</Artifactid>            <version>4.12</version>            <Scope>Test</Scope>        </Dependency>        <Dependency>            <groupId>Org.springframework</groupId>            <Artifactid>Spring-test</Artifactid>            <version>4.3.10.RELEASE</version>            <Scope>Test</Scope>        </Dependency>        <!--JSON assertion Test -        <Dependency>            <groupId>Com.jayway.jsonpath</groupId>            <Artifactid>Json-path</Artifactid>            <version>2.4.0</version>            <Scope>Test</Scope>        </Dependency>    </Dependencies>    <Build>        <Plugins>            <!--Unit Test Plug-in -            <plugin>                <groupId>Org.apache.maven.plugins</groupId>                <Artifactid>Maven-surefire-plugin</Artifactid>                <version>2.20</version>                <Dependencies>                    <Dependency>                        <groupId>Org.apache.maven.surefire</groupId>                        <Artifactid>Surefire-junit4</Artifactid>                        <version>2.20</version>                    </Dependency>                </Dependencies>                <Configuration>                    <!--whether to skip the test -                    <skiptests>False</skiptests>                    <!--Exclude Test Classes -                    <excludes>                        <Exclude>**/base*</Exclude>                    </excludes>                </Configuration>            </plugin>        </Plugins>    </Build>

(b). Service Layer Test Example

Create service layer test base class, new Baseservicetest.java

 //  Configure the test environment in spring  @RunWith ( Springjunit4classrunner. class  )  //  Specify Spring's profile path  @ContextConfiguration (locations = {"Classpath*:/spring/applicationcontext.xml") })  //  test class open transaction , the transaction manager needs to be specified, and when the default test is complete, the database operation automatically rolls back the  @Transactional (TransactionManager = "TransactionManager" )  //  Specifies that database operations are not rolled back , optional  @Rollback (value = false   public  class   Baseservicetest {}  

Test UserService class, new test class Userservicetest.java

 Public classUserservicetestextendsBaseservicetest {Private Static FinalLogger Logger = Loggerfactory.getlogger (userservicetest.class); @ResourcePrivateUserService UserService; @Test Public voidTestget () {Userdo Userdo= Userservice.get (1);        Assert.assertnotnull (Userdo);        Logger.info (Userdo.getusername ()); //Adding validation assertionsAssert.assertequals ("Testget Faield", "Google", Userdo.getusername ()); }}

(iii). Controller Layer Test Example

Create a controller layer test base class, new Basecontrollertest.java

//Configure the test environment in spring@RunWith (Springjunit4classrunner.class)//Specifies that the ApplicationContext used by the test environment is of type Webapplicationcontext//value specifies the root of the Web App@WebAppConfiguration (value = "Src/main/webapp")//specifying the Spring container hierarchy and configuration file path@ContextHierarchy ({@ContextConfiguration (name= "Parent", locations = {"Classpath*:/spring/applicationcontext.xml"}), @ContextConfiguration (name= "Child", locations = {"Classpath*:/spring/applicationcontext_mvc.xml"})})//The test class opens the transaction, requires the transaction manager to be specified, and the database operation is automatically rolled back after the default test is completed@Transactional (TransactionManager = "TransactionManager")//Specifies that database operations are not rolled back, optional@Rollback (value =false) Public classbasecontrollertest {}

Test Indexcontroller class, new test class Indexcontrollertest.java

 Public classIndexcontrollertestextendsBasecontrollertest {Private Static FinalLogger Logger = Loggerfactory.getlogger (userservicetest.class); //Inject Webapplicationcontext@ResourcePrivateWebapplicationcontext Webapplicationcontext; PrivateMockmvc Mockmvc; //Initialize the MOCKMVC, execute before each test method@Before Public voidSetup () { This. Mockmvc = Mockmvcbuilders.webappcontextsetup ( This. Webapplicationcontext). build (); } @Test Public voidTestindex ()throwsException {/*** Mockmvc.perform () executes a request * GET ("/server/get") constructs a request * Andexpect () Add Validation rule * Anddo () add A result handler * Andreturn () returns results after execution completes*/Mvcresult Result= Mockmvc.perform (Get ("/server/get"). param ("id", "1") . Andexpect (Mockmvcresultmatchers.status (). IsOk ()). Andexpect (Mockmvcresultmatchers.js Onpath ("$.username"). Value ("Google")) . Anddo (print ()). Andreturn ();        Logger.info (Result.getresponse (). getcontentasstring ()); //Adding validation assertionsAssert.assertnotnull (Result.getresponse (). getcontentasstring ()); }}

(iv). Performing unit Tests

The Engineering test directory structure is as follows, run the MVN Test command, automate the Maven-suerfire-plugin plugin

Execution results

(v). Beancreationnotallowedexception exception

Beancreationnotallowedexception exceptions may be thrown when executing test cases

[20:47:18,133 WARN] [Thread-3] (abstractapplicationcontext.java:994)-Exception thrown from applicationlistener handling ContextClosedEventorg.springframework.beans.factory.BeanCreationNotAllowedException:Error creating bean with Name '  Sessionfactory ': Singleton bean creation not allowed while singletons of this factory is in destruction (does not request a    Bean from a beanfactory in a destroy method implementation!) At Org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton ( defaultsingletonbeanregistry.java:216) at Org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean (abstractbeanfactory.java:302) at Org.springframework.beans.factory.support.AbstractBeanFactory.getBean (abstractbeanfactory.java:202) at Org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners ( abstractapplicationeventmulticaster.java:235) at Org.springframework.context.event.AbstractApplicationEventMulticaster.getAPplicationlisteners (abstractapplicationeventmulticaster.java:192) at Org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent ( simpleapplicationeventmulticaster.java:128)

By injecting Defaultlifecycleprocessor solution, edit resources/spring/applicationcontext.xml

    <id= "Lifecycleprocessor"  class= " Org.springframework.context.support.DefaultLifecycleProcessor ">        <  name = "Timeoutpershutdownphase" value = "10000" />    </ Bean >

Getting Started with SPRING+JUNIT4 unit testing

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.