>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring:Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 17227 个阅读者 刷新本主题
 * 贴子主题:  SpringMVC下的JUnit4单元测试 回复文章 点赞(0)  收藏  
作者:Jacky    发表时间:2020-11-03 02:22:33     消息  查看  搜索  好友  邮件  复制  引用

    

简述

在spingMVC框架中,所有的类都是通过springMVC容器来加载和实例化的。

因此在junit测试的时候可以在其初始化方法中去加载spring配置文件。所有用Junit进行单元测试,都需要下面的配置。注:配置文件的加载根据自己项目的实际情况进行配置。    

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:config/spring-mvc.xml",
        "classpath:config/spring-resources.xml",
        "classpath:config/spring-application.xml",
        "classpath:config/spring-security.xml" })

Dao层的单元测试

通过依赖注入的方式注入测试对象;    

package com.lczyfz.zerobdt.test;

import com.lczyfz.zerobdt.modules.test.dao.TestDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import static junit.framework.TestCase.assertEquals;

/**
* Created by maple on 2018-07-01.
*/

@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration(locations = {"/spring-context.xml"})
public class TestDaoTests {
    @Autowired
    TestDao testDao;

    @Test
    public void testFindAllList(){
        System.out.println(testDao.findAllList(new com.lczyfz.zerobdt.modules.test.entity.Test()).toString());
        assertEquals(testDao.findAllList(new com.lczyfz.zerobdt.modules.test.entity.Test()).size(),13);
    }
}

  成功:

                点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小

              失败:

                点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小        

Service层的单元测试

和Dao层类似;    

package com.lczyfz.zerobdt.test;

import com.lczyfz.zerobdt.modules.test.service.TestService;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.*;

/**
* Created by maple on 2018-07-01.
*/

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-context.xml"})
public class TestDaoServices {
    @Autowired
    TestService testService;

    @Test
    public void testFindAllList(){
        System.out.println(testService.get("5").toString());
        assertNotNull(testService.get("5"));
    }
}

Controller层的单元测试

package com.lczyfz.zerobdt.test;

import com.lczyfz.zerobdt.common.test.SpringTransactionalContextTests;
import com.lczyfz.zerobdt.modules.test.web.TestController;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import java.io.UnsupportedEncodingException;

import static org.junit.Assert.assertNotNull;

/**
* Created by maple on 2018-07-01.
*/

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring-context.xml","/spring-mvc.xml"})
public class TestDaoControllers extends SpringTransactionalContextTests{
    @Autowired
    TestController testController;

    MockMvc mockMvc;

        @Before
    public void setup(){
        mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }
    @Test
    public void testFindAllList(){
        ResultActions resultActions = null;
        try {
            resultActions = this.mockMvc.perform(MockMvcRequestBuilders.post("/show_user").param("id", "1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        MvcResult mvcResult = resultActions.andReturn();
        String result = null;
        try {
            result = mvcResult.getResponse().getContentAsString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println("=====客户端获得反馈数据:" + result);
        // 也可以从response里面取状态码,header,cookies...
//        System.out.println(mvcResult.getResponse().getStatus());

    }
}

  Controller层的测试建议采用Postman的方式来测试,可以记录url,同时也更符合实际情况。


----------------------------
原文链接:https://www.jianshu.com/p/8d0f7201b445

程序猿的技术大观园:www.javathinker.net



[这个贴子最后由 flybird 在 2020-11-24 20:26:14 重新编辑]
  Java面向对象编程-->接口
  JavaWeb开发-->JavaWeb应用入门(Ⅱ)
  JSP与Hibernate开发-->映射组成关系
  Java网络编程-->基于UDP的数据报和套接字
  精通Spring-->绑定表单
  Vue3开发-->Vue简介
  微服务架构集大成者—Spring Cloud简明教程
  循序渐进,阿里架构师看完都赞叹的Redis分布式锁原理分析
  Redis夺命连环11问
  @Service注解的使用
  Spring AOP的基本概念和注解
  SpringMVC 中 @ControllerAdvice 注解的三种使用场景!
  Spring Data JPA详解
  Spring MVC控制器类的方法的所支持的方法参数类型
  SpringMVC Model、ModelMap和ModelAndView的区别和用法
  国内 Java 开发者必备的两个神器:Maven国内镜像和Spring国内...
  Spring Cloud构建微服务架构的服务注册与发现
  Nginx安装及配置
  Zabbix后端存储ES的优化实践
  深入理解Mybatis一级缓存
  再谈响应式流(结合制奶厂业务的案例)
  更多...
 IPIP: 已设置保密
树形列表:   
1页 0条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。