如何将参数传递给模拟的 class 方法?

How to pass param to mocked class method?

我正在使用 mockito 来测试 mu jdk11-springboot 应用程序。

我的应用程序有 class 'ClientRepository' 并且有一个名为 'findById' 的方法,它采用 UUID 类型的参数。

所以该方法看起来像:

 public String findById(UUID id)

现在我嘲笑 class 来测试 :

@MockBean
private ClientRepository clientRepo;

现在我想知道如何在这里传递 UUID 参数:

 Mockito.when(clientRepo.findById(UUID id))
            .thenReturn(dslContext.selectFrom(CLIENT).where(CLIENT.ID.eq(UUID.fromString("3e064b19-ef76-4aea-bf82-e9d8d01daf1c"))).fetch());

有人能帮忙吗?

 Mockito.when(clientRepo.findById(Mockito.any(UUID.class))
            .thenReturn(dslContext.selectFrom(CLIENT).where(CLIENT.ID.eq(UUID.fromString("3e064b19-ef76-4aea-bf82-e9d8d01daf1c"))).fetch());

如果您的模拟只对特定值做出反应,请改用 Mockito.eq("your-uuid-goes-here")

直接传递 mock 预期的值 return 也应该有效。

Mockito.when(clientRepo.findById(<expected UUID>)
    .thenReturn(dslContext.selectFrom(CLIENT).where(CLIENT.ID.eq(UUID.fromString("3e064b19-ef76-4aea-bf82-e9d8d01daf1c"))).fetch());

您可以使用以下构造:

UUID expected = ...;
Mockito.when(clientRepo.findById(Mockito.eq(expected))).thenReturn(...);

如果预期的 UUID 与您在测试中配置的实例不同,这可能是一个很好的解决方案。

要考虑的另一点:

您似乎在使用 JOOQ,但有一个用于存储库的模拟 bean,这意味着您可能测试某种服务(业务逻辑层)。 在这种情况下,也许您根本不需要使用数据库,只需在模拟配置

thenReturn 部分创建一个字符串和 return