【问题标题】:Use result of one mock call in another在另一个中使用一个模拟调用的结果
【发布时间】:2021-12-29 16:26:58
【问题描述】:

如何将一个模拟的结果使用/注入到另一个模拟中?

我觉得我做错了

int 参数始终为空

我使用 spy 是因为我测试的方法是无效的。 我可以使用 mockito 吗?

@RunWith(MockitoJUnitRunner.class)
public class Test {

    @Mock
    Utils utils;

    @Mock
    Custom custom;

    @Spy
    @InjectMocks
    MyService service;

    @Test
    public void test(){
        Mockito.when(utils.get("p")).thenReturn(1); //use result of it in the next mock call

        Mockito.when(custom.isValid(1)).thenReturn(true); //custom use 1 here
        Mockito.doCallRealMethod().when(service).doIt("p");

        service.doIt("p");

        Mockito.verify(service,Mockito.times(1)).doIt("p");
    }
}
@Service
public class MyService {
    Utils utils;
    Custom custom;

    public MyService(Utils utils) {
        this.utils = utils;
    }

    public void doIt(String value){
        int param = utils.get(value);

        if(custom.isValid(param)){
            //do it
        }
    }
}

【问题讨论】:

  • 您模拟了调用Mockito.when(utils.get("p")).thenReturn(1);,但您的示例调用显示utils.get("param") - 您确定您在模拟正确的方法调用吗?
  • 如何在服务类中初始化Utils bean?它不适用于测试和引导
  • 更新了示例。 @DmitriiBykov 通过构造函数

标签: java junit mockito spring-test


【解决方案1】:

您实际上不需要监视MyService。您可以简化测试并让它发挥作用:

@RunWith(MockitoJUnitRunner.class)
public class Test {

   @Mock
   Utils utils;

   @InjectMocks
   MyService service;

    @Test
    public void test(){
        // Arrange
        Mockito.doReturn(1).when(utils.get("p"));
        Mockito.when(custom.isValid(1)).thenReturn(true);

        // Act
        service.doIt("p");

        // Assert
        Mockito.verify(utils, Mockito.times(1)).get("p");
        // You should also confirm that whatever is done in `if(param==1)` is actually done
    }
}

【讨论】:

  • 嗨,我更新了示例。请看一下
  • 我已经更新了我的答案。 “我使用 spy 是因为我测试的方法无效”,这不是使用 spy 的正当理由。除非您实际上是在模拟 MyService 方法(您不应该这样做),否则您不需要使用间谍。
  • 很高兴能帮上忙!
【解决方案2】:

你在模拟错误的参数,这样改变你的测试:

public class Test {

   @Mock
   Utils utils;

   @InjectMocks
   MyService service;


   @BeforeEach
   void setUp(){
     initMocks(this);
   }

   @Test
   public void test(){  
       Mockito.when(utils.get(any())).thenReturn(1);

       service.doIt("p");

       Mockito.verify(utils).get(any());
   }
}

而不是any(),您可以放置​​任何其他变量,但它应该与您调用服务的变量相同

【讨论】:

  • 嗨,我更新了示例。请看一下
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 2015-10-14
  • 2014-09-28
相关资源
最近更新 更多