如何将JUnit测试编写到Spring-MVC Controller类中?

时间:2018-09-30 14:56:07

标签: java spring-mvc junit junit4

我想为我的UserController类编写一个JUnit测试(Java单元),但是我不知道该怎么做。

UserController:

@RestController
@RequestMapping(CompositeController.ENTRY)
public class UserController {
protected final static String ENTRY = "/demo/v1/composite";
private UserService userService;

@Autowired
public UserController(UserService userService) {
    this.userService = userService;
}


 @GetMapping(path = "/isadmin")
 public ResponseEntity<Boolean> checkadmin(@RequestHeader String nickname){

 return userService.checkifadmin(nickname);

 }

UserService:

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

@Service
public interface UserService {
ResponseEntity<Boolean> checkifadmin(String nickname);
}

UserServiceImpl:

public class UserServiceImpl implements UserService {

 private final String userBaseAdress = "http://localhost:7777";
 private final String userBasePath = "/demo/v1/user";

 public ResponseEntity<Boolean> checkifadmin(String nickname) {          
        HttpHeaders headers = new HttpHeaders();            
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("nickname", nickname);       
        HttpEntity<String> entity = new HttpEntity<String>(headers);             
        RestTemplate restTemplate = new RestTemplate();          
        ResponseEntity<Boolean> response = restTemplate.exchange(userBaseAdress + userBasePath + "/isadmin",
                HttpMethod.GET, entity, Boolean.class);         
        return response;
    }
}

1 个答案:

答案 0 :(得分:4)

您可以使用Spring的MockMvc。在以下位置查看详细信息:https://spring.io/guides/gs/testing-web/

  

另一种有用的方法是根本不启动服务器,而是进行测试   只有它下面的一层,Spring处理传入的HTTP   请求并将其交给您的控制器。这样,几乎满   使用了堆栈,您的代码将被完全相同地调用,就像   它正在处理一个真实的HTTP请求,但是没有花费   启动服务器。为此,我们将使用Spring的MockMvc,   可以要求使用   测试案例上的@AutoConfigureMockMvc批注: