class Foo {
ReturnParameters function1(int a, int b) {
function2(a, b);
}
ReturnParameters function2(int a , int b) {
// body of this function...
}
}
I am creating a Junit test with Mockito and only want to test function1() and want to mock the returns from function2()
Below is my TestCase Class
class FooTest{
Foo foo = mock(Foo.class);
@Test
public void function1test(){
Mockito.when(foo.function2(1,2)).thenReturn(new ReturnParameters(100));
ReturnParameters actualResult = foo.function1(1,2);
int expectedResult = 100;
AssertEquals(expectedResult , actualResult.getStatus());
}
}
I am getting this error message that actualResult is a null value.
Can you please help?
You are attempting to partially stub the methods in a class. In order to do this, you must use Spy instead of Mock.
Here is some sample code (that assumes you are using Junit5 and uses doReturn.when instead of when.thenReturn):
@ExtendWith(MockitoExtension.class)
class TestFoo
{
@Spy
private Foo spyClassToTest;
@BeforeEach
public void before()
{
// stub the function 2 call. The function 1 call is still "live"
doReturn(new ReturnParameters(100)).when(spyClassToTest).function2(1, 2);
}
@Test
public void function1_descriptionOfTheTestScenario_returns100()
{
ReturnParameters actualResult;
int expectedResult = 100;
// Perform the test
actualResult = spyClassToTest.function1(1, 2);
assertNotNull(actualResult);
assertEquals(expectedResult, actualResult.getStatus());
}
}
I don't know the domain but maybe its a good idea to split your functions into different classes. It should solve this issue in a clean way. Spy should also work though.
You can partially mock a class by using @Spy
as mentioned in the other answer by DwB .
Or you can just provide a default answer when invoking mock()
:
// import org.mockito.Answers;
Foo foo = mock(Foo.class, Answers.CALLS_REAL_METHODS);
This also works when using the annotations:
@Mock(answer = Answers.CALLS_REAL_METHODS)
Foo foo;
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.