首页 > 解决方案 > 无法使用 Mockito.when 存根 ReactiveMongoRepository

问题描述

我是响应式编程的新手。我想为反应式 mongo 存储库编写一些测试用例。我试图存根一些查询方法并使用 step-verifier 来检查响应,但我的测试失败了。

ItemReactiveRepository.java

public interface ItemReactiveRepository extends ReactiveMongoRepository<Item, String> {
Mono<Item> findByDescription(String description);
}

项目.java

@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Item {

@Id
private String id;
private String description;
private Double price;
}

ItemReactiveRepositoryTest.java

@DataMongoTest
@RunWith(SpringRunner.class)
public class ItemReactiveRepositoryTest {

@Autowired
private ItemReactiveRepository itemReactiveRepository;


@Test
public void findById() {

    Item itemForTest = new Item("ABC", "Samsung TV", 405.0);

    Mockito.when(itemReactiveRepository.findById("ABC")).thenReturn(Mono.just(itemForTest));

    StepVerifier.create(itemReactiveRepository.findById("ABC"))
            .expectSubscription()
            .expectNextMatches(item -> item.getPrice() == 405.0)
            .verifyComplete();
 }
}

运行测试时收到的错误

org.mockito.exceptions.misusing.MissingMethodInvocationException: when() 需要一个参数,该参数必须是“模拟的方法调用”。例如:when(mock.getArticles()).thenReturn(articles);

此外,可能会出现此错误,因为:

  1. 你存根其中之一:final/private/equals()/hashCode() 方法。这些方法不能被存根/验证。不支持在非公共父类上声明的模拟方法。
  2. 在 when() 中,您不会在模拟上调用方法,而是在其他对象上调用方法。

测试反应流时使用存根有什么限制吗?或任何其他标准机制来测试上述场景?

标签: unit-testingmockitospring-webflux

解决方案


ItemReactiveRepository itemReactiveRepository=org.mockito.Mockito.mock(ItemReactiveRepository.class);

这对我有用。


推荐阅读