Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java EasyMock with withConstructor忽略构造函数内调用的addMockedMethod_Java_Easymock - Fatal编程技术网

Java EasyMock with withConstructor忽略构造函数内调用的addMockedMethod

Java EasyMock with withConstructor忽略构造函数内调用的addMockedMethod,java,easymock,Java,Easymock,我想测试一个类的方法。 为此,我需要模拟类的另一个方法,它是从构造函数调用的。 我还必须将模拟对象传递给构造函数。 当我不使用withConstructor时,它正确地选择了addMockedMethod。 但每当我使用withConstructor时,它就不再使用addMockedMethod中传递的方法。(获取以下代码的异常) 我能做些什么来解决这个问题吗?下面是代码 主要类别: public class A { B b; C c; public A (B _b) {

我想测试一个类的方法。 为此,我需要模拟类的另一个方法,它是从构造函数调用的。 我还必须将模拟对象传递给构造函数。 当我不使用withConstructor时,它正确地选择了addMockedMethod。 但每当我使用withConstructor时,它就不再使用addMockedMethod中传递的方法。(获取以下代码的异常) 我能做些什么来解决这个问题吗?下面是代码

主要类别:

public class A {
   B b;
   C c;
   public A (B _b) {
      b = _b;
      c = getC();
   }
   public void run (String _val) {
     String val = b.getValue();
     //do something
   }
   public static C getC() {
     StaticD.getC();
   }
}
public class StaticD {
   public static C getC() {
      throw new RuntimeException("error");
   }
}
测试等级:

@Test(testName = "ATest")
public class ATest  extends EasyMockSupport {
  public void testRun() {
     B bMock = createMock(B.class);
     expect(bMock.getValue()).andReturn("test");
     replayAll();
     A obj = createMockBuilder(A.class).
        addMockedMethod("getC").
        withConstructor(bMock).
        createMock();
     obj.run();
     verifyAll();
     resetAll();
  }
当在实例化过程中调用
A
类中的
getC()
方法时,在该类中模拟该方法是不可能仅使用EasyMock的。基本上,您试图在对象创建之前对其调用一个方法,因此它无法工作

话虽如此,PowerMock是您在这里的朋友。PowerMock能够模拟EasyMock无法模拟的方法。在这里的示例中,PowerMocks模拟静态方法的能力将有很大帮助

下面是我为您的案例准备的一个示例测试,它将允许您创建您的测试。它还允许您创建一个真正的
对象,因为您不再试图模仿它的任何方法

@RunWith(PowerMockRunner.class) //Tells the class to use PowerMock
@PrepareForTest(StaticD.class) //Prepares the class you want to use PowerMock on
public class ATest extends EasyMockSupport {

    @Test
    public void testRun() {
        final B bMock = createMock(B.class);
        final C cMock = createMock(C.class);

        PowerMock.mockStatic(StaticD.class); //Makes all the static methods of this class available for mocking
        EasyMock.expect(StaticD.getC()).andReturn(cMock); //Adds the expected behaviour
        PowerMock.replay(StaticD.class); //PowerMock to replay the static class

        final A aReal = new A(bMock);

        EasyMock.expect( bMock.getValue() ).andReturn("test");
        replayAll();

        aReal.run("test");

        verifyAll();
        resetAll();
    }
}
所需的PowerMock版本取决于您正在使用的JUnit版本,但所有这些内容都将在