Spring Boot @Async annotation and MockRestServiceServer












1















I'm using Spring Boot 2.0.6 and Java 10. I did the following service that only hits an external rest api using RestTemplate.



@Service
@Slf4j
public class DbApiClientImpl implements DbApiClient {

private final String URL_DELIMITER = "/";
private RestTemplate restTemplate;
private String url;

public DbApiClientImpl(
RestTemplateBuilder restTemplate,
@Value("${dbapi.namespace}") String namespace,
@Value("${dbapi.url}") String uri,
@Value("${dbapi.username}") String username,
@Value("${dbapi.password}") String password) {

this.restTemplate = restTemplate.basicAuthorization(username,
password).build();
this.url = namespace.concat(uri);
}

@Override
@Async("asyncExecutor")
public Merchant fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return response.getBody();
}
}


And the following test using MockeRestServiceServer:



@RunWith(SpringRunner.class)
@RestClientTest(value = {DbApiClient.class})
public class DbApiClientTest {

private static final String TEST_NAME = "test";
private static final String TEST_NAME_BAD_REQUEST = "test-
1";
private static final String TEST_NAME_SERVER_ERROR =
"test-2";

@Autowired DbApiClient dbApiClient;

@Value("${dbapi.namespace}")
private String namespace;

@Value("${dbapi.url}")
private String dbApiUrl;

@Autowired private MockRestServiceServer mockServer;

@Autowired private ObjectMapper objectMapper;

@Test
public void test() throws
JsonProcessingException, IOException {
Merchant mockMerchantSpec = populateFakeMerchant();
String jsonResponse =
objectMapper.writeValueAsString(mockMerchantSpec);
mockServer
.expect(manyTimes(),
requestTo(dbApiUrl.concat("/").concat(TEST_NAME)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(jsonResponse,
MediaType.APPLICATION_JSON));

assertNotNull(dbApiClient.fetchMerchant(TEST_NAME));
}


The thing is that I'm getting the following exception when I run the test "No further request expected HTTP GET http://localthost... excecuted"



So seems that the @Async is borking MockerServerService response...
Also, If I commented the @Async annotation everything works just fine and I get all test green.



Thanks in advance for your comments.



Update:



As per @M.Deinum's comment. I removed the CompletableFuture from the service but I'm still getting the same exception.










share|improve this question

























  • Remove the CompletableFuture from your method, that doesn't add anything. Or make your method return Future<Merchant> instead of what you have now. That way your calling code will wait for the response. Currently it won't wait and the test will finish (as the thread runs in the background).

    – M. Deinum
    Nov 23 '18 at 8:04













  • Thanks @M.Deinum same exception.. :(

    – Tori
    Nov 23 '18 at 14:48











  • I actually doubt this will work. You are returning a result from an async method. It should return either void or a Future so your calling code knows what to expect. So my guess is your code is wrong and not your test.

    – M. Deinum
    Nov 24 '18 at 18:11
















1















I'm using Spring Boot 2.0.6 and Java 10. I did the following service that only hits an external rest api using RestTemplate.



@Service
@Slf4j
public class DbApiClientImpl implements DbApiClient {

private final String URL_DELIMITER = "/";
private RestTemplate restTemplate;
private String url;

public DbApiClientImpl(
RestTemplateBuilder restTemplate,
@Value("${dbapi.namespace}") String namespace,
@Value("${dbapi.url}") String uri,
@Value("${dbapi.username}") String username,
@Value("${dbapi.password}") String password) {

this.restTemplate = restTemplate.basicAuthorization(username,
password).build();
this.url = namespace.concat(uri);
}

@Override
@Async("asyncExecutor")
public Merchant fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return response.getBody();
}
}


And the following test using MockeRestServiceServer:



@RunWith(SpringRunner.class)
@RestClientTest(value = {DbApiClient.class})
public class DbApiClientTest {

private static final String TEST_NAME = "test";
private static final String TEST_NAME_BAD_REQUEST = "test-
1";
private static final String TEST_NAME_SERVER_ERROR =
"test-2";

@Autowired DbApiClient dbApiClient;

@Value("${dbapi.namespace}")
private String namespace;

@Value("${dbapi.url}")
private String dbApiUrl;

@Autowired private MockRestServiceServer mockServer;

@Autowired private ObjectMapper objectMapper;

@Test
public void test() throws
JsonProcessingException, IOException {
Merchant mockMerchantSpec = populateFakeMerchant();
String jsonResponse =
objectMapper.writeValueAsString(mockMerchantSpec);
mockServer
.expect(manyTimes(),
requestTo(dbApiUrl.concat("/").concat(TEST_NAME)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(jsonResponse,
MediaType.APPLICATION_JSON));

assertNotNull(dbApiClient.fetchMerchant(TEST_NAME));
}


The thing is that I'm getting the following exception when I run the test "No further request expected HTTP GET http://localthost... excecuted"



So seems that the @Async is borking MockerServerService response...
Also, If I commented the @Async annotation everything works just fine and I get all test green.



Thanks in advance for your comments.



Update:



As per @M.Deinum's comment. I removed the CompletableFuture from the service but I'm still getting the same exception.










share|improve this question

























  • Remove the CompletableFuture from your method, that doesn't add anything. Or make your method return Future<Merchant> instead of what you have now. That way your calling code will wait for the response. Currently it won't wait and the test will finish (as the thread runs in the background).

    – M. Deinum
    Nov 23 '18 at 8:04













  • Thanks @M.Deinum same exception.. :(

    – Tori
    Nov 23 '18 at 14:48











  • I actually doubt this will work. You are returning a result from an async method. It should return either void or a Future so your calling code knows what to expect. So my guess is your code is wrong and not your test.

    – M. Deinum
    Nov 24 '18 at 18:11














1












1








1


1






I'm using Spring Boot 2.0.6 and Java 10. I did the following service that only hits an external rest api using RestTemplate.



@Service
@Slf4j
public class DbApiClientImpl implements DbApiClient {

private final String URL_DELIMITER = "/";
private RestTemplate restTemplate;
private String url;

public DbApiClientImpl(
RestTemplateBuilder restTemplate,
@Value("${dbapi.namespace}") String namespace,
@Value("${dbapi.url}") String uri,
@Value("${dbapi.username}") String username,
@Value("${dbapi.password}") String password) {

this.restTemplate = restTemplate.basicAuthorization(username,
password).build();
this.url = namespace.concat(uri);
}

@Override
@Async("asyncExecutor")
public Merchant fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return response.getBody();
}
}


And the following test using MockeRestServiceServer:



@RunWith(SpringRunner.class)
@RestClientTest(value = {DbApiClient.class})
public class DbApiClientTest {

private static final String TEST_NAME = "test";
private static final String TEST_NAME_BAD_REQUEST = "test-
1";
private static final String TEST_NAME_SERVER_ERROR =
"test-2";

@Autowired DbApiClient dbApiClient;

@Value("${dbapi.namespace}")
private String namespace;

@Value("${dbapi.url}")
private String dbApiUrl;

@Autowired private MockRestServiceServer mockServer;

@Autowired private ObjectMapper objectMapper;

@Test
public void test() throws
JsonProcessingException, IOException {
Merchant mockMerchantSpec = populateFakeMerchant();
String jsonResponse =
objectMapper.writeValueAsString(mockMerchantSpec);
mockServer
.expect(manyTimes(),
requestTo(dbApiUrl.concat("/").concat(TEST_NAME)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(jsonResponse,
MediaType.APPLICATION_JSON));

assertNotNull(dbApiClient.fetchMerchant(TEST_NAME));
}


The thing is that I'm getting the following exception when I run the test "No further request expected HTTP GET http://localthost... excecuted"



So seems that the @Async is borking MockerServerService response...
Also, If I commented the @Async annotation everything works just fine and I get all test green.



Thanks in advance for your comments.



Update:



As per @M.Deinum's comment. I removed the CompletableFuture from the service but I'm still getting the same exception.










share|improve this question
















I'm using Spring Boot 2.0.6 and Java 10. I did the following service that only hits an external rest api using RestTemplate.



@Service
@Slf4j
public class DbApiClientImpl implements DbApiClient {

private final String URL_DELIMITER = "/";
private RestTemplate restTemplate;
private String url;

public DbApiClientImpl(
RestTemplateBuilder restTemplate,
@Value("${dbapi.namespace}") String namespace,
@Value("${dbapi.url}") String uri,
@Value("${dbapi.username}") String username,
@Value("${dbapi.password}") String password) {

this.restTemplate = restTemplate.basicAuthorization(username,
password).build();
this.url = namespace.concat(uri);
}

@Override
@Async("asyncExecutor")
public Merchant fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return response.getBody();
}
}


And the following test using MockeRestServiceServer:



@RunWith(SpringRunner.class)
@RestClientTest(value = {DbApiClient.class})
public class DbApiClientTest {

private static final String TEST_NAME = "test";
private static final String TEST_NAME_BAD_REQUEST = "test-
1";
private static final String TEST_NAME_SERVER_ERROR =
"test-2";

@Autowired DbApiClient dbApiClient;

@Value("${dbapi.namespace}")
private String namespace;

@Value("${dbapi.url}")
private String dbApiUrl;

@Autowired private MockRestServiceServer mockServer;

@Autowired private ObjectMapper objectMapper;

@Test
public void test() throws
JsonProcessingException, IOException {
Merchant mockMerchantSpec = populateFakeMerchant();
String jsonResponse =
objectMapper.writeValueAsString(mockMerchantSpec);
mockServer
.expect(manyTimes(),
requestTo(dbApiUrl.concat("/").concat(TEST_NAME)))
.andExpect(method(HttpMethod.GET))
.andRespond(withSuccess(jsonResponse,
MediaType.APPLICATION_JSON));

assertNotNull(dbApiClient.fetchMerchant(TEST_NAME));
}


The thing is that I'm getting the following exception when I run the test "No further request expected HTTP GET http://localthost... excecuted"



So seems that the @Async is borking MockerServerService response...
Also, If I commented the @Async annotation everything works just fine and I get all test green.



Thanks in advance for your comments.



Update:



As per @M.Deinum's comment. I removed the CompletableFuture from the service but I'm still getting the same exception.







java spring asynchronous resttemplate






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 14:47







Tori

















asked Nov 22 '18 at 19:41









ToriTori

334




334













  • Remove the CompletableFuture from your method, that doesn't add anything. Or make your method return Future<Merchant> instead of what you have now. That way your calling code will wait for the response. Currently it won't wait and the test will finish (as the thread runs in the background).

    – M. Deinum
    Nov 23 '18 at 8:04













  • Thanks @M.Deinum same exception.. :(

    – Tori
    Nov 23 '18 at 14:48











  • I actually doubt this will work. You are returning a result from an async method. It should return either void or a Future so your calling code knows what to expect. So my guess is your code is wrong and not your test.

    – M. Deinum
    Nov 24 '18 at 18:11



















  • Remove the CompletableFuture from your method, that doesn't add anything. Or make your method return Future<Merchant> instead of what you have now. That way your calling code will wait for the response. Currently it won't wait and the test will finish (as the thread runs in the background).

    – M. Deinum
    Nov 23 '18 at 8:04













  • Thanks @M.Deinum same exception.. :(

    – Tori
    Nov 23 '18 at 14:48











  • I actually doubt this will work. You are returning a result from an async method. It should return either void or a Future so your calling code knows what to expect. So my guess is your code is wrong and not your test.

    – M. Deinum
    Nov 24 '18 at 18:11

















Remove the CompletableFuture from your method, that doesn't add anything. Or make your method return Future<Merchant> instead of what you have now. That way your calling code will wait for the response. Currently it won't wait and the test will finish (as the thread runs in the background).

– M. Deinum
Nov 23 '18 at 8:04







Remove the CompletableFuture from your method, that doesn't add anything. Or make your method return Future<Merchant> instead of what you have now. That way your calling code will wait for the response. Currently it won't wait and the test will finish (as the thread runs in the background).

– M. Deinum
Nov 23 '18 at 8:04















Thanks @M.Deinum same exception.. :(

– Tori
Nov 23 '18 at 14:48





Thanks @M.Deinum same exception.. :(

– Tori
Nov 23 '18 at 14:48













I actually doubt this will work. You are returning a result from an async method. It should return either void or a Future so your calling code knows what to expect. So my guess is your code is wrong and not your test.

– M. Deinum
Nov 24 '18 at 18:11





I actually doubt this will work. You are returning a result from an async method. It should return either void or a Future so your calling code knows what to expect. So my guess is your code is wrong and not your test.

– M. Deinum
Nov 24 '18 at 18:11












1 Answer
1






active

oldest

votes


















0














The problem is your code and not your test.



If you read the documentation (the JavaDoc) of AsyncExecutionInterceptor you will see the mention that only void or Future is supported as a return type. You are returning a plain object and that is internally treated as void.



A call to that method will always respond with null. As your test is running very quickly everything has been teared down already (or is in the process of being teared down) no more calls are expected to be made.



To fix, fix your method signature and return a Future<Merchant> so that you can block and wait for the result.



@Override
@Async("asyncExecutor")
public Future<Merchant> fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return CompletableFuture.completedFuture(response.getBody());
}


Now your calling code knows about the returned Future as well as the Spring Async code. Now in your test you can now call get on the returned value (maybe with a timeout to receive an error if something fails). TO inspect the result.






share|improve this answer
























  • This is correct buddy! Thanks for your comments! :)

    – Tori
    Nov 28 '18 at 21:13











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437218%2fspring-boot-async-annotation-and-mockrestserviceserver%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














The problem is your code and not your test.



If you read the documentation (the JavaDoc) of AsyncExecutionInterceptor you will see the mention that only void or Future is supported as a return type. You are returning a plain object and that is internally treated as void.



A call to that method will always respond with null. As your test is running very quickly everything has been teared down already (or is in the process of being teared down) no more calls are expected to be made.



To fix, fix your method signature and return a Future<Merchant> so that you can block and wait for the result.



@Override
@Async("asyncExecutor")
public Future<Merchant> fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return CompletableFuture.completedFuture(response.getBody());
}


Now your calling code knows about the returned Future as well as the Spring Async code. Now in your test you can now call get on the returned value (maybe with a timeout to receive an error if something fails). TO inspect the result.






share|improve this answer
























  • This is correct buddy! Thanks for your comments! :)

    – Tori
    Nov 28 '18 at 21:13
















0














The problem is your code and not your test.



If you read the documentation (the JavaDoc) of AsyncExecutionInterceptor you will see the mention that only void or Future is supported as a return type. You are returning a plain object and that is internally treated as void.



A call to that method will always respond with null. As your test is running very quickly everything has been teared down already (or is in the process of being teared down) no more calls are expected to be made.



To fix, fix your method signature and return a Future<Merchant> so that you can block and wait for the result.



@Override
@Async("asyncExecutor")
public Future<Merchant> fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return CompletableFuture.completedFuture(response.getBody());
}


Now your calling code knows about the returned Future as well as the Spring Async code. Now in your test you can now call get on the returned value (maybe with a timeout to receive an error if something fails). TO inspect the result.






share|improve this answer
























  • This is correct buddy! Thanks for your comments! :)

    – Tori
    Nov 28 '18 at 21:13














0












0








0







The problem is your code and not your test.



If you read the documentation (the JavaDoc) of AsyncExecutionInterceptor you will see the mention that only void or Future is supported as a return type. You are returning a plain object and that is internally treated as void.



A call to that method will always respond with null. As your test is running very quickly everything has been teared down already (or is in the process of being teared down) no more calls are expected to be made.



To fix, fix your method signature and return a Future<Merchant> so that you can block and wait for the result.



@Override
@Async("asyncExecutor")
public Future<Merchant> fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return CompletableFuture.completedFuture(response.getBody());
}


Now your calling code knows about the returned Future as well as the Spring Async code. Now in your test you can now call get on the returned value (maybe with a timeout to receive an error if something fails). TO inspect the result.






share|improve this answer













The problem is your code and not your test.



If you read the documentation (the JavaDoc) of AsyncExecutionInterceptor you will see the mention that only void or Future is supported as a return type. You are returning a plain object and that is internally treated as void.



A call to that method will always respond with null. As your test is running very quickly everything has been teared down already (or is in the process of being teared down) no more calls are expected to be made.



To fix, fix your method signature and return a Future<Merchant> so that you can block and wait for the result.



@Override
@Async("asyncExecutor")
public Future<Merchant> fetchMerchant(String id) {
ResponseEntity<Merchant> response =
restTemplate.getForEntity(url.concat(URL_DELIMITER).concat(id),
Merchant.class);
return CompletableFuture.completedFuture(response.getBody());
}


Now your calling code knows about the returned Future as well as the Spring Async code. Now in your test you can now call get on the returned value (maybe with a timeout to receive an error if something fails). TO inspect the result.







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 24 '18 at 18:25









M. DeinumM. Deinum

69.2k13139149




69.2k13139149













  • This is correct buddy! Thanks for your comments! :)

    – Tori
    Nov 28 '18 at 21:13



















  • This is correct buddy! Thanks for your comments! :)

    – Tori
    Nov 28 '18 at 21:13

















This is correct buddy! Thanks for your comments! :)

– Tori
Nov 28 '18 at 21:13





This is correct buddy! Thanks for your comments! :)

– Tori
Nov 28 '18 at 21:13


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437218%2fspring-boot-async-annotation-and-mockrestserviceserver%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Ottavio Pratesi

Tricia Helfer

15 giugno