springboot编写测试类常见错误(java.lang.IllegalStateException: Failed to load ApplicationContext)

java.lang.IllegalStateException: Failed to load ApplicationContext**

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'deptResource' defined in file [C:\Users\dw\Desktop\project\c2sample\console\target\classes\com\inossem\c2app\org\DeptResource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sysDeptService': Unsatisfied dependency expressed through field 'deptMapper'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sysDeptDao' defined in file [C:\Users\dw\Desktop\project\c2sample\console\target\classes\com\inossem\c2app\org\dao\SysDeptDao.class]: Unsatisfied dependency expressed through bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactory' threw exception; nested exception is org.springframework.core.NestedIOException: Failed to parse mapping resource: 'file [C:\Users\dw\Desktop\project\c2sample\console\target\classes\mapper\org\SysDeptMapper.xml]'; nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'file [C:\Users\dw\Desktop\project\c2sample\console\target\classes\mapper\org\SysDeptMapper.xml]'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'SysDept'.  Cause: java.lang.ClassNotFoundException: Cannot find class: SysDept

问题分析:很容易看到,实体类SysDept在mapper中没有识别,说明包扫描没有扫到,可以通过修改Mybatis包扫描包含进去,或者在mapper中对应SysDept实体换成全路径即可解决;

同样测试类问题

报错信息:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.apache.xmlbeans.impl.piccolo.xml.EntityManager' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

自动注入失败,修改包扫描范围:
在这里插入图片描述

MockMvc.perform报空指针

java.lang.NullPointerException
at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:94)

解决办法:

方法1:单元测试中添加如下代码

/**
 * web项目上下文
 */
@Autowired
private WebApplicationContext webApplicationContext;


/**
 * 所有测试方法执行之前执行该方法
 */
@Before
public void before() {
	//获取mockmvc对象实例
	mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

方法1,这样做是不加载其他的过滤器. 这样权限校验无法通过!

方法2:
加入 druid-spring-boot-starter 依赖
在application-test.properties中增加配置spring.datasource.druid.web-stat-filter.enabled=false
在测试类上增加@activeprofiles(“test”)

详细见https://gitee.com/jinglun404/DLXD/issues/IGCM9

java.lang.AssertionError: Content type not set

post请求
查看错误提示中请求参数类型没有被设置,参数没有被识别,查看了下controller中,请求参数没有加@RequestBody;虽然在程序启动过程中是不会出问题,但是在mockmvc测试类中中报错,在controller中加上了注解,并对应前端也做了更改;

 @Test
    @Transactional
    public void getSysPost() throws Exception {

        // Get the sysPost
        restSysPostMockMvc.perform(post("/org/XXController/getInfo")
            .contentType(MediaType.APPLICATION_JSON)
            .content(JSONObject.toJSONString(5L)))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.postId").value(5))
            .andExpect(jsonPath("$.postCode").value("emp"))
            .andExpect(jsonPath("$.postName").value("普通员工"))
            .andExpect(jsonPath("$.postSort").value("5"))
            .andExpect(jsonPath("$.status").value("0"))
public SysPost getInfo(@RequestBody Long postId)
    {
        return sysPostService.selectPostById(postId);
    }

第二种办法是修改mockmvc的contentType

.contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param("入参变量","参数值"))
            .andExpect(status().isOk())

实例循环问题

Description:

The dependencies of some of the beans in the application context form a cycle:

deptResource defined in file [XXX]

sysDeptService (XXX)

sysDeptDao defined in file [XXX]

sqlSessionFactory defined in class path resource [com/baomidou/mybatisplus/autoconfigure/MybatisPlusAutoConfiguration.class]
┌─────┐
| dynamicDataSource defined in class path resource [com//druid/DruidConfig.class]
↑ ↓
| masterDataSource defined in class path resource [com/druid/DruidConfig.class]
↑ ↓
| org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker

解决办法:
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })

问题解决,记录一下

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值