I have the below code
class A {
public int someMethod(int someParameters....) {
........// some implementation
}
}
class B extends A {
public int someMethodFromB(int someParameters....) {
........// some implementation
return someMethod(someParameters....);
}
}
I am writing test for class B for someMethodFromB and I want to mock someMethod which we are returning the value. How can I test the code as B is extending A.
I have tried the below 2 approaches but did not work out
@Test
public void testSomeMethodFromB() throws Exception {
ContextData contextData = mock(ContextData.class);
SomeObject obj = mock(SomeObject.class);
B b = spy(new B());
doReturn(obj).when(b).someMethod(obj, contextData, false);
Assert.assertNotNull(b.someMethodFromB(someAnotherObj, contextData, Optional.of("someString")));
}
and this one too
@Mock
private A a;
@InjectMock
private B b;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSomeMethodFromB() throws Exception {
ContextData contextData = mock(ContextData.class);
SomeObject obj = mock(SomeObject.class);
when(a.someMethod(obj, contextData, false)).thenReturn(obj);
b.someMethodFromB(someAnotherObj, contextData, Optional.of("someString"));
}
might be me but this:
makes no sense to me, what are SomeObject.class and SomeAnotherObj? SomeAnotherObj gets passed as a parameter but is never defined? You mock SomeObject.class but never mention it, is it just something you need for test, unrelated to the question? I think you could do something like this:
again, maybe im mistaken, its been a long day at work, but i dont quite understand the examples Good luck anyhow!