利用junit对springMVC的Controller进行测试(转)

平时对junit测试service/DAO层已经很熟悉不过了,如果不了解,可以猛戳这里,但是我们要测试controller层,不能总重启服务器吧,那么我们就用junit4模拟请求,测试controller层的方法。

代码1:直接Controller调用方法

import static org.junit.Assert.*;

import java.sql.SQLException;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.zz.login.web.LoginController;

/**
 * @author zhzh
 * 2015-4-7
 */
@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration({"classpath*:/beans.xml","classpath*:/spring-mvc.xml"})  
public class TestController {

	// 模拟request,response  
    private MockHttpServletRequest request;  
    private MockHttpServletResponse response;   
      
    // 注入loginController  
    @Autowired  
    private LoginController loginController ;  
      
    // 执行测试方法之前初始化模拟request,response  
    @Before    
    public void setUp(){    
        request = new MockHttpServletRequest();      
        request.setCharacterEncoding("UTF-8");      
        response = new MockHttpServletResponse();      
    }         
    /** 
     *  
     * @Title:testLogin 
     * @Description: 测试用户登录   
     */  
    @Test  
    public void testLogin() {   
        try {  
        	request.setParameter("userName", "admin");
        	request.setParameter("password", "2");
            assertEquals("login",loginController.loginIn(request,response)) ;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}

代码2:调用请求路径

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.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author zhzh
 * 2015-4-7
 */
@RunWith(SpringJUnit4ClassRunner.class)  
@WebAppConfiguration  
@ContextConfiguration({"classpath*:/beans.xml","classpath*:/spring-mvc.xml"}) 
//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否  
@TransactionConfiguration(defaultRollback = true)  
@Transactional 
public class TestController2 {
	@Autowired  
    private WebApplicationContext wac;  
  
    private MockMvc mockMvc; 
    
    @Before  
    public void setup() {   
        this.mockMvc = webAppContextSetup(this.wac).build();  
    } 
    
    @Test  
    public void testLogin() throws Exception {  
        mockMvc.perform((post("/loginTest").param("userName", "admin").param("password", "1"))).andExpect(status().isOk())  
                .andDo(print());  
    } 
    
    /*@Test  
    //有些单元测试你不希望回滚  
    @Rollback(false)  
	public void testInsert() throws Exception {  
	    mockMvc.perform((post("/insertTest"))).andExpect(status().isOk())  
	            .andDo(print());  
	} */
}
注意:import static 的spring类
     代码3:

LoginController代码片段

/**
	 * 登录入口
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/loginTest", method = RequestMethod.POST)
	public String loginTest(HttpServletRequest request,HttpServletResponse response){
		String account = request.getParameter("userName");
		String password = request.getParameter("password");
		if (account.equals("admin")&&password.equals("1")){
			return "index";
		}else{
			return "login";
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Junit 5 是一个流行的 Java 单元测试框架,它提供了一套功能强大且易于使用的工具,用于编写和执行单元测试。Spring MVC 是 Spring 框架中的一个模块,用于开发基于 MVC(Model-View-Controller)架构的 Web 应用程序。 在使用 Junit 5 进行 Spring MVC 的单元测试时,你可以通过以下步骤来进行配置和编写测试代码: 1. 添加 Junit 5 和 Spring MVC 的相关依赖到你的项目中。这包括 junit-jupiter、spring-test 等库。 2. 创建一个测试类,并使用 `@ExtendWith(SpringExtension.class)` 注解来启用 Spring 支持。 3. 使用 `@WebMvcTest` 注解标记测试类,以指定要测试的控制器或控制器类。 4. 使用 `@Autowired` 注解将需要进行测试的 Spring Bean 注入到测试类中。 5. 使用 Junit 5 提供的断言方法,如 `assertEquals`、`assertNotNull` 等,编写测试方法来验证你的控制器的行为和输出结果。 以下是一个简单的例子: ```java import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @ExtendWith(SpringExtension.class) @WebMvcTest(YourController.class) public class YourControllerTest { @Autowired private MockMvc mockMvc; @Test public void testYourController() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/your-endpoint")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.content().string("Expected Result")); } } ``` 在这个例子中,我们使用 `@WebMvcTest` 注解指定了要测试的控制器类 `YourController`,并使用 `MockMvc` 对象来模拟发送 HTTP 请求和验证响应。 当你运行这个测试类时,它将启动一个 Spring 上下文,并使用指定的控制器类进行测试。你可以编写更多的测试方法来覆盖不同的场景和逻辑。 希望这个例子能够帮助你开始使用 Junit 5 进行 Spring MVC 的单元测试。如果有任何进一步的问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值