0

我想覆盖 JMockit 中先前定义的期望。这就是我尝试过的(见下面的代码)——我有一个私有类,我记录所有常见的期望,并在各种测试方法中重放它。但是,我的一种方法需要大多数常见的期望,除了少数。首先,我调用CommonNonStrictExpectations私有类,然后在 my 中定义测试特定testMethod1的期望,希望我在这里定义的内容覆盖我之前定义的内容。我不认为这种压倒一切的方式有效,有没有一种有效的方式?

//MyClassTest.java
    import MyClass;

    public class MyClassTest {

    @Mocked Someobject object;    

    @Test
    public void testMethod1() throws Exception {
        new CommonNonStrictExpectations() {};
        new NonStrictExpectations() {
            {
                object.getInt(anyInt); returns (-1);
                object.getString(anyInt); returns ("failure");
            }
        };
        System.out.println("position: " + object.getInt(1));
        System.out.println("exec status: " + object.getString(1));
        MyClass m = new MyClass();
        m.method(object, -1);
    }

    private class CommonNonStrictExpectations extends NonStrictExpectations {
        public CommonNonStrictExpectations () throws Exception {
            object.getInt(anyInt); returns (anyInt);
            object.getString(anyInt); returns ("success");
        }
    }
}

//MyClass.java

import Someobject;
public class MyClass {

    public void method (Someobject someobject, int i) {
        String status = someobject.getString(i);
        if (status.equalsIgnoreCase("success")) {
            print(someobject, "success");
        }  else if (status.equalsIgnoreCase("failure")) {
            print(someobject, "failure");
        } else
            print(someobject, "");
    }

    private String print(Someobject someobject, String status) {
        return someobject.printMessage (status);
    }
}

// Someobject.java

public class Someobject {
    public String getString(int i) {
        if (i < 0)
            return "failure";
        else if (i > 0)
            return "success";
        else
            return "";
    }

    public int getInt(int k) {
        return k;
    }

    public String printMessage (String status) {
        return  "status is: " + status;
    }
}
4

0 回答 0