如何使用Mockito / PowerMockito在内部类中测试逻辑



我有以下类测试的类。

public class ClassToTest {
    private View view;
    public ClassToTest(View view) {
        this.view = view;
    }
    public void init() {
        view.add(new ParamClass.OnSomething() {
            @Override
            public void onSomethingElse() {
                view.doSomeWork();
            }
        });
    }
}

查看为

public class View {
    public void add(OnSomething onSomething) {
    }
    public void doSomeWork() {
    }
}

我嘲笑了视图对象,但是没有线索如何测试标记为"在此处进行某些逻辑的逻辑"的逻辑

paramclass是最终的。

public final class ParamClass {
  public interface onSomething {
    public void onSomethingElse();
  }
}

没有更改来源,有没有办法使用Mockito/PowerMockito进行单位测试?

我正在尝试验证DosomeWork((

的调用
@RunWith(PowerMockRunner.class)
@PrepareForTest({ ClassToTest.class })
public class TestClass {
    @Mock View view;
    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    @Test
    public void test() throws Exception {
        ClassToTest classToTest = new ClassToTest(view);
        PowerMockito.doCallRealMethod().when(view).add(Mockito.any(ParamClass.OnSomething.class));
        PowerMockito.whenNew(ParamClass.OnSomething.class)
                .withAnyArguments()
                .thenReturn(new ParamClass.OnSomething() {
                    @Override
                    public void onSomethingElse() {
                        view.doSomeWork();
                    }
                });
        classToTest.init();
        Mockito.verify(view, Mockito.times(1)).doSomeWork();
    }
}

其投掷异常

java.lang.ArrayIndexOutOfBoundsException: 0
at org.powermock.api.mockito.internal.expectation.DefaultConstructorExpectationSetup.withAnyArguments(DefaultConstructorExpectationSetup.java:66)
at com.linkedin.android.lite.animations.TestClass.test(TestClass.java:29)

我弄清楚了如何做。更新答案。

public class TestClass {
    @Mock View view;
    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }
    @Test
    public void test() throws Exception {
        ClassToTest classToTest = new ClassToTest(view);
        classToTest.init();
        ArgumentCaptor<ParamClass.OnSomething> captor =
        ArgumentCaptor.forClass(ParamClass.OnSomething.class);
        verify(view).add(captor.capture());
        ParamClass.OnSomething onSomething = captor.getValue();
        onSomething.onSomethingElse();
        Mockito.verify(view, Mockito.times(1)).doSomeWork();
    }
}

您正试图测试什么?如果内部有代码onsomethingelse调用其他对象/方法,则可以简单地模拟所有其他呼叫,然后使用mockito.verify(mockobjecthere(.methodcalled((在所谓的方法上,如果您只想实现行为的测试。

相关内容

  • 没有找到相关文章

最新更新