1

我目前正在尝试测试一种创建对象数组的方法,然后以对象数组作为参数对对象执行方法。每次我尝试这样做时,我都会遇到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 框架。

4

1 回答 1

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实例实际上没有被篡改。

于 2013-04-23T23:19:36.867 回答