lundi 7 décembre 2015

Mock inner instance on class to test

I am writing some test cases using Mockito. I am facing a problem, I looked for the solution on the net but I did not find a clear answer.

I made up the smallest example.

Given the following classes I want to mock all calls to the method getMessage on the ClassB on all instances of this type.

public class ClassA {

private ClassB b = new ClassB("From ClassA");

int methodToTest() {
    System.out.println("methodToTest use instqnce ClassB " + b.getMessage());
    return -1;
}

}

class ClassB {

private String message;

/**
 * 
 */
public ClassB(final String msg) {
    this.message = msg;
}

/**
 * @return the message
 */
public String getMessage() {
    return message;
}

/**
 * @param message the message to set
 */
public void setMessage(final String message) {
    this.message = message;
}
}

What I tried but it did not work is the following:

public class ClassATest {

@Test
public void testOK1() {
   ArgumentCaptor<ClassB> captorClassB = ArgumentCaptor.forClass(ClassB.class);
   Mockito.doReturn("MOCK message").when(captorClassB.capture()).getMessage();

   ClassA a = new ClassA();
   assertTrue(a.methodToTest() == -1);
}
}

@Test
public void testOK2() {
    Mockito.doReturn("MOCK message").when(Mockito.any(ClassB.class)).getMessage();

    ClassA a = new ClassA();
    assertTrue(a.methodToTest() == -1);
}
}

My question is firstly whether it is possible. Secondly, how? Shall I refactor the code?

Any comments are welcomed.

Aucun commentaire:

Enregistrer un commentaire