【发布时间】:2019-09-27 22:14:13
【问题描述】:
我是单元测试和 TDD 的新手。我想为我在 Spring Boot 中编写的控制器和服务类应用单元测试。
我已经使用教程实现了测试类。但是,我无法成功实施。我已经包含了我当前的代码。
控制器
@RestController
@RequestMapping("/api")
public class MyController {
private static final Logger LOGGER = LoggerFactory.getLogger(AdminController.class);
@Autowired
MyService myService;
@PostMapping("/create")
public ResponseEntity<?> createUser(@RequestHeader("Authorization") String token,
@RequestBody User user){
ResponseDTO finalResponse = new ResponseDTO();
try {
ResponseEntity<?> entity = myService.create(token, user);
finalResponse.setMessageCode(entity.getStatusCode());
finalResponse.setMessage("Success");
finalResponse.setError(false);
ResponseEntity<ResponseDTO> finalEntity = ResponseEntity.ok().body(finalResponse);
return finalEntity;
} catch (Exception e) {
finalResponse.setMessageCode(HttpStatus.EXPECTATION_FAILED);
finalResponse.setMessage(e.getMessage());
finalResponse.setError(true);
ResponseEntity<ResponseDTO> finalEntity =
ResponseEntity.ok().body(finalResponse);
return finalEntity;
}
}
ResponseDTO
public class ResponseDTO {
private HttpStatus messageCode;
private String message;
private String messageDetail;
private Object body;
private boolean error;
//setters and getters
}
当前测试类
@RunWith(SpringRunner.class)
public class MyControllerTest {
private MockMvc mockMvc;
@InjectMocks
private MyController myController;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(myController).build();
}
@Test
public void testCreateUser() throws Exception {
mockMvc.perform(post("/api/create")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.*", Matchers.hasSize(1)));
}
}
当我运行测试类时,我得到WARN Resolved [org.springframework.web.bind.MissingRequestHeaderException: Missing request header 'Authorization' for method parameter of type String]
我在这里做错了什么?任何帮助将不胜感激。
【问题讨论】:
-
您错过了
.header("Authorization", "some value")的 mockMvc。顺便说一句,.content("your testing payload")也错过了。 -
如果你正在为控制器编写测试,这不是单元测试。
标签: java rest unit-testing spring-boot junit