简体   繁体   中英

Mock method on class extended by another class

I have:

public class A extends B {
    public ObjectC methodToTest() {
        return getSomething(); 
    }
}

/* this class is in other project and compiles in project I want test */
public class B {
    public ObjectC getSomething() {
       //some stuff calling external WS
    }
}

and on test:

@RunWith(MockitoJUnitRunner.class)
public class ATest {

   @Mock
   B bMock;

   @InjectMocks
   A classTotest;

   @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

   @Test
   public void getMethodToTestShouldReturnObjectC() {
        Mockito.when(bMock.getSomething()).thenReturn(new ObjectC());
        assertEquals(classTotest.methodToTest().getClass, ObjectC.class);
   }
}

But when I run test Mockito is calling B (and it fails because calls a ws...)

I read a lot of stuff about this but I can't solve it.

¿How Can I mock getSomething() to return ObjectC?

Mockito.when(bMock.getSomething()).thenReturn(new ObjectC());

This method changes only bMock . It doesn't change any other class B (or A ) instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM