有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想测试一个类的方法。 为此,我需要模拟该类的另一个方法,它是从构造函数调用的。 我还必须将模拟对象传递给构造函数。 当我不使用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();
  }

共 (1) 个答案

  1. # 1 楼答案

    在实例化过程中调用A类中的getC()方法时,对它进行模拟永远不会只使用EasyMock。你基本上是在一个对象被创建之前调用它,所以它不能工作

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

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

    @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版本,但所有这些都将在PowerMock Home Page中介绍