Java 无法从模拟类执行测试方法

Java 无法从模拟类执行测试方法,java,unit-testing,junit,mocking,mockito,Java,Unit Testing,Junit,Mocking,Mockito,我正在编写单元测试来寻找我所在地附近的银行。 我模拟了这个类并试图调用这些方法。 但是,控件不会被方法执行。 下面是单元测试用例 @Test public void testFindBanksByGeo() { String spatialLocation = "45.36134,14.84400"; String Address = "Test Address"; String spatialLocation2 = "18.04706,38.78501";

我正在编写单元测试来寻找我所在地附近的银行。 我模拟了这个类并试图调用这些方法。 但是,控件不会被方法执行。 下面是单元测试用例

@Test
public void testFindBanksByGeo() {

    String spatialLocation = "45.36134,14.84400";
    String Address = "Test Address";
    String spatialLocation2 = "18.04706,38.78501";

    // 'SearchClass' is class where 'target' method resides
    SearchClass searchClass = Mockito.mock(SearchClass.class);
    BankEntity bank = Mockito.mock(BankEntity.class);

    // 'findAddressFromGeoLocation' and 'getGeo_location' to be mocked. They are called within 'target' method
    when(searchClass.findAddressFromGeoLocation(anyString())).thenReturn(Address);
    when(bank.getGeo_location()).thenReturn(spatialLocation2);

    // 'writeResultInJson' is void method. so needed to 'spy' 'SearchClass' 
    SearchClass spy = Mockito.spy(SearchClass.class);
    Mockito.doNothing().when(spy).writeResultInJson(anyObject(), anyString());

    //This is test target method called. **Issue is control is not going into this method**
    SearchedBanksEntity searchBanksEntity = searchClass.findNearbyBanksByGeoLocation(spatialLocation, 500);

    assertNull(searchBankEntity);
}
我所尝试的也是调用它的真实方法

Mockito.when(searchClass.findNearbyBanksByGeoLocation(anyString(), anyDouble())).thenCallRealMethod();
这调用了real方法,但我上面模拟的方法执行起来就像real方法一样。表示“模拟方法”没有返回我要求它们返回的内容

那么,我到底做错了什么?
为什么方法没有执行?

由于您正在模拟上调用该方法,因此没有调用该方法。应该对实际对象调用该方法

或者您可以在调用该方法之前使用类似的方法

Mockito.when(searchClass.findNearbyBanksByGeoLocation(Mockito.eq(spatialLocation), Mockito.eq(500))).thenCallRealMethod();

但是我认为这不是你应该写测试的方式。首先,你不应该嘲笑SearchClass。相反,SearchClass中会有一个依赖项,它会为您提供地址和地理位置。您应该模拟特定的依赖关系。

好的,假设我们有以下代码:

class Foo {
    // has a setter
    SomeThing someThing;

    int bar(int a) {
       return someThing.compute(a + 3);
    }
}
我们想测试
Foo#bar()
,但是有一个对
某物的依赖,我们可以使用模拟:

@RunWith(MockitoJunitRunner.class)
class FooTest {
    @Mock // Same as "someThing = Mockito.mock(SomeThing.class)"
    private SomeThing someThing,

    private final Foo foo;

    @Before
    public void setup() throws Exception {
        foo = new Foo(); // our instance of Foo we will be testing
        foo.setSomeThing(someThing); // we "inject" our mocked SomeThing
    } 

    @Test
    public void testFoo() throws Exception {
        when(someThing.compute(anyInt()).thenReturn(2); // we define some behavior
        assertEquals(2, foo.bar(5)); // test assertion
        verify(someThing).compute(7); // verify behavior.
    } 
}
使用模拟,我们可以避免使用真正的
东西

一些阅读:


searchClass
是一个模拟类,您想要实现的是奇怪的,谢谢您的评论。但我对莫基托是新手。只是说它奇怪无助于我的成长。更确切地说是什么地方出了问题,这样用户就可以对它进行修改了。您是否可以分享您正在为之编写junit的代码的相关部分?