如何将 JUnit 测试写入我的 Spring-MVC 控制器 类?

How I can write JUnit tests to my Spring-MVC Controller classes?

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

用户控制器:

@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);

 }

用户服务:

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;
    }
}

您可以使用 Spring 的 MockMvc。查看详情:https://spring.io/guides/gs/testing-web/

Another useful approach is to not start the server at all, but test only the layer below that, where Spring handles the incoming HTTP request and hands it off to your controller. That way, almost the full stack is used, and your code will be called exactly the same way as if it was processing a real HTTP request, but without the cost of starting the server. To do that we will use Spring’s MockMvc, and we can ask for that to be injected for us by using the @AutoConfigureMockMvc annotation on the test case: