我目前正在尝试测试创建对象数组的方法,然后在对象数组作为参数的对象上执行方法。每次我尝试这样做时,我都会收到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框架。
答案 0 :(得分:1)
嗯。你不能只是模拟你作为参数传递的Bar
实例,期望用update
数组调用Bar[]
,返回你想要的任何内容,等等吗?
这可能是这样的:
@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
实例实际上没有被篡改。