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 ...
随机推荐
- asp.net mvc 简单实现一个账号只能在一个地方登录
原理: 假设用户在机器A登陆后, 这时用户再次在机器B登陆,会以当前会话的SessionID作为键,用户id作为值,插入dictionary集合中,集合再保存在application(保存在服务器 ...
- 6.0-uC/OS-III软件定时器管理
1.软件定时器管理 uC/OS-III提供了软件定时器服务(相关代码在OS_TMR.C中).当设置OS_CFG.H中的OS_CFG_TMR_EN为1时软件定时器服务被使能. 2.uC/OS-III 定 ...
- java框架之SpringBoot(5)-SpringMVC的自动配置
本篇文章内容详细可参考官方文档第 29 节. SpringMVC介绍 SpringBoot 非常适合 Web 应用程序开发.可以使用嵌入式 Tomcat,Jetty,Undertow 或 Netty ...
- python学习之数组二
作用于数组的函数: 通用函数:函数基于元素的,以单元方式作用于数组的,返回的是与原数组具有相同形状的数组. 不通用函数(数组函数):函数能以行或者列的方式作用于整个矩阵:如果没有提供任何参数时,它们将 ...
- day11 python之函数装饰器
一,什么是装饰器? 装饰器本质上就是一个python函数,他可以让其他函数在不需要做任何代码变动的前提下,增加额外的功能,装饰器的返回值也是一个函数对象. 装饰器的应用场景:比如插入日志,性能测试,事 ...
- 关于easy ui 的combobox遍历选中
$.post("fleetAction!queryAllCompanyByCompanyID.do",{"truckCompany.id":companyId} ...
- 网页分享到微博、QQ、QQ空间、微信
<ul id="content-share-list" class="bdsharebuttonbox bdshare-button-style0-16" ...
- vs2017 exe在Linux上运行
1:将vs .netcore控制台项目发布打包(比如文件名为:demo2core.zip,以下会用到) 2:使用XShell软件连接Linux a.在linux上使用命令 id addr找出ip地址 ...
- 对比PG数据库结构是否一致的方法
如果版本升级涉及数据库更新,测试时要对比旧版数据库更新后是否和全新安装的是否一致,但是数据库结构很复杂的时候对比就很麻烦,postgre可以使用以下方法对比:pg_dump.exe –h 数据库IP ...
- ★Pandas 零碎知识
1 修改属性 1.1 修改1列的类型属性: df['总金额'] = pd.to_numeric(df['总金额']) #转变dataframe的1列为数值型 1.2 多列设为数值型:(使用DataFr ...