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

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>
    
    
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • 找不到dbconfig.properties文件,查看一下配置路径。

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题