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); } } 
5
  • 1
    Pass in a RestTemplate instance to the constructor of SenderServiceImpl so that you can mock it, instead of creating it inside the class Commented Apr 19, 2019 at 12:02
  • PS : I cannot make changes in the code as its not owned by me Commented Apr 19, 2019 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 (static.javadoc.io/org.mockito/mockito-core/2.27.0/org/mockito/…), but something is seriously wrong if you're supposed to unit test code that you're not allowed to modify. Commented Apr 19, 2019 at 12:06
  • Possible duplicate of Mockito: Mock private field initialization Commented Apr 19, 2019 at 12:14
  • You can possibly use powermock (automationrhapsody.com/mock-new-object-creation-powermock). But this is not clean solution. Commented Apr 19, 2019 at 12:14

1 Answer 1

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); // ... } 
Sign up to request clarification or add additional context in comments.

2 Comments

What fix would you suggest, if not injecting the instance?
omg silly me, it supposed to be "this code needs dependency injection"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.