我目前正在尝试测试一种创建对象数组的方法,然后以该对象数组作为参数对对象执行方法。每次我尝试这样做时,我都会收到 constructorNotFound
错误。如果不清楚,我深表歉意,但希望您能够通过下面的示例理解我在说什么。
public class Bar {
public final String name;
public final Bar[] barList;
public Bar(String name) {
this.name = name;
barList = null;
}
public Bar update(Bar[] bar) {
Bar newBar = new Bar(name);
newBar.barList = bar;
return newBar;
}
}
public class Foo {
public static Bar internalMethod( Bar oldBar) {
// in reality this method does a lot more
// I just kept it simple for demonstration purposes
Bar[] bar = new Bar[2];
oldBar = oldBar.update(bar);
// about 15-20 method calls with oldBar as a parameter
// and require mocking
return oldBar;
}
}
这是测试类:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Bar[].class)
public class testFoo {
@Test
public void test() throws Exception {
Bar[] barArr = new Bar[2];
PowerMock.expectNew(Bar[].class).andReturn(barArr);
PowerMock.replay(Bar[].class);
Bar bar = new Bar("name");
Bar newBar = Foo.internalMethod(bar);
// assume there are many more checks to make sure that the appropriate
// methods were called and the changes were made
assertEquals("name", newBar.name);
assertNull(newBar.barList[0]);
assertNull(newBar.barList[1]);
}
}
有谁知道如何处理这样的情况吗?
我意识到类设计并不理想,但不幸的是,我无法更改它。我正在使用 PowerMock 1.4.10,并且无法访问mockito 框架。
最佳答案
嗯。难道您不能只是模拟作为参数传递的 Bar
实例,期望使用 Bar[]
数组调用 update
,返回您想要的任何内容,等等?
这可能看起来像这样:
@Test
public void test() throws Exception {
Bar bar = new Bar("name").update(new Bar[2]);
Bar barMock = EasyMock.createMock(Bar.class);
EasyMock.expect(barMock.update(EasyMock.aryEq(new Bar[2]))).andReturn(bar);
EasyMock.replay(barMock);
Bar newBar = Foo.internalMethod(barMock);
EasyMock.verify(barMock);
assertEquals("name", newBar.name);
assertNull(newBar.barList[0]);
assertNull(newBar.barList[1]);
}
这看起来也有点有趣,因为断言都检查在测试开始时设置的 Bar
实例。但考虑到 internalMethod
做了更多的事情,它会验证返回的 Bar
实例实际上没有被篡改。
关于java - 如何期望使用 PowerMock 创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16174031/