您当前的位置: 首页 >  单元测试

梁云亮

暂无认证

  • 1浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

SpringBoot单元测试

梁云亮 发布时间:2020-02-06 21:03:29 ,浏览量:1

junit4和junit5对比 junit4junit5特点@Test@Test声明一个测试方法@BeforeClass@BeforeAll在当前类的所有测试方法之前执行。注解在【静态方法】上@AfterClass@AfterAll在当前类中的所有测试方法之后执行。注解在【静态方法】上@Before@BeforeEach在每个测试方法之前执行。注解在【非静态方法】上@After@AfterEach在每个测试方法之后执行。注解在【非静态方法】 示例 第一步:创建Maven项目,添加依赖:

        org.springframework.boot
        spring-boot-starter-test
        test
        
            
                org.junit.vintage
                junit-vintage-engine
            
        
    
    
        junit
        junit
        4.12
        test
    
第二步:测试代码示例:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class LogbackdemoApplicationTests {

    @Test
    public void fun() {
        System.out.println(33+44);
    }

}

或者

@RunWith(SpringRunner.class) //SpringRunner相当于SpringJUnit4ClassRunner的别名
@SpringBootTest
class LogbackdemoApplicationTests {

    @Test
    public void fun() {
        System.out.println(33+44);
    }

}

或者

@RunWith(SpringRunner.class)
@WebMvcTest
public class DeptController3Test {
    @Resource
    private DeptController deptController;
    @Test
    public void fun(){
        System.out.println(deptController);
    }
}

注意:使用SpringBoot整合Junit5时,测试类和测试方法都可以不使用public修饰,甚至@RunWith注解也可以省略

  • @SpringBootTest:告诉SpringBoot去寻找一个主配置类(例如带有@SpringBootApplication的配置类),并使用它来启动Spring应用程序上下文。该注解会试图去寻找所有可能的Bean,因此速度会很慢。
  • @RunWith:会为我们构造一个Servlet容器运行环境,并在此环境下测试。
  • @WebMvcTest:主要用于Controller层的测试,只覆盖应用程序的Controller层(性能较高),HTTP请求和响应是模拟出来的,不会创建真正的连接。
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.1355s