如何在Spock测试中检查在SpringReact类中抛出的异常

ruyhziif  于 2023-02-16  发布在  Spring
关注(0)|答案(1)|浏览(151)

bounty将在3天后过期。回答此问题可获得+50的声誉奖励。BreenDeen正在寻找来自声誉良好来源的答案

我正在尝试测试一个服务,如果在数据库中没有找到结果,该服务将抛出异常。我正在尝试通过抛出NotFoundException来测试没有找到值的情况。下面是该服务。我想测试没有找到结果但在测试中没有抛出预期异常的情况。我已经包含了测试代码段。

@Service
@RequiredArgsConstructor
public class ProductService {
  private final ProductRepository ProductRepository;

  public Mono<Product> getProductById(Long Id){
    return ProductRepository.findProductById(Id)
    .switchIfEmpty(Mono.error(new NotFoundException("No Product found")));
  }
}

下面是我的测试,为简洁起见,省略了不相关的部分

def 'A Product resource by product id which does not exist in db'() {

  given:
                    
  def id = 4444L

  productRepository.findProductById(id) >> Mono.empty()

  when: 'A call to get a Product is made to the service but cannot be found'

  def result = productService.getProductById(id)

  then: 'A NotFoundException is thrown from the service'
  
  // Does not work 
  StepVerifier.create(result).expectError(NotFoundException)
}
plicqrtu

plicqrtu1#

我想您忘记在StepVerifier链的末尾使用verify()。我们需要将verify()或其他变体放在链的末尾。否则,StepVerifier将不会订阅我们的发布服务器。
下面是您的测试场景的一个工作示例:

@ExtendWith(SpringExtension.class)
public class ProductTest {

    @TestConfiguration
    public static class ProductTestConfiguration {

        @MockBean
        public ProductRepository productRepository;

        @Bean
        public ProductService productService() {
            return new ProductService(productRepository);
        }
    }

    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private ProductService productService;

    @Test
    public void when_not_found_ends_with_exception() {
        Long id = 4444L;
        // repository setup
        Mockito.when(productRepository.findProductById(id))
                .thenReturn(Mono.empty());
        // expect error, don't forget to call verify()
        StepVerifier.create(productService.getProductById(id))
                .expectError(NotFoundException.class)
                .verify();
    }
}

您可以看到测试已通过:

如果使用更改存储库设置

// return not empty, return new product
Mockito.when(productRepository.findProductById(id))
                .thenReturn(Mono.just(new Product()));

然后测试按预期失败:

相关问题