mardi 25 septembre 2018

Override autowired instance with a mock

ServiceInstance.createInstance is supposed to be called when a PUT call is made to the URL below. To be able to test if the correct method is called when a PUT request is sent, I want to mock the object(ServiceInstance) that has the method called. However, the mock doesn't override the real instance. What am I missing in this setting?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MySpringBootApplication.class })
@SpyBean(ServiceInstance.class)

public class ServiceTest {

@Autowired
ServiceInstance serviceInstance;

@BeforeClass
public static void setUp() {
    SpringApplication.run(MySpringBootApplication.class, new String[] {});
}

@Test
public void sendPutRequest() throws JSONException, ClientProtocolException, IOException {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpPut putRequest = new HttpPut("http://localhost:8080/v2/instances/1");
    //.....

    httpClient.execute(putRequest);
    Mockito.verify(serviceInstance, Mockito.times(1)).createInstance(Mockito.any());

}

}

Aucun commentaire:

Enregistrer un commentaire