MOCKITO:如何将方法调用作为参数

发布于 2025-02-01 12:51:54 字数 909 浏览 5 评论 0原文

我想创建一种方法,该方法将生成nibes nibes nibes的,以启用固执模拟迭代模拟。例如,如何通过,方法调用,例如:mock.getId()作为方法的参数?

我已经使用了下一个方法,但是它不起作用,它传递了方法调用的结果

public class MyMock {

   private String id;

   public MyMock(String id) {
       this.id = id;
   }
   
   public String getId() {
       return this.id;
   }
}

...

@Test
public void stubExample() {
   MyMock mock = Mockito.mock(MyMock.class);
   List<MyMock> mocksList = stubbingMethod(() -> mock.getId());
   Assert.assertEquals(3, mocksList.size());
}

private List<MyMock> stubbingMethod(Supplier<String> sup) {
   Mockito.when(sup.get()).thenReturn("id1")
                .thenReturn("id2")
                .thenReturn("id3");

   return List.of(
          new MyMock(sup.get()),
          new MyMock(sup.get()),
          new MyMock(sup.get()));
}

,并且每次抛出NullPoInterException。

谢谢!

I want to create a method that will generate OngoingStubbing for N times to enable stubbing mocks iteratively. How can I pass, method call, for instance: mock.getId() as a parameter to a method?

I have used next approach, but it doesn't work, it passes result of method invocation

public class MyMock {

   private String id;

   public MyMock(String id) {
       this.id = id;
   }
   
   public String getId() {
       return this.id;
   }
}

...

@Test
public void stubExample() {
   MyMock mock = Mockito.mock(MyMock.class);
   List<MyMock> mocksList = stubbingMethod(() -> mock.getId());
   Assert.assertEquals(3, mocksList.size());
}

private List<MyMock> stubbingMethod(Supplier<String> sup) {
   Mockito.when(sup.get()).thenReturn("id1")
                .thenReturn("id2")
                .thenReturn("id3");

   return List.of(
          new MyMock(sup.get()),
          new MyMock(sup.get()),
          new MyMock(sup.get()));
}

And every time throws NullPointerException.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执手闯天涯 2025-02-08 12:51:54

我有另一个问题,描述有点模棱两可。因此,对于迭代固定使用,接下来是:

public void stub(List<MyMock> mocks, List<String> ids) {
     IntStream.range(0, mocks.size()).boxed()
               .map(index ->
                       Mockito.when(mock.getId()).thenReturn(ids.get(index)));
}

例如。只有以相同的顺序映射您的模拟和ID。

I had another problem, description is a little bit ambiguous. So, for iterative stubbing use next:

public void stub(List<MyMock> mocks, List<String> ids) {
     IntStream.range(0, mocks.size()).boxed()
               .map(index ->
                       Mockito.when(mock.getId()).thenReturn(ids.get(index)));
}

For example. Only in case your mocks and ids are mapped in the same order.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文