1. We know that JUnit tests are available in both J2SE and Android, and using JUnit can help facilitate the testing of code. In my previous blog, I also wrote some examples of junit tests in J2SE, today for a little discussion of junit in spring.
The jar package required for this spring test:
Spring-test-3.2.0.release.jar
2.Spring and JUnit diagrams
The traditional way of testing the code on the left, which is generally j2se, is problematic:
(1). Each test starts with spring,
(2). In this case, the test code manages the spring container, and the spring container manages the test code to the back.
There may be other situations, so the junit test should be done on the right, and the spring frame diagram is being validated, so why test is at the bottom
3. A simple case:
The role of the package cn.wwh.www.spring.bbb.test;/** * Class: * * * @author Skiff * @version 1.0 *@ created: 2014-9-21 pm 03:22:26 */public cl The HelloWorld {public void Show () {System.out.println ("Hello world! This is my first spring! ");}
Test Case:
Package Cn.wwh.www.spring.bbb.test;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.beans.factory.beanfactory;import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.test.context.contextconfiguration;import org.springframework.test.context.junit4.springjunit4classrunner;/** * class function: Test write test Framework in spring * * * @author Skiff *@ Version 1.0 *@ creation time: 2014-9-21 10:19:41 *///indicates that the spring container is started and JUnit is run in the Spring container @runwith ( Springjunit4classrunner.class) @ContextConfigurationpublic class Springtesttest {//Auto assemble Spring container @autowiredprivate Beanfactory factory; @Testpublic void Testbeanfactory () throws Exception {HelloWorld World = Factory.getbean (" HelloWorld ", Helloworld.class); World.show ();}}
Springtesttest-context.xml configuration file:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd "><bean id=" HelloWorld "class=" Cn.wwh.www.spring.bbb.test.HelloWorld "/></beans>
Attention:
(1) [Email protected] (Springjunit4classrunner.class)
@ContextConfiguration
@Autowired
@Test
These are the test labels.
(2) [email protected] to find the configuration file, the default from the current path to find
If the file name = current test class name-context.xml, you can find it in the current path. You can omit the springtesttest-context.xml as above , the test class is:Springtesttest.java
If it is not written as agreed, the test needs to be written in the format of the load path:
@ContextConfiguration ("Classpath:cn/wwh/www/spring/bbb/test/springtesttest-context.xml")
Spring and JUnit Testing