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



我正在编写单元测试,用于查找我所在位置附近的银行的方法。我嘲笑了这个类,并试图调用这些方法。但是,控制不会执行它的方法。下面是单元测试用例。

@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();

这称为真正的方法,但我上面模拟的方法像真正的方法一样执行。意味着"模拟方法"不会返回我要求他们返回的内容。

那么,我在这里做错了什么?为什么方法不执行?

该方法

未被调用,因为您在模拟上调用它。您应该在实际对象上调用该方法。

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

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(),但是有一个依赖SomeThing,然后我们可以使用一个模拟:

@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.
    } 
}
使用

模拟,我们能够避免使用真实的SomeThing

一些阅读:

  • http://www.vogella.com/tutorials/Mockito/article.html
  • https://github.com/mockito/mockito/wiki

相关内容

最新更新