简体   繁体   English

使用 Mockito 间谍模拟类中的方法

[英]Mocking a method within a class using Mockito spy

Refering to mock methods in same class引用同一个类中的模拟方法

class Temp() {

public boolean methodA(String param) {

     try {

         if(methodB(param))
               return true;

         return false;
     } catch (Exception e) {
           e.printStackTrace();
     }
}
}

The test class测试类

@Test
public void testMethodA() {

Temp temp = new Temp();
Temp spyTemp = Mockito.spy(temp);

Mockito.doReturn(true).when(spyTemp).methodB(Mockito.any()); 
boolean status = temp.methodA("XYZ");

Assert.assertEquals(true, status);
}

When calling the real class temp to methodA should return the mocked method B value.当调用真实类 temp 到 methodA 时,应该返回模拟的方法 B 值。 Thus returning true.因此返回true。 Why is this incorrect.为什么这是不正确的。 I encounter the same problem.我遇到了同样的问题。 I want to run the test on the real class and not for mock object as suggested by the answer.我想在真正的班级上运行测试,而不是按照答案的建议运行模拟对象。 I want to run the class methodA and expect the mocked object spyTemp methodB value when it is called我想运行类 methodA 并在调用时期望模拟对象 spyTemp methodB 值

Here is the Problem: methodA() you´re callint is from temp and you´ve defined a returning value from tempSPY .这是问题:你调用的 methodA methodA()来自temp并且你已经定义了一个来自tempSPY的返回值。

So you need to call tempSpy.methodA() and then it´s returning the value of methodB() you´ve defined.所以你需要调用tempSpy.methodA()然后它返回你定义的methodB()的值。

Here the solution if methodB() is public - spy temp/cut and call it this way:这里的解决方案 if methodB()public - spy temp/cut 并以这种方式调用它:

// temp = cut
@Test
public void testMethodA_valid() {
    // given
    Temp spyTemp = Mockito.spy(temp);
    boolean expected = true;
    Mockito.doReturn(expected).when(spyTemp).methodB(Mockito.any(String.class)); 

    // when
    boolean actual = spyTemp.methodA("XYZ");

    // then (faster readable)       
    Mockito.verify(spyTemp, times(1)).methodB(any(String.class))
    Mockito.verifyNoMoreInteraction(<ALL YOUR MOCKS HERE>);
    Assert.assertEquals(expected, is(equalTo(actual)));
}

If methodB() is private you can´t define what it should return.如果methodB()是私有的,你就不能定义它应该返回什么。 Then is´t just this and if error occures then methodB() got wrong behaviour:那么不仅如此,如果发生错误,则methodB()出现错误的行为:

@Test
public void testMethodA_valid() {
    // given
    boolean expected = true;

    // when
    boolean actual = temp.methodA("XYZ");

    // then (faster readable)       
    Assert.assertEquals(expected, is(equalTo(actual)));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM