spring整合junit报错
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>
参考资料:
(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报错的更多相关文章
- spring整合quartz报错
今天spring整合quartz报错,最后一步步排查,发现是和redis依赖冲突,最后redis升级了一下,问题解决. 总结:发现问题,逐一排查,如果是整合问题,报类加载不到的错误,大概率是和其他组件 ...
- Spring整合Hibernate报错:annotatedClasses is not writable or has an invalid setter method
Spring 整合Hibernate时报错: org.springframework.beans.factory.BeanCreationException: Error creating bean ...
- Spring+Hibernate4 Junit 报错No Session found for current thread
论坛上有另外一篇更全面的帖子,jinnianshilongnian写的:http://www.iteye.com/topic/1120924 本文的环境是: spring-framework-3.1 ...
- spring+hibernate整合:报错org.hibernate.HibernateException: No Session found for current thread
spring+hibernate整合:报错信息如下 org.hibernate.HibernateException: No Session found for current thread at o ...
- Spring整合Redis时报错:java.util.NoSuchElementException: Unable to validate object
我在Spring整合Redis时报错,我是犯了一个很低级的错误! 我设置了Redis的访问密码,在Spring的配置文件却没有配置密码这一项,配置上密码后,终于不报错了!
- 【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 ...
- weblogic 整合cxf 报错:cannot create a secure XmlInputFactory
weblogic 整合cxf 报错:cannot create a secure XmlInputFactory ================================ ©Copyright ...
- Spring boot 启动报错 Failed to auto-configure a DataSource
1.Spring boot 启动报错 Failed to auto-configure a DataSource 参考资料https://blog.csdn.net/liuyinfei_java/ar ...
- 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 ...
随机推荐
- (转载)中文Appium API 文档
该文档是Testerhome官方翻译的源地址:https://github.com/appium/appium/tree/master/docs/cn官方网站上的:http://appium.io/s ...
- java框架之MyBatis(2)-进阶&整合Spring&逆向工程
进阶内容 准备 jdbc.url=jdbc:mysql://192.168.208.192:3306/test?characterEncoding=utf-8 jdbc.driver=com.mysq ...
- aop execution 表达式解析
execution(* com.sample.service.impl..*.*(..)) 解释如下: 符号 含义execution()表达式的主体:第一个”*“符号表示返回值的类型任意:com.sa ...
- node(03)--利用 HTTP 模块 URl 模块 PATH 模块 FS 模块创建一个 WEB 服务器
Web 服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,可以向浏览器等 Web 客户端提供文档,也可以放置网站文件,让全世界浏览:可以放置数据文件,让全世界下载.目前最主流的三个 We ...
- Flask最强攻略 - 跟DragonFire学Flask - 第十四篇 Flask-SQLAlchemy
前不久刚刚认识过了SQLAlchemy,点击这里复习一下 当 Flask 与 SQLAlchemy 发生火花会怎么样呢? Flask-SQLAlchemy就这么诞生了 首先要先安装一下Flask-SQ ...
- Eclipse进度条出现“Remote System Explorer Operation”解决方法
Eclipse进度条出现“Remote System Explorer Operation”解决方法
- 从路由器镜像中提取uImage头信息
uImage header为64字节,文件头为27 05 19 56 hexdump -C a.bin | grep "27 05 19 56" 或者 hd aa.bin | gr ...
- mysql awr v1.0.3修正说明以及发布
本版本计划修正或者包含如下内容: 1.innodb buffer_pool只是分配的vm大小,实际并不一定真正使用这么多,还可能会有内存泄露,故调整从innodb_buffer_pool_stats获 ...
- 节约内存:Instagram的Redis实践(转)
Instagram可以说是网拍App的始祖级应用,也是当前最火热的拍照App之一,Instagram的照片数量已经达到3亿,而在Instagram里,我们需要知道每一张照片的作者是谁,下面就是Inst ...
- java excel大数据量导入导出与优化
package com.hundsun.ta.utils; import java.io.File; import java.io.FileOutputStream; import java.io.I ...