欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mockito 测试Controller

程序员文章站 2022-07-08 16:14:34
...

Controller类

LoginController.java

package org.jinglun.base.controller;

import javax.validation.Valid;

import org.jinglun.base.dto.LoginDto;
import org.jinglun.base.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value="/login")
public class LoginController {

    private LoginService loginService;

    @Autowired
    LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    @RequestMapping(value={"", "/"}, method=RequestMethod.POST)
    public String login(@Valid LoginDto dto, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            return "login";
        }
        if (loginService.login(dto)) {
            return "home";
        } else {
            return "login";
        }
    }
}

 

测试类

LoginControllerTest.java

package org.jinglun.base.controller;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.any;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

import org.jinglun.base.dto.LoginDto;
import org.jinglun.base.service.LoginService;
import org.junit.Test;
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;
import org.springframework.test.web.servlet.MockMvc;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:spring-web.xml","classpath:spring-dao.xml","classpath:spring-mybatis.xml","classpath:spring-service.xml"})
public class LoginControllerTest {

    @Test
    public void testLogin() throws Exception {
        try {
            LoginService service = mock(LoginService.class);
            LoginController controller = new LoginController(service);
            when(service.login(any(LoginDto.class))).thenReturn(true);

            MockMvc mockmvc = standaloneSetup(controller).build();
            mockmvc.perform(post("/login")
                    .param("username", "admin")
                    .param("password", "admin"))
                    .andExpect(view().name("home"));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}