我有一个包含测试方法的测试类TestService1和两个服务类Service1Service2。我在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 ...
  }

最佳答案

您需要做的是在junit调用任何方法之前,在要对其进行测试的Service2类中设置Service1对象。我想您尚未在Service 2中正确设置Service1对象,并且它没有其他值。

在对Service2调用任何测试方法之前,请使用Reflection在Service2类中设置Service1对象。反射应仅用于测试目的,而不能用于代码中。

ReflectionTestUtils.setField(service1instance, "service",
            serviceobjectvalue);

关于java - 当`mockito`不返回正确的模拟列表时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24164057/

10-10 08:02