我有一个测试类TestService1
包含测试方法和两个服务类Service1
和Service2
。我正在为isResourceAlreadyPresent
类中的方法Service2
编写JUnit测试,其中包括对Service1
类方法的调用。在测试方法中我写了
when(testMapper1.getAlreadyPresentResources()).thenReturn(mockTestResourceList);
所以当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 ...
}
答案 0 :(得分:0)
您需要做的是在您的junit调用任何方法之前,在您正在进行测试的Service2类中设置Service1对象。我想你没有在Service 2中正确设置Service1对象,而是取其他值。
在Service2上调用任何测试方法之前,使用Reflection在Service2类中设置Service1对象。反射应该仅用于测试目的而不是代码中。
ReflectionTestUtils.setField(service1instance, "service",
serviceobjectvalue);