开发者社区> 问答> 正文

Junit对springMvc的测试问题?报错

现在项目想增加对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该怎么写,或者还需要配置哪些东西。

展开
收起
爱吃鱼的程序员 2020-06-08 12:46:37 601 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
    /loginControllerlogin

    最好写/login比较好 

    我也发现了。。。
    2020-06-08 12:46:54
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
移动互联网测试到质量的转变 立即下载
给ITer的技术实战进阶课-阿里CIO学院独家教材(四) 立即下载
F2etest — 多浏览器兼容性测试整体解决方案 立即下载