mherzl
mherzl

Reputation: 6200

Mockito define behavior of mock when it is type cast

In Mockito, is it possible to define the behavior of a mock object in the event that it is type cast, perhaps as one can use Mockito's "when ... thenReturn" functionality to define the behavior of a mock object in the event that of its methods is called?

For example, in the following example class and test...

public class MyClass {
  public String myMethod(ObjectString arg) {
    ans = (String) arg;
    return ans;
  } 
}

public class MyClassTest {
  @Test
  public void myMethod_should_convert_to_string() {
    MyClass testMyClass = new MyClass();
    ObjectString mockObjectString = Mockito.mock(ObjectString.class);
    String expected = "expected string returned";
    Mockito.when(mockObjectString.IS_CAST_TO_STRING).thenReturn(expected);
    String actual = testMyClass.myMethod(mockObjectString);
    Assert.assertEquals(expected, actual);
  }
}

...is there something I can perhaps replace 'IS_CAST_TO_STRING' with that will cause mockObjectString to be cast to the specific value "expected string returned"?

Upvotes: 3

Views: 6824

Answers (1)

Carlos
Carlos

Reputation: 1176

An instance of ObjectString can never be cast to String. String does not inherit from any class called ObjectString nor does it implement any interface called ObjectString. Casting to String will always throw a ClassCastException unless arg is null.

On the other hand, if your class under test looked like this:

public class MyClass {
    public String myMethod(final Object arg) {
        final String ans = (String) arg;
        return ans;
    }
}

Then, you could achieve what you're looking for without Mockito:

@Test
public void myMethod_should_convert_to_string() {
    MyClass testMyClass = new MyClass();
    String expected = "expected string returned";
    String actual = testMyClass.myMethod(expected);
    assertEquals(expected, actual);
}

Upvotes: 1

Related Questions