Spring-单元测试 demo

摘要:
记录一下自己用过的单元测试方法

-1 注意

  1. 加了@test的类 不能有返回值和参数

0 中间遇到的bug

中间遇到一个maven插件的问题
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-cli) on project spring_junit_module: No tests were executed! (Set -DfailIfNoTests=false to ignore this error.) -> [Help 1]
可能的解决办法 用法二
https://blog.csdn.net/u011781521/article/details/74868680
其实后来发现,ide下面的event log里面也有报错,重启了一次ide

文章目录

    • -1 注意
    • 0 中间遇到的bug
    • 1.法一 用IntelliJ
    • 2 法二 使用spring junit
      • 我的具体操作:
      • 项目源码:

1.法一 用IntelliJ

优点:简单
缺点:不能批量处理吧

可参考:
https://blog.csdn.net/yangshijin1988/article/details/63262400
Spring-单元测试 demo_第1张图片

Spring-单元测试 demo_第2张图片

2 法二 使用spring junit

优点:直接加注释就行了
缺点:配置有点麻烦

package test;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@ContextConfiguration(locations={"classpath:applicationContext.xml","classpath:dispatcher-servlet.xml"}) //加载配置文件
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseJunit4Test  {
}

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@ContextConfiguration(locations={"classpath:applicationContext.xml","classpath:dispatcher-servlet.xml"}) //加载配置文件
@RunWith(SpringJUnit4ClassRunner.class)
public class test extends BaseJunit4Test{

    @Test
    public void test (){
       System.out.print("ok");
    }

}

applicationContext.xml



    
    
    

pom.xml



    4.0.0

    groupId
    spring_junit_module
    1.0-SNAPSHOT


    
        
            junit
            junit
            4.9
            test
        
        
            org.springframework
            spring-test
             3.2.4.RELEASE  
            provided
        
        
            junit
            junit
            4.12
        


    
    
    
      
    
        

            
                org.apache.maven.plugins
                maven-surefire-plugin
                2.4.2
                
                    true
                
            
        



    









我的具体操作:

1.新建一个springmvc项目
2.添加maven支持
3.修改application,xml 并把这两个文件放到resource目录下
4.增加和修改上面的文件
5.运行 :直接点击方法左边的运行按钮就行 无需启动整个项目Spring-单元测试 demo_第3张图片

项目源码:

项目1:
https://github.com/sunny73/WEB_Projects/commit/11438da6256fce670816fe33c82c314e0b69dffc

项目2:
https://github.com/sunny73/WEB_Projects/commit/7ab17ff76c072bf4a37a2bd74857864e7b6ee1d0

你可能感兴趣的:(WEB,备战秋招)