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
  • 相关阅读:
    【SVN解决代码提交冲突】https://www.cnblogs.com/aaronLinux/p/5521844.html
    查询有2门及以上不及格科目的学生姓名及其平均成绩
    【Python】split
    【Python】文件处理
    【robotframework】打开浏览器提示:NoSuchWindowException: Message: Unable to get browser
    定位到新窗口
    8月1号
    【定位】https://blog.csdn.net/cyjs1988/article/details/76284289
    【Robotframework】脚本跑完后自动发送邮件
    jQuery Mobile Data 属性
  • 原文地址:https://www.cnblogs.com/coder-lzh/p/9060110.html
Copyright © 2011-2022 走看看