spring整合junit时遇到的问题

1、Could not autowire field: private javax.servlet.http.HttpServletRequest

参考:https://www.cnblogs.com/summary-2017/p/8000626.html

https://stackoverflow.com/questions/17619029/spring-junit-test-case-failed

@WebAppConfiguration("src/main/resources") : 注解在类上,用来声明加载的ApplicationContex 是一个WebApplicationContext ,它的属性指定的是Web资源的位置,默认为 src/main/webapp ,自定义修改为 resource

2、添加@WebAppConfiguration注解后又有错误: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale zh_CN

java.lang.ExceptionInInitializerError
at org.springframework.mock.web.MockHttpServletResponse.<init>(MockHttpServletResponse.java:)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$.runReflectiveCall(SpringJUnit4ClassRunner.java:)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:)
at org.junit.runners.ParentRunner$.run(ParentRunner.java:)
at org.junit.runners.ParentRunner$.schedule(ParentRunner.java:)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:)
at org.junit.runners.ParentRunner.access$(ParentRunner.java:)
at org.junit.runners.ParentRunner$.evaluate(ParentRunner.java:)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:)
at org.junit.runners.ParentRunner.run(ParentRunner.java:)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:)
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale zh_CN
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:)
at javax.servlet.ServletOutputStream.<clinit>(ServletOutputStream.java:)
... more

参考:https://stackoverflow.com/questions/31561603/java-util-missingresourceexception-cant-find-bundle-for-base-name-javax-servle

http://www.cnblogs.com/TonyYPZhang/p/5185386.html

报错原因:
Your running tests are missing the servlet-api dependency.
If you're using maven make sure this dependency is in your project:

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

也可以将tomcat运行jar添加到buildpath,这样本地测试的时候使用Server Runtime里面的servlet.jar;但是使用maven打包项目时仍然会报错,所以最好还是在maven中添加依赖。

3、java.lang.NoClassDefFoundError: com/jayway/jsonpath/InvalidPathException

  缺少了jar包,可以添加以下的maven依赖:

<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path-assert</artifactId>
<version>0.8.1</version>
<scope>test</scope>
</dependency>

参考资料:

  (1)SpringMVC 测试 mockMVC

  (2)Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法

spring整合junit其他参考资料:

  (1)https://lohasle.iteye.com/blog/1617929

  (2)https://blog.csdn.net/tony_java_2017/article/details/80760806

spring整合junit

1.JUnitDaoBase类

package com.oy;
import javax.transaction.Transactional; import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration; // do rollback
@TransactionConfiguration(defaultRollback = true)
@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { /* "classpath:spring-mvc.xml", */ "classpath:spring-mybatis.xml" })
public class JUnitDaoBase extends AbstractTransactionalJUnit4SpringContextTests {
}

2.JUnitControllerBase

package com.oy;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration; // do rollback
//@TransactionConfiguration(defaultRollback = true)
//@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:spring-mvc-test.xml", "classpath:spring-mybatis-test.xml" })
public class JUnitControllerBase {
}

3.UserSymbolCollectDaoTest

public class UserSymbolCollectDaoTest extends JUnitDaoBase {

    @Autowired
UserSymbolCollectDao userSymbolCollectDao; @Test
public void testCountByExample() {
long start = System.currentTimeMillis();
UtilFunctions.log.info("==== testCountByExample begin ===="); UserSymbolCollectExample example = new UserSymbolCollectExample();
UserSymbolCollectExample.Criteria criteria = example.createCriteria();
criteria.andUseridEqualTo(233);
long result = userSymbolCollectDao.countByExample(example);
UtilFunctions.log.info("==== result:{} ====", result); long time = System.currentTimeMillis() - start;
UtilFunctions.log.info("==== testCountByExample end, takes time:{} ms ====", time);
}
}

4.测试Controller

package com.oy.controller;

