[英]mockito `when` not returning correct mocked list
I have a test class TestService1
contains test methods and two service classes Service1
and Service2
. 我有一个测试类TestService1
其中包含测试方法以及两个服务类Service1
和Service2
。 I am writing JUnit test for method isResourceAlreadyPresent
in Service2
class which includes call to Service1
class method. 我正在编写Service2
类中方法isResourceAlreadyPresent
JUnit测试,其中包括对Service1
类方法的调用。 In test method I have written 在测试方法中,我写了
when(testMapper1.getAlreadyPresentResources()).thenReturn(mockTestResourceList);
so when testMapper1.getAlreadyPresentResources()
gets called then it should return mockTestResourceList
which is of size 1 but its not returning this list and it is returning a list but of size 0. 因此,当testMapper1.getAlreadyPresentResources()
时,它应返回大小为1但不返回此列表的mockTestResourceList
,并且返回大小为0的列表。
@ContextConfiguration(locations = "../TestServiceApplicationContext1.xml")
public class TestService1
{
@Autowired
private TestMapper1 testMapper1;
private TestResource testResource1;
private List<TestResource> mockTestResourceList;
private Service1 service1;
private Service1 service2;
@Before
public void setUp()
{
testMapper1 = mock(TestMapper1.class);
service1 = Service1Util.getService();
service1.setTestMapper1(testMapper1);
mockTestResourceList = new ArrayList<TestResource>();
testResource1 = Service1Util.createTestResource();
testResource1.setId(1);
mockTestResourceList.add(testResource1);
}
@Test
public void isResourceAlreadyPresentTest()
{
when(testMapper1.getAlreadyPresentResources()).thenReturn(mockTestResourceList);
boolean isPresent = service2.isResourceAlreadyPresent();
assertTrue(isPresent == true);
}
}
public class Service2
{
... some code ...
public boolean isResourceAlreadyPresent()
{
List<TestResource> resourceList = Service1Util.getAlreadyPresentResources(); //service1.getTestMapper1().getAlreadyPresentResources();
//resourceList size is 0
if(resourceList.size() > 0)
return true;
else
return false;
}
... some code ...
}
What you need to do is to set Service1 object inside your Service2 class for which you are doing the testing before your junit calls any method. 您需要做的是在junit调用任何方法之前,在要对其进行测试的Service2类中设置Service1对象。 I suppose you have not set the Service1 Object properly in Service 2 and its taking some other value. 我想您尚未在Service 2中正确设置Service1对象,并且其取其他值。
Use Reflection to set the Service1 object in the Service2 class before you call any test methods on Service2. 在对Service2调用任何测试方法之前,请使用Reflection在Service2类中设置Service1对象。 Reflection should be used only for testing purposes and not in the code. 反射应仅用于测试目的,而不能用于代码中。
ReflectionTestUtils.setField(service1instance, "service",
serviceobjectvalue);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.