0
votes

I have the following class

public class EmailManager{

  protected String getEmailContent(String content,String image){
     String result = content.toPrettyLook(); //this is an inner method
     result+="<img src='" + +"' />";
     return result;
  }

  protected String getImageLocation(String image){
      //write image to disc
      return newLocation;
  } 
}

public class EmailManagerTest{

  EmailManager emailManager;

  @Test
  public void testEmailContent(){
     String result = emailManager.getEmailContent("Hello World");
  }
}
  1. What annotation should I put above EmailManager? @Spy @Mock or @Autowired?

  2. How can I tell Mockito not to execute getImageLocation (the method that is being called by getEmailContent) and always returns instead of it "new location"? I saw many articles and got confused between "when" "stub" "doReturn"

1

1 Answers

3
votes

What you want here is a Spy : a partially mocked object. You want to test the real getEmailContent() method, but you want to stub the getImageLocation() method of the same object. So the test should look like

public class EmailManagerTest{

    private EmailManager emailManager;

    @Test
    public void testEmailContent(){
        emailManager = spy(new EmailManager());
        doReturn("new location").when(emailManager).getImageLocation("someImage");
        String result = emailManager.getEmailContent("Hello World", "someImage");
        // assertions ...
    }
}

If you want to use annotations to let Mockito create the spy for you, then you can use the Spy annotation:

@Spy
private EmailManager emailManager = new EmailManager();

Don't forget to add a @Before method which calls MockitoAnnotations.initClass(this).

Mockito is very well documented. Read the documentation.