springboot单元测试

步骤一:基于前面的知识点

  本知识点在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'

 

posted @ 2019-05-08 11:38  仰望星空的脚踏实地  阅读(3797)  评论(0编辑  收藏  举报