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. python摸爬滚打之day15----初识类

    1.面向对象和面向过程 面向过程: 以事物的流程为核心.  优点: 负责的事物流程化, 编写简单; 缺点: 可拓展性差. 面向对象: 一切以对象为核心. 对象里封装着一切. 优点: 可拓展性强; 缺点 ...

  2. C语言中tm结构体

    struct tm { int tm_sec; /* Seconds. [0-60] (1 leap second) */ int tm_min; /* Minutes. [0-59] */ int ...

  3. Python3学习之路~5.10 PyYAML模块

    Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation

  4. java框架之SpringCloud(3)-Eureka服务注册与发现

    在上一章节完成了一个简单的微服务案例,下面就通过在这个案例的基础上集成 Eureka 来学习 Eureka. 介绍 概述 Eureka 是 Netflix 的一个子模块,也是核心模块之一.Eureka ...

  5. java之beanutils使用

    介绍 BeanUtils是Apache Commons组件的成员之一, 主要用于简化JavaBean封装数据的操作. ​ 点击下载依赖 jar 包 使用 有如下 javabean : package ...

  6. Python subprocess.Popen() error (No such file or directory)

    这个错误很容易引起误解,一般人都会认为是命令执行了,但是命令找不到作为参数对应的文件或者目录.其实还有一层含义,就是这个命令找不到,命令找不到,也会报没有这个文件或者目录的错误. 为什么找不到这个命令 ...

  7. 下载工具axel 和 mwget

    axel, yum安装或者apt-get安装 但有时axel不行,需要上wget,但单线程的太慢,需要安装mwget.apt-get -y install intltoolwget http://ja ...

  8. 利用spring实现服务启动就自动执行某些操作的2种方式

    第一种方式,用bean的init-method属性 <bean class="com.emax.paycenter.log.LogBridge" init-method=&q ...

  9. windows将文件夹映射为虚拟磁盘

    subst X: e:123 将e盘下的123文件夹映射为x盘,123的容量即x盘容量 subst X: /t 删除映射的x盘

  10. select报错

    query = query.Where(c => c.MfcKey==temp); int hhho = query.Count(); query = from q in query join ...