我创建了一个尚未实现完整CRUD的简单API,但是我发现了第一个问题。 当我用大张旗鼓地运行我的API时,所有方法都很好用,但是当我对Post方法运行测试时,似乎它拒绝了我的请求。
测试:
@RunWith(SpringRunner.class)
@WebFluxTest(controllers = CustomerController.class)
@Import(CustomersService.class)
public class CustomerControllerTest {
@MockBean(answer = Answers.RETURNS_DEEP_STUBS)
private CustomersService mockedService;
@Autowired
private WebTestClient client;
...
@Test
public void endpointAddWhenGivenGoodJsonShouldReturn201() {
//todo: fix test, it works in API.
int id = -1;
Customer customer1 = new Customer(id, "name", new Address("city", "street", "zcode"));
Mockito
.when(mockedService.addCustomer(customer1))
.thenReturn(Mono.just(customer1));
client.post()
.uri("/api/add/")
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Flux.just(customer1), Customer.class)
.exchange()
.expectStatus().isCreated();
}
@Test
public void endpointAddWhenGivenGoodJsonShouldReturn400() {
int id = -1;
Customer customer1 = new Customer(id, "name", new Address("city", "street", "zcode"));
Mockito
.when(mockedService.addCustomer(customer1))
.thenReturn(Mono.empty());
client.post()
.uri("/api/add/")
.accept(MediaType.APPLICATION_JSON_UTF8)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.body(Mono.just(customer1), Customer.class)
.exchange()
.expectStatus().isBadRequest();
}
}
两个测试似乎都返回isNotFound()。
服务类别:
@Service
public class CustomersService implements CustomersServiceInterface {
private final RepositoryInterface customersRepository;
public CustomersService(RepositoryInterface customersRepository) {
this.customersRepository = customersRepository;
}
public Flux<Customer> getCustomerById(int id) {
return customersRepository.getById(id);
}
public Flux<Customer> getAllCustomers() {
return customersRepository.getAll();
}
public Mono<Customer> addCustomer(Customer newCustomer) {
return customersRepository.saveCustomer(newCustomer);
}
}
那是被嘲笑的,所以存储库没关系。
我该如何修复测试以查看api的作用,从而使ergo返回良好的状态码(201和400)?