有 Java 编程相关的问题?

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

无法通过JMockJava方法对其进行模拟

请帮助,此模拟不起作用:

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();
}

共 (2) 个答案

  1. # 1 楼答案

    用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();
    }
    
  2. # 2 楼答案

    我一替换Integer,模拟就起作用了。使用实际期望的int值初始化

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