簡體   English   中英

如何在不實現存根類的情況下為 Mockito 的接口生成間諜?

[英]How can I generate a spy for an interface with Mockito without implementing a stub class?

所以我有以下界面:

public interface IFragmentOrchestrator {
    void replaceFragment(Fragment newFragment, AppAddress address);
}

如何使用mockito創建一個spy ,允許我將ArgumentCaptor對象掛鈎到對replaceFragment()調用?

我試過

    IFragmentOrchestrator orchestrator = spy(mock(IFragmentOrchestrator.class));

但是 mockito 抱怨“Mockito 只能模擬可見和非 final 類。”

到目前為止,我想出的唯一解決方案是在創建spy之前實現接口的實際模擬。 但這違背了模擬框架的目的:

public static class EmptyFragmentOrchestrator implements IFragmentOrchestrator {
    @Override
    public void replaceFragment(Fragment newFragment, AppAddress address) {

    }
}

public IFragmentOrchestrator getSpyObject() {
    return spy(new EmptyFragmentOrchestrator());
}

我錯過了一些基本的東西嗎? 我一直在瀏覽文檔但沒有找到任何東西(但我可能是瞎的)。

間諜是指您想在現有實現上覆蓋存根。 這里你有一個裸接口,所以看起來你只需要mock

public class MyTest {
  @Captor private ArgumentCaptor<Fragment> fragmentCaptor;
  @Captor private ArgumentCaptor<AppAddress> addressCaptor;

  @Before
  public void setup() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testThing() {
    IFragmentOrchestrator orchestrator = mock(IFragmentOrchestrator.class);

    // Now call some code which should interact with orchestrator 
    // TODO

    verify(orchestrator).replaceFragment(fragmentCaptor.capture(), addressCaptor.capture());

    // Now look at the captors
    // TODO
  }
}

另一方面,如果你真的想監視一個實現,那么你應該這樣做:

IFragmentOrchestrator orchestrator = spy(new IFragmentOrchestratorImpl());

這將調用IFragmentOrchestratorImpl上的實際方法,但仍允許使用verify進行攔截。

我們可以使用org.mockito.Mock注釋來做到這org.mockito.Mock

import org.mockito.Mock;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.when;

public class Test {
    @Mock
    private TestInterface mockTestInterface;

    @Test
    public void testMethodShouldReturnTestString() {
        String testString = "Testing...";

        when(mockTestInterface.testMethod()).thenReturn(testString);

        assertThat(mockTestInterface.testMethod(), is(testString));
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM