junit 测试Webflux REST API的正确方法

7cjasjjr  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(134)

我第一次使用Webflux和Reactive Mongo构建了一个REST服务。
这是我的控制器和服务工具:
控制器:

@RestController
@RequestMapping("/endpoint/computer")
@RequiredArgsConstructor
public class ComputerEndpoint {

    private final ComputerServiceImpl computerService;

    @PostMapping
    @ResponseStatus(code = HttpStatus.CREATED)
    public Mono<Computer> createNewComputer(@Valid @RequestBody Computer computer) {
        return computerService.create(computer);
    }

    @GetMapping
    public Flux<Computer> findAllComputer() {
        return computerService.findAll();
    }

    @GetMapping("/{id}")
    public Mono<Computer> findOneComputer(@PathVariable("id") String id) {
        return computerService.findById(id);
    }

    @PutMapping("/{id}")
    public Mono<Computer> updateOneComputer(@PathVariable("id") String id, @Valid @RequestBody Computer parsedBody) {
        return computerService.update(id, parsedBody);
    }

    @DeleteMapping("/{id}")
    public Mono<Void> deleteOneComputer(@PathVariable("id") String id) {
        return computerService.deleteById(id);
    }

}

服务实现:

@Service
@RequiredArgsConstructor
public class ComputerServiceImpl implements ComputerService {

    private final ComputerRepository repo;

    @Override
    public Flux<Computer> findAll() {
        return repo.findAll();
    }

    @Override
    public Mono<Computer> findById(String id) {
        return repo.findById(id)
                .switchIfEmpty(Mono.error(new Exception("COMPUTER_NOT_FOUND")));
    }

    @Override
    public Flux<Computer> saveAll(List<Computer> computers) {
        return repo.saveAll(computers);
    }

    @Override
    public Mono<Computer> create(Computer computer) {
        return repo.save(computer);
    }

    @Override
    public Mono<Computer> update(String id, Computer computer) {
        return repo.findById(id)
                .switchIfEmpty(Mono.error(new Exception("COMPUTER_NOT_FOUND")))
                .map(c -> {
                    computer.setId(id);
                    return computer;
                })
                .flatMap(repo::save);
    }

    @Override
    public Mono<Void> delete(Computer computer) {
        return repo.delete(computer);
    }

    @Override
    public Mono<Void> deleteById(String id) {
        return repo.deleteById(id);
    }

    @Override
    public Mono<Void> deleteAll() {
        return repo.deleteAll();
    }
}

而Reactive Stream(Mono和Flux)的原理对我来说是非常新的,然后我尝试使用JUnit 5和Mockito为这些方法编写一些测试。
测试项目:

@ExtendWith(SpringExtension.class)
@WebFluxTest(controllers = ComputerEndpoint.class)
@Import(ComputerServiceImpl.class)
class ComputerEndpointTest {

    @MockBean
    ComputerServiceImpl service;

    @Autowired
    private WebTestClient client;

    @Test
    void createNewComputer() {

        Computer computer = new Computer();
        computer.setName("DESKTOP PC");
        computer.setComputerModel("OptiPlex 7020");
        computer.setComputerSpecs("Q87 Mainboard, i5-4590, 16Gb Ram, 1TB HDD, 256Gb SSD, 300W PSU");

        Mockito.when(service.create(computer)).thenReturn(Mono.just(computer));

        client.post()
                .uri("/endpoint/computer")
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(computer))
                .exchange()
                .expectStatus().isCreated();

