In the spring MVC + mybatis project, We sometimes need to inject the DAO operations database into the test code, and make the table to be added and removed, to achieve the following:
This is the general MAVEN project project structure
The test code is generally written under the Src/test/java Package.
This is a common test class that queries the data of a table by Mybatis.
1 public classSpringmybatistest {2 3 @Resource4 Private StaticTestdao testdao;5 6 @BeforeClass7 public Static voidInit () {8 //Initialize Spring Fetch context9ApplicationContext content =NewClasspathxmlapplicationcontext ("classpath*:spring/spring.xml");TenTestdao = Content.getbean (testdao.class); one } a @Test - public voidtest1 () { -list<map<object,object>> list = this. Testdao.querylistmap (); the for(map<object,object>Map:list) { - for(map.entry<object, object>Temp:map.entrySet ()) { -System.out.println ("key:" +temp.getkey () + "----" + "value:" +Temp.getvalue ()); - } + } - } +}
If there are multiple XML files that need to be imported when initializing spring, you can use the following method:
ApplicationContext content = new Classpathxmlapplicationcontext ("classpath*:spring/root.xml");
Introduce all the spring configuration files in root.xml, as Follows:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "http://www.springframework.org/schema/beans" >< Import resource= "classpath*:spring/spring.xml"/><import resource= "classpath*:spring/spring-mvc.xml"/> </beans>
Testdao Interface Code:
public interface Testdao {public list<map<object,object>> querylistmap ();}
The corresponding XML file Sql:
<select id= "querylistmap" resulttype= "java.util.HashMap" >select * from test</select>
The test table is simple, as Follows:
Run the test method with the following results:
Normal access to the database is normal and does not need to be written to a complex controller or serverice.
Using JUnit in spring MVC + Mybatis