我正在尝试测试我的服务 ProductService,但它失败,表明断言是 MonoJust 而不是我期望的产品。我不知道为什么测试因该问题而失败。我希望能得到一些帮助来解决这个问题
下面是我的存储库、服务和测试代码
class Product {
String name
String productCode
int quantity
double price
}
interface ProductRepository extends ReactiveMongoRepository<Product, Long> {
}
class ProductService {
ProductRepository productRepository;
ProductService(ProductRepository productRepository) {
this.productRepository = productRepository
}
Mono<Product> saveProduct(Mono<Product> product){
return product.flatMap ( _prod -> productRepository.save(_prod))
}
}
import reactor.core.publisher.Mono
import reactor.test.StepVerifier
import spock.lang.Specification
import static org.assertj.core.api.Assertions.assertThat
class ProductServiceSpec extends Specification{
ProductRepository productRepository = Mock()
ProductService productService = new ProductService(productRepository)
def "should save a product to database"() {
given:
def product = new Product("T-Shirt", "LG-TSHRT", 1220, 7.77)
def productMono = Mono.just(product)
productMono.flatMap {productRepository.save(it) } >> productMono
when:
Mono<Product> productResult = productService.saveProduct(productMono)
then:
StepVerifier.create(productResult)
.expectNext(config)
.assertNext(_product -> {
assertThat(product.getName()).isEqualTo("T-Shirt")
})
.expectComplete()
.verify()
}
}
如果我是你,我会使用expectNextMateches。 类似这样的事情
StepVerifier.create(productResult)
.expectNextMatches(product -> product.getName().isEqualTo("T-Shirt"))
.expectComplete()
.verify()
请记住,您可以使用 && 或 || 添加多个匹配项运营商