I'm pretty new to Junit and I'm trying to test isApproved method in Junit. I'm am mocking isDateValidOfData method using when and thenReturn using
Mockito.when(isDateValidOfData(anyLong(), anyString()).thenReturn(true);
This is getting an indexOutOfBounds exception. Here the serviceClass is being called on argument matchers so returning nothing in the list of data. I just want to know is there a way to mock the data and test it using Mockito and Junit.
Using spy to get the object of the same class to call the method.
MyClass {
//Service class calls the repository to fetch data.
@Autowired
ServiceClass serviceClass;
public boolean isApproved(Long id, String code) {
// Validation is done on the arguments
//if id is of a particular type then return true by default
//if code is in a list already present then continue with the below code or else return true by default.
return isDateValidOfData(Long id, String code);
}
public boolean isDateValidOfData(Long id, String code) {
List<Data> data = serviceObject.getData(id, code);
LocalDateTime eDate = data.get(0).getEDate();
LocalDateTime rDate = data.get(0).getRDate();
// check if eDate and rDate is greater than current date, if yes return true or return false
}
}
@RunWith(SpringRunner.class)
TestClass {
@InjectMocks
MyClass myClass;
@Test
public void isApprovedTest() {
MyClass myClass1 = Mockito.spy(myClass);
Mockito.when(myClass1.isDateValidOfData(anyLong(), anyString())).thenReturn(true);
Assert.assertTrue(myClass1.isApproved(1234L, "1234");
}
}