【发布时间】:2019-10-16 16:43:19
【问题描述】:
我正在寻找一种在执行我的测试类之前执行一些 SQL 脚本的方法。使用 Spring,我可以轻松地使用 @Sql 注释来注释我的测试类(或测试方法)。我还没有找到任何特定的方法来对 Micronaut 做同样的事情。
我发现的唯一方法是在测试方法本身中以编程方式手动填充数据,但根据我的经验,有时您必须执行多次插入来测试单个案例。
我想出了以下代码来测试 REST 控制器:
代码
@Validated
@Controller("/automaker")
public class AutomakerController {
private AutomakerService automakerService;
public AutomakerController(AutomakerService automakerService) {
this.automakerService = automakerService;
}
@Get("/{id}")
public Automaker getById(Integer id) {
return automakerService.getById(id).orElse(null);
}
@Get("/")
public List<Automaker> getAll() {
return automakerService.getAll();
}
@Post("/")
public HttpResponse<Automaker> save(@Body @Valid AutomakerSaveRequest request) {
var automaker = automakerService.create(request);
return HttpResponse
.created(automaker)
.headers(headers -> headers.location(location(automaker.getId())));
}
@Put("/{id}")
@Transactional
public HttpResponse<Automaker> update(Integer id, @Body @Valid AutomakerSaveRequest request) {
var automaker = automakerService.getById(id).orElse(null);
return Objects.nonNull(automaker)
? HttpResponse
.ok(automakerService.update(automaker, request))
.headers(headers -> headers.location(location(id)))
: HttpResponse
.notFound();
}
}
测试
@Client("/automaker")
public interface AutomakerTestClient {
@Get("/{id}")
Automaker getById(Integer id);
@Post("/")
HttpResponse<Automaker> create(@Body AutomakerSaveRequest request);
@Put("/{id}")
HttpResponse<Automaker> update(Integer id, @Body AutomakerSaveRequest request);
}
@MicronautTest
public class AutomakerControllerTest {
@Inject
@Client("/automaker")
AutomakerTestClient client;
@Test
public void testCreateAutomakerWhenBodyIsValid() {
var request = new AutomakerSaveRequest("Honda", "Japan");
var response = client.create(request);
assertThat(response.code()).isEqualTo(HttpStatus.CREATED.getCode());
var body = response.body();
assertThat(body).isNotNull();
assertThat(body.getId()).isNotNull();
assertThat(body.getName()).isEqualTo("Honda");
assertThat(body.getCountry()).isEqualTo("Japan");
}
@Test
public void testUpdateAutomakerWhenBodyIsValid() {
var responseCreated = client.create(new AutomakerSaveRequest("Chvrolet", "Canada"));
assertThat(responseCreated.code()).isEqualTo(HttpStatus.CREATED.getCode());
var itemCreated = responseCreated.body();
assertThat(itemCreated).isNotNull();
var responseUpdated = client.update(itemCreated.getId(), new AutomakerSaveRequest("Chevrolet", "United States"));
assertThat(responseUpdated.code()).isEqualTo(HttpStatus.OK.getCode());
var itemUpdated = responseUpdated.body();
assertThat(itemUpdated).isNotNull();
assertThat(itemUpdated.getName()).isEqualTo("Chevrolet");
assertThat(itemUpdated.getCountry()).isEqualTo("United States");
}
}
我可以使用带有@Before 注释的方法来填充我需要的所有数据,但是能够像使用Spring 一样使用*.sql 脚本真的很棒。有没有办法在测试执行之前提供这样的*.sql 脚本?
【问题讨论】: