Summary of unit tests using spring with JUnit

Source: Internet
Author: User
Tags jboss

Recent company projects and their own projects have used spring integrated junit for unit testing, summarizing several basic uses:

1. Test the bean injected directly in spring (in DAO, for example):

Adding @runwith annotations on a test class specifies the test runner using Springjunit, @ContextConfiguration note Specifies the location of the spring configuration file for the test

Then we can inject the beans we need to test, and JUnit will parse the spring configuration file before running the test and initialize the bean configured in spring

@RunWith (Springjunit4classrunner.class) @ContextConfiguration (locations={"Classpath*:spring-config-test.xml "}) Public classTestprojectdao { @Autowired projectdao Projectdao;     
@Test Public voidTestcreateprojectcode () {LongApplytime =System.currenttimemillis (); Timestamp TS=NewTimestamp (applytime); Map CodeMap= Projectdao.generatecode ("5", "8", TS, "in hospital")); String Projectcode= (String) codemap.get ("_project_code"); Timestamp Apply_time= (Timestamp) codemap.get ("_apply_time"); System.out.print (Projectcode); System.out.print (Apply_time.tostring ()); Assert.asserttrue (Projectcode.length ()==12); }

2. Test the SPRINGMVC:

ORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC class spring3.2 followed by support for SPRINGMVC unit tests

Examples are as follows:

 PackageCom.jiaoyiping.baseproject;ImportCom.jiaoyiping.baseproject.privilege.controller.MeunController;ImportCom.jiaoyiping.baseproject.training.bean.Person;ImportJunit.framework.Assert;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.http.MediaType;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;Importorg.springframework.test.context.web.WebAppConfiguration;ImportORG.SPRINGFRAMEWORK.TEST.WEB.SERVLET.MOCKMVC;Importorg.springframework.test.web.servlet.ResultActions;Importorg.springframework.test.web.servlet.setup.MockMvcBuilders;ImportOrg.springframework.web.servlet.ModelAndView;Import Staticorg.springframework.test.web.servlet.request.mockmvcrequestbuilders.*;Import Staticorg.springframework.test.web.servlet.result.mockmvcresultmatchers.*;/*** Created with IntelliJ idea. * User: KJ a flat * date:14-9-25 * Time: PM 6:45 * To change this template use File | Settings | File Templates. */@RunWith (Springjunit4classrunner.class) @WebAppConfiguration//@ContextConfiguration (classes = {webmvcconfig.class, mockdataconfig.class})@ContextConfiguration (locations={"Classpath:/spring/applicationcontext.xml", "classpath*: Mvc-dispatcher-servlet.xml "}) Public classTESTMOCKMVC {@AutowiredPrivateOrg.springframework.web.context.WebApplicationContext context;    Mockmvc Mockmvc; @Before Public voidbefore () {//all controllers can be tested .MOCKMVC =Mockmvcbuilders.webappcontextsetup (context). build (); //test only for a single controller//MOCKMVC = Mockmvcbuilders.standalonesetup (New Meuncontroller ()). build ();} @Test Public voidTestgetmenu () {Try{System.out.println ("----------------------------"); Resultactions Actions= This. Mockmvc.perform (Get ("/menu/manage.action")); System.out.println (status ());//System.out.println (Content (). toString ()); Actions.andexpect (Status (). IsOk ());//Actions.andexpect (Content (). ContentType ("text/html"));System.out.println ("----------------------------"); } Catch(Exception e) {e.printstacktrace (); //To change body of catch statement use File | Settings | File Templates.        }    }    //add users directly from the controller (using the Post method)//Post ("path"). param ("attribute name", "attribute value"); Use this method to construct the post@Test Public voidAddperson () {Try{resultactions resultactions= This. Mockmvc.perform (Post ("/person/add"). param ("Name", "UF software"). param ("Age", "23"). param ("Address", "Beijing Yongfeng Tun")            );        Resultactions.andexpect (Status (). IsOk ()); } Catch(Exception e) {e.printstacktrace (); //To change body of catch statement use File | Settings | File Templates.        }    }    //method of obtaining the Modelandview returned by the controller layer: Resultactions.andreturn (). Getmodelandview (). Getmodel (). Get ("person");@Test Public voidGetperson () {String ID= "297e5fb648b0e6d30148b0e6da6d0000";Try {Resultactions resultactions = This. Mockmvc.perform (Post ("/person/toeditperson"). PARAM ("id"), id)). Andexpect (Status (). IsOk ());assert.assertequals ((person) (Resultactions.andreturn (). Getmodelandview (). Getmodel (). Get ("person")). GE Tage ());Person person = (person) (Resultactions.andreturn (). Getmodelandview (). Getmodel (). Get (' person '));            System.out.println (Person.getid ());            System.out.println (Person.getname ());            System.out.println (Person.getage ());            System.out.println (Person.getaddress ()); Assert.assertequals (23, Person.getage ()); } Catch(Exception e) {e.printstacktrace (); //To change body of catch statement use File | Settings | File Templates.        }    }}

3. Test the interface provided by the Resteasy (used when using the rest type interface provided by Resteasy)

Resteasy provides the Org.jboss.resteasy.core.Dispatcher class to simulate HTTP requests and return data

This way, you do not have to start the container when you test the interface.

The code is as follows

/*** Cn.cmri.pds.controller.TestProjectTagController.java * Copyright (c) Hewlett-Packard Development company, L. P. * All rights reserved. */ PackageCn.cmri.pds.controller;Importjava.net.URISyntaxException;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.jboss.resteasy.core.Dispatcher;Importorg.jboss.resteasy.mock.MockDispatcherFactory;Importorg.jboss.resteasy.mock.MockHttpRequest;ImportOrg.jboss.resteasy.mock.MockHttpResponse;ImportOrg.junit.Assert;ImportOrg.junit.Before;Importorg.junit.Test;ImportOrg.junit.runner.RunWith;Importorg.springframework.beans.factory.annotation.Autowired;Importorg.springframework.test.context.ContextConfiguration;ImportOrg.springframework.test.context.junit4.SpringJUnit4ClassRunner;ImportCn.cmri.pds.project.controllor.ProjectTagControllor;ImportCn.cmri.pds.project.service.ProjectTagService;/*** <pre> * DESC: *@authorCoke One flat * @refactor Coke one flat * @date December 10, 2014 PM 3:44:03 *@version1.0 *@see* Revisions: * Version Date Author Description *-------------------------------- -----------------------------------* 1.0 December 10, 2014 Coke one ping 1.  Created this class. * </pre>*/@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations= {"Classpath*:spring-config-test.xml" }) Public classTestprojecttagcontroller {@Autowired projecttagservice projecttagservice;    Dispatcher Dispatcher; @Before Public voidbefore () {Projecttagcontrollor Projecttagcontrollor=NewProjecttagcontrollor ();        Projecttagcontrollor.setprojecttagservice (Projecttagservice); Dispatcher=Mockdispatcherfactory.createdispatcher ();    Dispatcher.getregistry (). Addsingletonresource (Projecttagcontrollor); } @Test Public voidTestprojecttags ()throwsurisyntaxexception{mockhttprequest Request= Mockhttprequest.get ("/rest/project/123456/tags"); Mockhttpresponse Response=NewMockhttpresponse ();        Dispatcher.invoke (request, response);        Assert.assertequals (Httpservletresponse.sc_not_found, Response.getstatus ()); Assert.assertequals ("The specified item does not exist", response.getcontentasstring ()); }    }

Summary of unit tests using spring with JUnit

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.