我正在寻找一种在执行我的测试类之前执行一些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
脚本就好了。在测试执行之前提供这些脚本的方法是否存在?