【问题标题】:cannot stub ReactiveMongoRepository using Mockito.when无法使用 Mockito.when 存根 ReactiveMongoRepository
【发布时间】: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);

此外,出现此错误的原因可能是:

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

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

【问题讨论】:

标签: unit-testing mockito spring-webflux


【解决方案1】:

您必须为来自import org.mockito.Mock; 的存储库准备模拟,而不是使用@Autowired

@Mock
ItemReactiveRepository itemReactiveRepository;

正如@Thomas 所提到的,您不是在模拟,而是使用DataMongoTest 使用实际的 MongoDB,而是您必须摆脱这一点,只需模拟方法并测试您的服务层。 Autowired 期望所有默认配置和容器准备的 bean 供您使用,但事实并非如此,您必须模拟和使用。

【讨论】:

    【解决方案2】:
    ItemReactiveRepository itemReactiveRepository=org.mockito.Mockito.mock(ItemReactiveRepository.class);
    

    这对我有用。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      相关资源
      最近更新 更多