【发布时间】:2021-06-30 13:25:03
【问题描述】:
我已经使用 spring boot 编写了 rest api 这是控制器代码
@RestController
public class ApiController {
@Autowired
private ApiService apiService;
@PostMapping(path = "/user", consumes = {MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE})
@LogTransaction
public ResponseEntity<String> user(HttpServletRequest request) {
//apiService.getUser() method call database so i need to mock it
USer user = apiService.getUser(request);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(user);
}
}
这个 api 工作正常,我已经在 groovy 中使用 spock 框架编写了测试
@SpringBootTest
class ApiControllerTest extends Specification {
@Autowired
private ApiController apiController;
@Autowired
private ApiService apiService;
@Autowired
MockMvc mockMvc
def "User api"() {
given:
def User user = new User()
apiService.getUser(_) >> user
when:
def result = mockMvc.perform(MockMvcRequestBuilders
.post("/user")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"username":"demo",
"password":"demo"
}
"""))
.andReturn()
then:
assert result.response.status == HttpStatus.OK.value()
}
这也很好用。方法 apiService.getUser(request) 调用数据库。我想嘲笑它。但它每次都调用数据库。所以我试图在这里使用@Autowired 模拟 apiService.getUser(request) 但它对我不起作用,并且这个方法每次都执行并调用数据库。任何人都可以分享模拟控制器的 apiService.getUser(request) 方法的方法。
【问题讨论】:
标签: spring-boot groovy spock