1

I want to mock my RestTemplate which uses RestTemplateBuilder. Hence, I am using restclienttest.

Unfortunately, I am not able to mock the resttemplate call. when Sup supExpected = myService.getDetails("1234") is called, it's performing the complete backend call instead resulting what I have asked to do.

Instead of resulting the custom json string "SD", it is performing actual GET call and giving the response from backend.

Here is my junit code:

@RunWith(SpringRunner.class)
@RestClientTest(MyService.class)
public class TestMyServiceApplication {


    @Autowired
    private MyService myService; 

     @Autowired
        private RestTemplate restTemplate;

    @Autowired 
    private MockRestServiceServer server;       

    @Before public void setUp() { 
     server= MockRestServiceServer.createServer(restTemplate); }

    @Test
    public void ReturnSupplierSuccessfully() {

        String SD= "{\"SUP\": {\"LNR\": \"1234\",\"NAME1\": \"RestClient\"}]}}";
        this.server
        .expect(requestTo("abc.net/service/v1?lnr=1234"))
        .andExpect(method(HttpMethod.GET))
        .andRespond(withSuccess(SD, MediaType.APPLICATION_JSON));

        Sup supExpected = myService.getDetails("1234");

        server.verify();
        assertNotNull(supExpected);
    }

Can anyone help me what's wrong in my code?

Smile
  • 3,832
  • 3
  • 25
  • 39
Manju
  • 21
  • 2
  • Please attempt the following . 1) Remove the `setUp()` method. 2) modify `requestTo("/service/v1?lnr=1234)` – R.G Apr 23 '20 at 05:59
  • @R.G unfortunately that didnt help me. i have redesigned our service class. then it started working . – Manju May 02 '20 at 12:41

1 Answers1

0

Try to put @Mock annotation on top of RestTemplate and other respective service classes.

@Mock
Alien
  • 15,141
  • 6
  • 37
  • 57
  • In this case i am using @ restclienttest , inorder to use @ Mok : i have to use mockito framework. Since i have RestTemplateBuilder in my service, mockito didn't help me hence i wanted to try with @ restclienttest – Manju Apr 16 '20 at 07:12