蜗牛一样的小白 2021-07-26 20:52 采纳率: 100%
浏览 31
已结题

ssm中spring单元测试出现的问题 need your help

20:38:24.001 [main] ERROR org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@420745d7] to prepare test instance [com.lzw.test.MvcTest@7e11ab3d]
java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/dbconfig.properties]

Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/dbconfig.properties]

java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/dbconfig.properties]

Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/dbconfig.properties]

xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.lzw">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>


    <!-- 配置jdbc 引入外部jdbc信息 -->
    <context:property-placeholder location="dbconfig.properties"/>
    <bean id="duridDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"></property>
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>


    <!-- 整合mybatis -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="mybatis-config.xml"/>
        <property name="dataSource" ref="duridDataSource"/>
        <property name="mapperLocations" value="mapper/*.xml"/>
    </bean>

    <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lzw.crud.dao"/>
    </bean>

    <!-- 配置一个可以执行批量的sqlSession -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>

    <!-- 事务控制配置 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="duridDataSource"/>
    </bean>

    <!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式)  -->
    <aop:config>
        <!-- 切入点表达式 -->
        <aop:pointcut expression="execution(* com.lzw.crud.service..*(..))" id="txPoint"/>
        <!-- 配置事务增强 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
    </aop:config>

    <!--配置事务增强,事务如何切入  -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 所有方法都是事务方法 -->
            <tx:method name="*"/>
            <!--以get开始的所有方法  -->
            <tx:method name="get*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
</beans>


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

<!-- springmvc的配置文件 网站跳转逻辑的控制配置 -->
    <context:component-scan base-package="com.lzw">
    <!-- 只扫描控制器 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

<!-- 配置视图解析器 页面返回 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

<!-- spring处理不了的交给tomcat -->
    <mvc:default-servlet-handler/>
<!-- springmvc更加高级的功能 JSR303校验 快捷的ajax 映射动态请求 -->
    <mvc:annotation-driven/>

</beans>
**Service以及Controller**
package com.lzw.crud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzw.crud.bean.Employee;
import com.lzw.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


@Controller
public class EmployeeController{

    @Autowired
    EmployeeService employeeService;

    // 查询员工数据
    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model){
        // 分页查询插件 插第几页 几条数据
        PageHelper.startPage(pn,5);

        List<Employee> emps =   employeeService.getAll();
        // 包装查询结果 只需要将pageinfo交给页面
        PageInfo page = new PageInfo(emps);
        model.addAttribute("pageInfo",page);


        return "list";

    }
}


package com.lzw.crud.service;

import com.lzw.crud.bean.Employee;
import com.lzw.crud.dao.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class EmployeeService{

    @Autowired
    EmployeeMapper employeeMapper;

    public List<Employee> getAll(){
        return employeeMapper.selectByExampleWithDept(null);
    }
}

单元测试


@RunWith(SpringJUnit4ClassRunner.class)
// web ioc也能拿到
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:applicationContext.xml","file:D:/Teaching/Idea/SpringBoot/ssm_crud/ssm_01/web/WEB-INF/dispatcherServlet-servlet.xml"})
public class MvcTest{
    // 传入springmvc的ioc
    @Autowired
    WebApplicationContext context;

    // 虚拟mvc请求 获取处理结果
    MockMvc mockMvc;

    @Before
    public void initMockMvc(){
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void testPage() throws Exception{
        // 模拟请求拿到返回值
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn", "1")).andReturn();

        // 请求成功后 请求域中会有pageInfo 取出该值进行验证
        MockHttpServletRequest request = result.getRequest();
        PageInfo pi = (PageInfo) request.getAttribute("pageInfo");

        System.out.println("当前页码:"+pi.getPageNum());
        System.out.println("总页码:"+ pi.getPages());
        System.out.println("总记录数:"+pi.getTotal());
        int[] nums = pi.getNavigatepageNums();
        for (int i :
                nums) {
            System.out.println(" "+i);
        }
        List<Employee> list = pi.getList();
        for (Employee e :
                list) {
            System.out.println("ID:"+e.getEmpId()+"==>Name"+e.getEmpName());
        }

    }


}

请君助我 困扰我一下午了

  • 写回答

2条回答 默认 最新

  • CSDN专家-微编程 2021-07-26 21:09
    关注

    xml配置文件,配置数据库的那个是不是少写了东西,你的system-properties-mode="NEVER"呢

    <!--    &lt;!&ndash;引入小配置文件 读取jdbc.properties&ndash;&gt;-->
        <context:property-placeholder location="classpath:common.properties" system-properties-mode="NEVER"/>
        <bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
            <property name="driverClassName" value="${driverClassName}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
        </bean>
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 8月3日
  • 已采纳回答 7月26日
  • 创建了问题 7月26日

悬赏问题

  • ¥15 使用yolov5-7.0目标检测报错
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备