Spring's unit Test

Source: Internet
Author: User

Introduction

The use of unit testing when running a program is an important indicator of the quality of a programmer. The use of unit testing allows me to check the correctness of the program logic and also let us reduce the program testing bugs, easy to debug can improve our writing program efficiency. We used to use junit when we were doing unit tests, just to introduce the relevant jar package. But we can use the unit test when we use spring, the answer is yes. Spring itself integrates the juint, which greatly facilitates the development of our programs.

1. Introduction of relevant environment

If we want to use the unit testing capabilities provided by spring, we will need to introduce the Spring Unit Test jar package In addition to the spring-related environment, using the MAVEN configuration is

  

<Dependency>    <groupId>Org.springframework</groupId>      <Artifactid>Spring-test</Artifactid>      <version>3.2.10.RELEASE</version></Dependency></span>
2. Using the example

We immediately followed the results of the previous experiment, the last time we were factorybean to load the spring environment and implement the injection function, then we can directly through the unit test method to achieve, see the following example:

Import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.test.context.contextconfiguration;import Org.springframework.test.context.junit4.springjunit4classrunner;import service. Hello;import Javax.annotation.Resource; @RunWith (Springjunit4classrunner.class) @ContextConfiguration ({"Classpath : Applicationcontext.xml "}) public class TestDemo2 {    @Resource    hello hello;    @Test public    void Testhello () {        Hello.sayhello ();        Hello.saygoodbye ();    }}

Operation Result:

We tested the functionality of our service class directly through the unit tests above.

3. Explanation of annotations

  

 @RunWith (Springjunit4classrunner.class)// Specifies the run of the test case, here is the specified


The @ContextConfiguration ({"Classpath:applicationContext.xml"})//Loads the spring configuration in, can load multiple, use arrays, But the classpath path can also be the file path
@Resource//Inject the appropriate class into the spring IOC container and then you can use it directly. (Injected by Type)

@Autowied//inject the corresponding class, function and @resource are the same


@Test//Mark this is a unit test method, which needs to be added to each unit test method


In addition to the above notes, many useful annotations in spring unit tests are described below,


@Before// executes before each test case method, positioned above the method


@After// executes after each test case method, positioned above the method

Spring's unit tests provide support for these features if we have a way to resolve or provide support for transaction processing in our test unit. Mainly through the following several annotations to achieve:


@Transactional//uses transactions for all test methods and rolls back the transaction after the test is complete, and the function of this annotation is related to the location in which it is located, if The position of the @Transactional is above the class so it means that the transaction is used for multiple unit test methods, but if it is on top of a test method, the transaction is only used by the method, and the transaction is rolled back by default when the method executes.


@Rollback (FALSE)//set to false here to let the transaction not rollback. If we do not want the transaction rollback after adding the transaction support we just need to add this annotation at the appropriate location. If TRUE indicates that the transaction is rolled back, the default is true.
4. Other 

the above annotation function basically can meet our needs, if we do not know the function of @ContextConfiguration annotations, we should use the above method to inject the spring configuration. Take a look at the following two test examples:Unittestbase.java


  

ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.springframework.beans.BeansException;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;Importorg.springframework.util.StringUtils; Public classUnittestbase {PrivateClasspathxmlapplicationcontext context; PrivateString Springxmlpath;  Publicunittestbase () {} Publicunittestbase (String springxmlpath) { This. Springxmlpath =Springxmlpath; } @Before Public voidbefore () {if(Stringutils.isempty (Springxmlpath)) {Springxmlpath= "Classpath*:applicationcontext.xml"; }        Try{Context=NewClasspathxmlapplicationcontext (Springxmlpath.split ("[, \\s]+"));        Context.start (); } Catch(beansexception e) {e.printstacktrace (); }} @After Public voidAfter () {Context.destroy (); } @SuppressWarnings ("Unchecked")    protected<textendsObject>T Getbean (String beanid) {Try {            return(T) Context.getbean (Beanid); } Catch(beansexception e) {e.printstacktrace (); return NULL; }    }        protected<textendsObject> T Getbean (class<t>clazz) {        Try {            returnContext.getbean (Clazz); } Catch(beansexception e) {e.printstacktrace (); return NULL; }    }}
Importorg.junit.Test;ImportOrg.junit.runner.RunWith;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;ImportCom.imooc.ioc.interfaces.OneInterface;Importcom.imooc.test.base.UnitTestBase; the @RunWith (Springjunit4classrunner.class) Public classTestspringunitextendsUnittestbase { PublicTestspringunit () {Super("Classpath*:applicationcontext.xml"); } @Test Public voidTestsay () {Hello Hello=Super. Getbean ("Hello"); Hello.sayhello (); }}

So we can do a simple encapsulation of the test unit, and put some necessary checks into the @before. With the Getbean interface provided by the tool class, we can get the bean we need, but he just encapsulates the spring Factorybean. In development we should use the first one directly.

5. Impressions

For the robustness of the program is also the owner of the most own code, we need more use of unit testing, which is a good habit. Use annotations more when you use Spring-integrated unit tests to submit productivity.

Spring's unit Test

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.