import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; import javax.servlet.http.Cookie; import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext; import com.oy.JUnitControllerBase;
import com.oy.utils.UtilFunctions; public class UserSymbolControllerTest extends JUnitControllerBase { @Autowired
public WebApplicationContext applicationContext; @Value("${PHPSESSIDValue}")
private String PHPSESSIDValue; private String PHPSESSIDKey = "PHPSESSID";
private MockMvc mockMvc; @Before
public void setup() {
this.mockMvc = webAppContextSetup(this.applicationContext).build();
} @Test
@Rollback(true)
public void testDeleteSymbolCollect1() {
try {
String uri = "/usersymbol/collect/1000"; String PHPSESSIDValue = this.PHPSESSIDValue;
Cookie cookiePHPSESSID = new Cookie(PHPSESSIDKey, PHPSESSIDValue); String mvcResult = mockMvc
.perform(delete(uri).contentType(MediaType.APPLICATION_FORM_URLENCODED).cookie(cookiePHPSESSID))
.andDo(print()).andExpect(status().isOk()).andExpect(jsonPath("$.code").value(500)).andReturn()
.getResponse().getContentAsString(); UtilFunctions.log.info("=== mvcResult:{} ===", mvcResult); } catch (Exception e) {
e.printStackTrace();
}
} @Test
@Rollback(true)
public void testDeleteSymbolCollect2() {
try {
String uri = "/usersymbol/collect/571"; String PHPSESSIDValue = this.PHPSESSIDValue;
Cookie cookiePHPSESSID = new Cookie(PHPSESSIDKey, PHPSESSIDValue); String mvcResult = mockMvc
.perform(delete(uri).contentType(MediaType.APPLICATION_FORM_URLENCODED).cookie(cookiePHPSESSID))
.andDo(print()).andExpect(status().isOk()).andExpect(jsonPath("$.code").value(0)).andReturn()
.getResponse().getContentAsString(); // === mvcResult:{"code":0} ===
UtilFunctions.log.info("=== mvcResult:{} ===", mvcResult); } catch (Exception e) {
e.printStackTrace();
}
} @Rollback(false)
@Test
public void testAddSymbolCollect() {
try {
String uri = "/usersymbol/collect"; String PHPSESSIDValue = this.PHPSESSIDValue;
Cookie cookiePHPSESSID = new Cookie(PHPSESSIDKey, PHPSESSIDValue); String mvcResult = mockMvc
.perform(post(uri)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.cookie(cookiePHPSESSID)
.param("base", "a")
.param("quote", "abc12"))
.andDo(print()).andExpect(status().isOk()).andExpect(jsonPath("$.code").value(0)).andReturn()
.getResponse().getContentAsString(); // === mvcResult:{"code":0} ===
UtilFunctions.log.info("=== mvcResult:{} ===", mvcResult); } catch (Exception e) {
e.printStackTrace();
}
}
}

  测试Controller:请求参数是form表单类型或json

@Test
public void postTradeOrder() {
try {
String uri = "/trade/order"; String PHPSESSIDValue = this.PHPSESSIDValue;
Cookie cookiePHPSESSID = new Cookie(PHPSESSIDKey, PHPSESSIDValue); // JSONObject paramsJson = new JSONObject();
// paramsJson.put("market", "eth_btc");
// paramsJson.put("price", "0.03");
// paramsJson.put("num", "1557.5425");
// paramsJson.put("direction", "2");
// paramsJson.put("trade_type", "1");
// paramsJson.put("paypassword", ""); String mvcResult = mockMvc.perform(
post(uri).contentType(MediaType.APPLICATION_FORM_URLENCODED)
// post(uri).contentType(MediaType.APPLICATION_JSON)
// .content(paramsJson.toJSONString()) // request json data
.param("market", "eth_btc")
.param("price", "0.03")
.param("num", "1557.5425")
//.param("direction", "1") // grpc return -19
.param("direction", "2")
.param("trade_type", "1")
.param("paypassword", "")
//.header("Cookie", PHPSESSIDKey + "=" + PHPSESSIDValue) // not ok
.cookie(cookiePHPSESSID)
//.requestAttr("uid", 106)
.accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
)
.andDo(print())
.andExpect(status().isOk())
//.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.code").value(0))
// .andExpect(jsonPath("$.data.name", is("测试")))
// .andExpect(jsonPath("$.data.createTime", notNullValue()))
.andReturn().getResponse().getContentAsString(); // === mvcResult:{"pay_pass":"3","code":0,"data":"2rhm0-1d85sc0ns-1-2"} ===
UtilFunctions.log.info("=== mvcResult:{} ===", mvcResult); } catch (Exception e) {
e.printStackTrace();
}
}

