我对Junit还是很陌生,我正尝试在Junit中测试isApproved方法。我正在模拟使用when和thenReturn的isDateValidOfData方法
Mockito.when(isDateValidOfData(anyLong(), anyString()).thenReturn(true);
这将获取indexOutOfBounds异常。这里在参数匹配器上调用serviceClass,因此在数据列表中不返回任何内容。我只想知道是否有一种方法可以模拟数据并使用Mockito和Junit对其进行测试。
使用间谍获取相同类的对象以调用该方法。
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");
}
}
答案 0 :(得分:1)
由于使用的是@InjectMocks,因此应在类级别使用@RunWith(MockitoJUnitRunner.class),一切都会正常运行。
如果要使用@RunWith(SpringRunner.class),请使用@MockBean和@SpyBean编写测试。
编辑:
您可以看到更多@RunWith(SpringRunner.class)与@RunWith(MockitoJUnitRunner.class)here
另外,您可以选中此Why we use Mockitojunitrunner class in our junit test?