【发布时间】:2020-10-22 00:07:10
【问题描述】:
我是响应式编程的新手。我想为反应式 mongo 存储库编写一些测试用例。我试图存根一些查询方法并使用 step-verifier 来检查响应,但我的测试失败了。
ItemReactiveRepository.java
public interface ItemReactiveRepository extends ReactiveMongoRepository<Item, String> {
Mono<Item> findByDescription(String description);
}
Item.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);
此外,出现此错误的原因可能是:
- 您存根以下任一方法:final/private/equals()/hashCode() 方法。 这些方法不能被存根/验证。 不支持在非公共父类上声明的模拟方法。
- 在 when() 中,您不会在 mock 上调用方法,而是在其他对象上调用方法。
在测试反应流时使用存根有什么限制吗?或者任何其他标准机制来测试上述场景?
【问题讨论】:
-
不,没有限制,你只是写错了代码。当使用
@DataMongoTest时,您的应用程序将以内存中的mongo 开始,因此您实际上不需要模拟任何东西。如果您想模拟您的存储库,则不需要该注释,并且您需要使用@MockBean实际提供一个模拟。如果你想测试东西,我建议你在问这里之前先查看官方文档如何测试东西。 docs.spring.io/spring-boot/docs/current/reference/htmlsingle/… -
@ThomasAndolf 非常感谢您的澄清
标签: unit-testing mockito spring-webflux