Junit对springMvc的测试问题

胃在烧 发布于 2017/07/07 16:02
阅读 118
收藏 1

现在项目想增加对springMvc的controller层的测试,调试后发现有个问题无法解决,请大神帮忙。

代码如下:

controller层代码:

项目的url为(括号里是参数)

/loginController.do?login{userLoginName=admin}{userPassward=admin}

@Controller
@RequestMapping("/loginController")
public class LoginController {
	Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private LoginService loginService;

	@RequestMapping(params = "login")
	@ResponseBody
	public AjaxResult login(AjaxResult jsonResult, SessionModel sessionModel, HttpSession session) {
		loginService.login(jsonResult, sessionModel, session);
		session.setAttribute(Constant.SESSION_MODEL_KEY, sessionModel);
		return jsonResult;
	}
}

其中SessionModel用于接收登录参数,正常在浏览器登录是没问题的。

Junit代码:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:springMvc.xml", "classpath:spring.xml" })
@SuppressWarnings("unused")
public class LcpJunitBase {
	public MockHttpServletRequest request;
	public MockHttpServletResponse response;

	@Before
	public void setup() {
		request = new MockHttpServletRequest();
		request.setCharacterEncoding("UTF-8");
		response = new MockHttpServletResponse();
	}

	/**
	 * @Title: setUpBeforeClass
	 * @Description: 初始化数据库
	 * @throws java.lang.Exception
	 * @date 2017-7-7 上午10:27:20
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		String url = "jdbc:oracle:thin:@192.168.103.93:1521/jhemr";
		ComboPooledDataSource dataSource = null;
		try {
			dataSource = new ComboPooledDataSource();
			dataSource.setUser("jhlcpv6");
			dataSource.setPassword("jhlcpv6");
			dataSource.setJdbcUrl(url);
			dataSource.setDriverClass("com.p6spy.engine.spy.P6SpyDriver");// 用p6spy监控sql
			dataSource.setInitialPoolSize(5);
			dataSource.setMinPoolSize(5);
			dataSource.setMaxPoolSize(30);
			dataSource.setMaxStatements(50);
			dataSource.setMaxIdleTime(0);
			dataSource.setAcquireRetryAttempts(5);
			dataSource.setAcquireRetryDelay(1000 * 60);
			dataSource.setCheckoutTimeout(5000);
			// 连接失败后保持连接状态
			// dataSource.setBreakAfterAcquireFailure(true);
			dataSource.getConnection();
		} catch (PropertyVetoException e) {
			LoggerUtil.error(DbPoolUtil.class, "create database error,please check you config :url=" + url);
			dataSource = null;
		} catch (SQLException e) {
			LoggerUtil.error(DbPoolUtil.class, "create database error,please check you config :url=" + url);
			dataSource = null;
		}
		SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
		builder.bind("java:comp/env/jdbc/jhlcp", dataSource);
		builder.activate();
	}

}
public class LoginControllerTest extends LcpJunitBase {
	@Autowired
	private WebApplicationContext wac;

	private MockMvc mockMvc;

	@Before
	public void setup() {
		this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
	}

	/**
	 * Test method for
	 * {@link com.goodwillcis.jhlcp.controller.LoginController#login(com.goodwillcis.jhlcp.model.AjaxResult, com.goodwillcis.jhlcp.model.SessionModel, javax.servlet.http.HttpSession)}
	 * .
	 * 
	 * @throws Exception
	 */
	@Test
	public void testLogin() throws Exception {
		// jhlcp/loginController.do?login{userLoginName=admin}{userPassward=admin}{hospitalId=40068980X4}
		ResultActions resultActions = mockMvc.perform(post("/loginController.do?login").param("userLoginName", "admin")
				.param("userPassward", "admin")
				.contentType(MediaType.APPLICATION_FORM_URLENCODED)
				.accept(MediaType.parseMediaType("application/json;charset=UTF-8")));
		resultActions.andExpect(status().isOk());
		AjaxResult result = (AjaxResult) resultActions.andReturn().getModelAndView().getModel();
		Assert.assertEquals(1, result.getStatus());
	}
}

测试后代码报错为:

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver handleNoSuchRequestHandlingMethod
警告: No matching handler method found for servlet request: path '/loginController.do', method 'POST', parameters map['login' -> array<String>[[null]], 'userLoginName' -> array<String>['admin'], 'userPassward' -> array<String>['admin'], 'hospitalId' -> array<String>['40068980X4']]

后来我把controller的方法注释改成

@RequestMapping("/login")

然后测试时候url改成

mockMvc.perform(post("/loginController/login")

才通过测试。

请问controller中的方法注释为

@RequestMapping(params = "login")

这种写法的时候测试时候的url该怎么写,或者还需要配置哪些东西。

加载中
0
温安适
温安适
/loginControllerlogin

最好写/login 比较好 

胃在烧
胃在烧
我也发现了。。。
返回顶部
顶部