spring整合junit报错的更多相关文章

  1. spring整合quartz报错

    今天spring整合quartz报错,最后一步步排查,发现是和redis依赖冲突,最后redis升级了一下,问题解决. 总结:发现问题,逐一排查,如果是整合问题,报类加载不到的错误,大概率是和其他组件 ...

  2. Spring整合Hibernate报错:annotatedClasses is not writable or has an invalid setter method

    Spring 整合Hibernate时报错: org.springframework.beans.factory.BeanCreationException: Error creating bean ...

  3. Spring+Hibernate4 Junit 报错No Session found for current thread

    论坛上有另外一篇更全面的帖子,jinnianshilongnian写的:http://www.iteye.com/topic/1120924 本文的环境是:  spring-framework-3.1 ...

  4. spring+hibernate整合:报错org.hibernate.HibernateException: No Session found for current thread

    spring+hibernate整合:报错信息如下 org.hibernate.HibernateException: No Session found for current thread at o ...

  5. Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object

    我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!

  6. 【Junit 报错】No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).

    Junit报错 log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvi ...

  7. weblogic 整合cxf 报错:cannot create a secure XmlInputFactory

    weblogic 整合cxf 报错:cannot create a secure XmlInputFactory ================================ ©Copyright ...

  8. Spring boot 启动报错 Failed to auto-configure a DataSource

    1.Spring boot 启动报错 Failed to auto-configure a DataSource 参考资料https://blog.csdn.net/liuyinfei_java/ar ...

  9. spring Boot启动报错Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.core.annotation.AnnotatedElementUtils.getAnnotationAttributes

    spring boot 启动报错如下 org.springframework.context.ApplicationContextException: Unable to start web serv ...

随机推荐

  1. C++中vector使用详细说明 (转)

    转自:http://blog.chinaunix.net/uid-26000296-id-3785610.html http://www.cnblogs.com/mr-wid/archive/2013 ...

  2. Vue.filter 过滤器

    [过滤器] import Vue from '../../../node_modules/vue/dist/vue'; // 后台数据与前端展示数据需要换算,与后台交互的请求的参数是不需要.假如说前端 ...

  3. java八大数据类型

    基本数据类型以值传递的方式进行传递,String以值传递的方式传递,其他的以地址的方式进行传递 分别是:byte  short  int  long  float  double char boole ...

  4. 1、vue 笔记之 组件

    1.组件个人理解:  <组件>是页面的一部分,将界面切分成部分,每部分称为 <组件>   2.组件化思想:          //2.1.定义一个全局的组件,组件支持‘驼峰命名 ...

  5. js/jquery 元素是否存在

    <!DOCTYPE html><html><head><meta charset="UTF-8"><title>spli ...

  6. 69A

    #include <stdio.h> int main() { int n; int sum1=0, sum2=0, sum3=0; int x, y, z; scanf("%d ...

  7. 2019.04.13 python基础

    第一节    主要讲python背景  没什么要注意的  了解记住概念就好 python官网  python.org  自带shell  可以运行python代码 在IDLE中怎么运行代码 新建文本  ...

  8. MySQL Backup mydumper

    生产环境中有一实例每天使用mysqldump备份时长达到了2个小时53分钟,接近3个小时,还不算上备份文件归档的时间,这个时间对于逻辑备份来说有点久.为了提高逻辑备份效率,打算替换为使用mydumpe ...

  9. 大数据Spark+Kafka实时数据分析案例

    本案例利用Spark+Kafka实时分析男女生每秒购物人数,利用Spark Streaming实时处理用户购物日志,然后利用websocket将数据实时推送给浏览器,最后浏览器将接收到的数据实时展现, ...

  10. python 全局变量的import机制

    在之前学习python设计模式(工厂模式实践篇),希望使用全局变量代替c++的宏完成服务自动注册功能时,遇到过一个问题,全局变量的定义和使用放在同一个可执行脚本中的问题.先把有问题的代码晒一下: IS ...