zoukankan      html  css  js  c++  java
  • 使用maven对项目进行junit的单元测试

    Spring中的单元测试

    需要引入依赖

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
        <scope>test</scope>
    </dependency>
    
    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.2.RELEASE</version>
            <scope>test</scope>
    </dependency>
    View Code

    你也可以编写基类,然后具体业务类继承,你也可以直接怼,这里我就规范一下,先写基类

    BaseTest.java如下,其中@Before和@After注解都是junit提供的,其含义写在代码的注释中了:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})
    public class BaseTest {
        @Before
        public void init() {
            //在运行测试之前的业务代码
        }
        @After
        public void after() {
            //在测试完成之后的业务代码
        }
    }
    View Code

    编写具体测试类

    写完测试基类后,就可以开始写真正的单元测试了,下面是一个简单的示例:

    public class HelloTest extends BaseTest {
    
        @Test
        public void getTicketInfo() {
            System.out.println("hello");
    }
    View Code

    我们可以看到在IDEA中可以直接对单元测试的某个方法进行运行,不用编译项目和启动服务器就可以达到对业务代码的功能测试,可见其便利程度。

    SpringBoot中的单元测试

    SpringBoot中使用Junit和SpringMVC基本类似,只需要改动一些配置即可。

    加入依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-test</artifactId>
        <version>1.5.2.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>4.3.7.RELEASE</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    View Code

    编写测试基类

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class BaseTest {
        @Before
        public void init() {
            
        }
        
        @After
        public void after() {
            
        }
    }
    View Code
  • 相关阅读:
    求一列的和,awk和perl哪个快?
    转:使用memc-nginx和srcache-nginx模块构建高效透明的缓存机制
    使用apt-get autoremove造成的系统无法开机
    因不公对待,技术销毁删除代码数据,谁对谁错?负能量文章,老板慎入。
    我曾经做过的插件
    宝石TD迷宫设计器
    VSX-5 VSXMusic 编码听音乐
    耐得住寂寞,才能守得住繁华
    VSX-4 VSXTra
    VSX-3 VSCT文件
  • 原文地址:https://www.cnblogs.com/coder-lzh/p/9060110.html
Copyright © 2011-2022 走看看