相关疑难解决方法(0)

Mockito Spy'ing对被单元测试的对象

间谍对正在进行单元测试的物体是否有代码味?例如,假设我有一个LineCounter类,其作用是简单地计算字符串中的行数.-

class LineCounter {
    public int getNumLines(String string) {
        String metadata = getStringMetadata(string);

        // count lines in file
        return numLines;
    }

    /** Expensive operation */
    protected String getStringMetadata(String string) {
        // do stuff with string
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想为此编写一个JUnit 4测试来测试该getNumLines方法,同时模拟昂贵的getStringMetadata调用.我决定使用Mockito的间谍机制来getStringMetadata返回虚拟值.

class LineCounterTests {
    @Test public void testGetNumLines() {
        LineCounter lineCounterSpy = Mockito.spy(new LineCounter());

        // Mock out expensive call to return dummy value.            
        Mockito.when(lineCounterSpy.getStringMetadata(Mockito.anyString()).thenReturn("foo");

        assertEquals(2, lineCounterSpy.getNumLines("hello\nworld");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是合理的事吗?我觉得测试一个Spy对象而不是实际的类很奇怪,但是我无法想到反对它的原因.

java junit unit-testing mockito

13
推荐指数
1
解决办法
5917
查看次数

PowerMockito:模拟上的NotAMockException

有点复杂的设置.Robolectric,PowerMockito基于规则的配置.

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
// Using "PrepareOnlyThis" prevents powermock from trying to instrument the whole hierarchy,
// part of which we've ignored (android.os.* in this case)
@PrepareOnlyThisForTest({ServiceCallbackBase.class}) // this class extends Handler, 
// so we need PrepareOnlyThis.  It also has some final methods we need to verify()
public class ServiceBaseTests {

  private class Foo {
    // nothing
  }

  @Rule
  public PowerMockRule rule = new PowerMockRule();

  private ServiceCallbackBase<Object, Foo> setupCallback( boolean hasValidContext, boolean allContextsCanceled …
Run Code Online (Sandbox Code Playgroud)

android powermock robolectric powermockito

12
推荐指数
1
解决办法
3493
查看次数