Search code examples
jmockitprivate-methodspartial-mocks

How to match 'any' parameter type while mocking private method in Jmockit


I have a problem while using jmockit for the following scenario. Did a research on the web, but couldn't locate the answers yet.

In the record phase, I am setting the expectation on an object that is partially mocked. While doing it, I would like to mock a private method with single parameter. But i don't really concerned with that parameter value. I want to match all invocation of that particular private method with any instance of argument passed to it. How do I do it in Jmockit. Is there a way?

new Expectations(student) {
    {
        Deencapsulation.invoke(student, "setDepartment", (Department) any);
        result = new Delegate<Student>() {
            public void setDepartment(Department dept) {
                System.out.println("Mocked setDepartment() methodd.....");
            }
        };
    }
};  

In the above code, (Department) any can not be passed, since Deencapsulation.invoke(...) method doesn't accept null value.


Solution

  • Note the API documentation for the any field says:

    "In invocations to non-accessible methods or constructors (for example, with Deencapsulation.invoke(Object, String, Object...)), use withAny(T) instead."

    That is, you need to use withAny(Department.class) with the invoke(...) call.