【问题标题】:Unable to mock a private method via jmockit无法通过 jmockit 模拟私有方法
【发布时间】:2014-11-03 21:40:36
【问题描述】:

请帮忙,这个模拟不起作用:

class ClassBeingTested {

    private AnotherClass anotherClass;

    public void someMethod() {
       int ans = anotherClass.targetMethod(5);
       // Use ans here
    }
}

// 我的测试

ClassBeingTested classObject;
AnotherClass anotherClassObject;

@Before 
public void setup() {
        // Initialize anotherClassObject here

        classObject = new ClassBeingTested(anotherClassObject);

        new NonStrictExpectations(anotherClassObject) {{
            invoke(anotherClassObject, "targetMethod", Integer.class); result = 100;
        }};
}

@Test
public void testSomeMethod() {
   classObject.someMethod();
}

【问题讨论】:

    标签: java unit-testing mocking jmockit


    【解决方案1】:

    当我将 Integer.class 替换为实际的预期 int 值后,模拟就起作用了。

       new NonStrictExpectations(anotherClassObject) {{
            invoke(anotherClassObject, "targetMethod", 5); result = 100;
        }};
    

    【讨论】:

      【解决方案2】:

      用 JMockit 模拟这种方式怎么样?

      import mockit.Injectable;
      import mockit.Tested;
      ...
      
      
      @Tested
      ClassBeingTested classObject;
      @Injectable
      AnotherClass anotherClassObject;
      
      @Before 
      public void setup() {
          new Expectations() {{
              anotherClassObject.targetMethod(anyInt); result = 100;
          }};
      }
      
      @Test
      public void testSomeMethod() {
         classObject.someMethod();
      }
      

      【讨论】:

        猜你喜欢
        • 2016-05-22
        • 1970-01-01
        • 2014-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多