        Mockito.verify(service, Mockito.times(1)).create(computer);

    }

    @Test
    void findAllComputer() {

        Computer computer1 = new Computer();
        computer1.setName("DELL WORKSTATION");
        computer1.setComputerModel("OptiPlex 7020 Ultra");
        computer1.setComputerSpecs("Q87 Mainboard, i5-4590, 16Gb Ram, 1TB HDD, 256Gb SSD, 300W PSU");

        Computer computer2 = new Computer();
        computer2.setName("DELL PC");
        computer2.setComputerModel("OptiPlex 7020 Power");
        computer2.setComputerSpecs("Q87 Mainboard, i3-4150, 8Gb Ram, 500Gb HDD, 120Gb SSD, 300W PSU");

        Mockito.when(service.findAll()).thenReturn(Flux.just(computer1, computer2));

        client.get()
                .uri("/endpoint/computer")
                .exchange()
                .expectStatus().isOk()
                .expectBodyList(Computer.class);

        Mockito.verify(service, Mockito.times(1)).findAll();
    }

    @Test
    void findOneComputer() {

        Computer computer = new Computer();
        computer.setId("3b241101-e2bb-4255-8caf-4136c566a962");
        computer.setName("DESKTOP PC");
        computer.setComputerModel("OptiPlex 7020");
        computer.setComputerSpecs("Q87 Mainboard, i5-4590, 16Gb Ram, 1TB HDD, 256Gb SSD, 300W PSU");

        Mockito.when(service.findById(computer.getId())).thenReturn(Mono.just(computer));

        client.get()
                .uri("/endpoint/computer/{id}", computer.getId())
                .exchange()
                .expectStatus().isOk()
                .expectBody(Computer.class);

        Mockito.verify(service, Mockito.times(1)).findById(computer.getId());
    }

    @Test
    void updateOneComputer() {

        Computer computerOrigin = new Computer();
        computerOrigin.setId("3b241101-e2bb-4255-8caf-4136c566a962");
        computerOrigin.setName("DESKTOP PC");
        computerOrigin.setComputerModel("OptiPlex 7020");
        computerOrigin.setComputerSpecs("Q87 Mainboard, i5-4590, 16Gb Ram, 1TB HDD, 256Gb SSD, 300W PSU");

        Computer computerUpdated = new Computer();
        computerUpdated.setName("DELL PC");
        computerUpdated.setComputerModel("OptiPlex 7020 Power");
        computerUpdated.setComputerSpecs("Q87 Mainboard, i3-4150, 8Gb Ram, 500Gb HDD, 120Gb SSD, 300W PSU");

        Mockito.when(service.update(computerOrigin.getId(), computerUpdated))
                .thenReturn(Mono.just(computerOrigin));

        client.put()
                .uri("/endpoint/computer/{id}", computerOrigin.getId())
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(computerUpdated))
                .exchange()
                .expectStatus().isOk();

        Mockito.verify(service, Mockito.times(1)).update(computerOrigin.getId(), computerUpdated);

    }

    @Test
    void deleteOneComputer() {

        Computer computer = new Computer();
        computer.setId("3b241101-e2bb-4255-8caf-4136c566a962");
        computer.setName("DESKTOP PC");
        computer.setComputerModel("OptiPlex 7020");
        computer.setComputerSpecs("Q87 Mainboard, i5-4590, 16Gb Ram, 1TB HDD, 256Gb SSD, 300W PSU");

        Mockito.when(service.deleteById(computer.getId())).thenReturn(Mono.empty());
        System.out.println(service.findById(computer.getId()));

        client.delete()
                .uri("/endpoint/computer/{id}", computer.getId())
                .exchange()
                .expectStatus().isOk();

        Mockito.verify(service, Mockito.times(1)).deleteById(computer.getId());

    }
}

所有的测试都通过了。但是我不确定模拟过程是否正确完成,是否在Mocks中没有任何持久化就达到了预期。特别是在删除测试中,当我怀疑没有持久化就删除其ID的模拟时。
因此问题是,哪种方法是编写React式服务测试的正确方法,以及如何设置期望满足所有要求以真正通过测试?
我可能会混淆自动取款机,但请好心帮助。

mhd8tkvw

mhd8tkvw1#

这看起来不错。只是要记住,你实际上是在测试你的url -〉控制器Map,控制器-〉服务Map,url安全,http动词,有效负载注解等等。
您可能希望为实际的服务实现编写单独的集成测试。

相关问题