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中添加依赖。

spring整合junit报错-LMLPHP

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

spring整合junit报错-LMLPHP

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();
}
}
04-21 09:21