步驟一:基於前面的知識點
本知識點在springboot使用基於Mybatis注解方式實現的CRUD的基礎上進行的。
步驟二:修改pom.xml文件
在pom.xml文件添加 junit的依賴和spring-boot-starter-test
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- springboot test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
步驟三:創建測試類
1. 需要加上2個注解:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
2. 自動裝配 CategoryMapper map; 以便於使用
3. test 方法加上 @Test 注解,然后就可以使用map來工作了
4. 運行的時候選擇 JUnit Test 方式
package cn.xdf.springboot.test; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import cn.xdf.springboot.Application; import cn.xdf.springboot.mapper.CategoryMapper; import cn.xdf.springboot.pojo.Category; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class) public class TestFindAll { @Autowired CategoryMapper map; @Test public void test(){ List<Category> cs = map.findAll(); for (Category c : cs) { System.out.println("c.getname():"+c.getName()); } } }
步驟四:測試
2019-05-08 11:12:31.976 INFO 12472 --- [ main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in globalExceptionHandler 2019-05-08 11:12:32.000 INFO 12472 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2019-05-08 11:12:32.336 INFO 12472 --- [ main] cn.xdf.springboot.test.TestJPA : Started TestJPA in 6.753 seconds (JVM running for 8.329) c.getname():家具 c.getname():電器 c.getname():服裝 c.getname():化妝品 c.getname():水果 c.getname():美女 c.getname():睡么 c.getname():帥哥 c.getname():電飯鍋 c.getname():梵蒂岡 c.getname():扶搖 c.getname():混蛋 c.getname():極樂世界 c.getname():mybatis c.getname():劉濤-南 2019-05-08 11:12:32.470 INFO 12472 --- [ Thread-4] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext@145df59: startup date [Wed May 08 11:12:26 CST 2019]; root of context hierarchy 2019-05-08 11:12:32.473 INFO 12472 --- [ Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'