0

I have a SenderService class as shown below.

I am using the restTemplate object to call a url. How should I write a junit test for this by ONLY using Mockito ?

I have already tried creating a spy for my class but its not working

@Service
public class SenderServiceImpl implements SenderService{

    @Autowired
    private Logger logger;

    private RestTemplate restTemplate = new RestTemplate();

     @Override
    public void sendNotification(SenderNotification notification) {
        try {
            HttpEntity sendRequestBody = new HttpEntity<> 
            (notification,headers);
            response = 
            restTemplate.postForEntity(url,sendRequestBody,String.class); 
     }
}
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
Roshni
  • 137
  • 1
  • 2
  • 11
  • 1
    Pass in a `RestTemplate` instance to the constructor of `SenderServiceImpl` so that you can mock it, instead of creating it inside the class – Tim Apr 19 '19 at 12:02
  • PS : I cannot make changes in the code as its not owned by me – Roshni Apr 19 '19 at 12:04
  • 2
    Then why are you testing it? You won't be able to fix any bug you might find anyway. You can use the Mock and InjectMocks annotations (https://static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/Mockito.html#21), but something is seriously wrong if you're supposed to unit test code that you're not allowed to modify. – JB Nizet Apr 19 '19 at 12:06
  • Possible duplicate of [Mockito: Mock private field initialization](https://stackoverflow.com/questions/36173947/mockito-mock-private-field-initialization) – Wojtek Mlodzianowski Apr 19 '19 at 12:14
  • You can possibly use powermock (https://automationrhapsody.com/mock-new-object-creation-powermock/). But this is not clean solution. – Failed Apr 19 '19 at 12:14

1 Answers1

0

I agree with the comments-this code needs dependency injection and should rather be fixed. If you really want to mock field you can use PowerMock or the solution from this question: Mockito: Mock private field initialization

Mockito comes with a helper class to save you some reflection boiler plate code:

import org.mockito.internal.util.reflection.Whitebox;

//...

@Mock
private Person mockedPerson;
private Test underTest;

// ...

@Test
public void testMethod() {
    Whitebox.setInternalState(underTest, "person", mockedPerson);
    // ...
}