0

I'm trying to build one integration test using MockMvc and I want to mock only the RestTemplate used by MyService.java. If I uncomment the code on MyIT.java, this test will fail because the RestTemplate used by MockMvc will be mocked as well.

MyRest.java

@RestController
public class MyRest {

    @Autowired
    private MyService myService;

    @RequestMapping(value = "go", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<String> go() throws IOException {
        myService.go();
        return new ResponseEntity<>("", HttpStatus.OK);
    }
}

MyService.java

@Service
public class MyService {

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }

    public void go() {
        restTemplate.getForObject("http://md5.jsontest.com/?text=a", String.class);
    }
}

MyIT.java

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
//@RestClientTest(MyService.class)
public class MyIT {

    @Autowired
    private MockMvc mockMvc;

//    @Autowired
//    private MockRestServiceServer mockRestServiceServer;

    @Test
    public void shouldGo() throws Exception {

//    mockRestServiceServer.expect(requestTo("http://md5.jsontest.com/?text=a"))
//              .andRespond(withSuccess());

        mockMvc.perform(get("/go")).andExpect(status().isOk());
    }
}
ivo
  • 13
  • 5

1 Answers1

0
  1. First, you should @Autowired your RestTemplate bean to your test class.
  2. Then create the MockRestServiceServer with the restTemplate, instead of autowiring it.

Perhaps try this one:

@Autowired
private RestTemplate restTemplate;

private MockRestServiceServer mockRestServiceServer;

@Before
public void setup() {
    mockRestServiceServer= MockRestServiceServer.createServer(restTemplate);
}
SzabK
  • 75
  • 1
  • 7