javaunit-testingjunitmockingmockito

Mock an object inside a method in JUnit


I'm trying to get to grips with JUnit & Mockito etc.

I currently have a method with the below line.

ObjectMetadata metadata = getMetadata(path.toString());

Is there any way I can mock it? I've tried things like the below

Whitebox.setInternalState(<mock of class>, "metadata", "abc");

but I just get

org.powermock.reflect.exceptions.FieldNotFoundException: No instance field named "metadata" could be found in the class hierarchy of com.amazonaws.services.s3.model.ObjectMetadata.

I think it's because previous use of Whitebox.setInternalState was with variables.

Any info. that might get me started would be appreciated.


Solution

  • If the method is protected then you dont need to use Powermockito, plain vanilla Mockito is enough and spying would do the trick here. Assuming the test class is in the same package as the production one, just in the src/test/java dir.

    ClassUnderTest classUnderTestSpy = Mockito.spy(new ClassUnderTest()); // spy the object 
    
    ObjectMetadata objectMetadataToReturn = new ObjectMetadata();
    
    doReturn(objectMetadataToReturn).when(classUnderTestSpy).get(Mockito.any(String.class));
    

    I used any() matcher for the input but you can use a concrete value also.

    Update If you cannot see the method then you would need to create an inner class that extends the prod one, implement the get method:

    public class Test{
    
      ObjectMetadata objectMetadataToReturn = new ObjectMetadata();
    
      @Test
      public void test(){
          ClassUnderTestCustom classUnderTestCustom  = new ClassUnderTestCustom();
    
          // perform tests on classUnderTestCustom  
      }
    
      private class ClassUnderTestCustom extends ClassUnderTest{
    
         @Override
         public String getMetadata(String path){
            return objectMetadataToReturn ;
         }
      }
    
    }