2017-04-11 65 views
0

我正在編寫單元測試,以找到位置附近的銀行的方法。 我嘲笑這個班級,並試圖調用這些方法。 但是,控制不會去執行它的方法。 以下是單元測試用例。無法執行模擬類的測試方法

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

這需要真正的方法,但我上面嘲笑的方法,在執行像真正的一個。手段'嘲弄的方法'沒有返回我要求他們返回。

那麼,我在這裏做什麼錯? 爲什麼方法沒有執行?

+0

'searchClass'是一個模擬,你要實現的目標是奇怪 – 2017-04-11 13:43:06

+0

謝謝評論。但我是Mockito新手。只是稱它奇怪不會幫助我成長。而是提到什麼是錯誤的,以便用戶可以使用它。 – user252514

+1

你能分享你正在編寫junit的代碼的相關部分嗎? – djames

回答

0

該方法沒有被調用,因爲你正在模擬調用它。您應該在實際對象上調用該方法。

或者你可以在調用方法之前使用類似的東西。

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

但我認爲這不是你應該寫測試的方式。你不應該首先嘲笑SearchClass。相反,在SearchClass中會有一個依賴關係,它會爲您提供地址和地理位置。你應該嘲笑那個特定的依賴。

+0

我早些時候嘗試過。讓我編輯我的問題。 – user252514

0

OK,讓我們說我們有這樣的代碼:

class Foo { 
    // has a setter 
    SomeThing someThing; 

    int bar(int a) { 
     return someThing.compute(a + 3); 
    } 
} 

我們要測試Foo#bar(),但有向SomeThing的依賴,我們就可以使用mock:

@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

一些閱讀:

相關問題