gpt4 book ai didi

java - 如何使用 Mockito/Powermockito 在内部类中对逻辑进行单元测试

转载 作者:行者123 更新时间:2023-11-30 06:38:49 24 4
gpt4 key购买 nike

我有以下类(class)要测试。

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

View 在哪里

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

public void doSomeWork() {
}
}

我已经模拟了 View 对象,但不知道如何测试标记为“此处要测试的一些逻辑”的逻辑

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

关于java - 如何使用 Mockito/Powermockito 在内部类中对逻辑进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44752712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com