0

Please help, this mock isn't working :

class ClassBeingTested {

    private AnotherClass anotherClass;

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

// My test

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();
}
user1071840
  • 3,522
  • 9
  • 48
  • 74

2 Answers2

0

Mocking worked as soon as I replaced Integer.class with actual expected int value.

   new NonStrictExpectations(anotherClassObject) {{
        invoke(anotherClassObject, "targetMethod", 5); result = 100;
    }};
user1071840
  • 3,522
  • 9
  • 48
  • 74
0

How about this way of mocking with 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();
}