简体   繁体   中英

mockito `when` not returning correct mocked list

I have a test class TestService1 contains test methods and two service classes Service1 and Service2 . I am writing JUnit test for method isResourceAlreadyPresent in Service2 class which includes call to Service1 class method. 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.

    @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. I suppose you have not set the Service1 Object properly in Service 2 and its taking some other value.

Use Reflection to set the Service1 object in the Service2 class before you call any test methods on Service2. Reflection should be used only for testing purposes and not in the code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM