我尝试在CoinControllerTest
中运行测试时遇到错误,据我所知coinMarketClient
是bean。该应用程序运行,一切似乎都可以正常工作,只是测试失败。
任何建议表示赞赏
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.reactboot.coindash.reactivecoindash.controllers.CoinController': Unsatisfied dependency expressed through field 'coinMarketClient'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.reactboot.coindash.reactivecoindash.webclients.CoinMarketClient' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
package com.reactboot.coindash.reactivecoindash.controllers;
import com.reactboot.coindash.reactivecoindash.models.Coin;
import com.reactboot.coindash.reactivecoindash.webclients.CoinMarketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
@RestController
@RequestMapping(value = "/coins")
public class CoinController {
@Autowired
private CoinMarketClient coinMarketClient;
private static final Logger LOGGER = LoggerFactory.getLogger(Coin.class);
@RequestMapping(value = "/meta")
public Mono<Coin> getMetaInfo(@RequestParam(value = "id") String id) {
return coinMarketClient.getCoinMetaInfo(id);
}
@RequestMapping(value = "/list")
public Mono<Coin> getAllCoins(@RequestParam(value = "start") String start, @RequestParam(value = "limit") String limit, @RequestParam(value = "convert") String convert) {
return coinMarketClient.getAllCoins(start, limit, convert);
}
@RequestMapping(value = "/price")
public Mono<Coin> getPriceInfo(@RequestParam(value = "id") String id, @RequestParam(value = "convert") String convert) {
return coinMarketClient.getCoinPriceInfo(id, convert);
}
@RequestMapping(value = "/ids")
public Mono<Coin> getAllCoinIds() {
return coinMarketClient.getAllCoinIds();
}
@ExceptionHandler(WebClientResponseException.class)
public ResponseEntity<String> handleWebClientResponseException(WebClientResponseException ex) {
LOGGER.error("Error from WebClient - Status {}, Body {}", ex.getRawStatusCode(),
ex.getResponseBodyAsString(), ex);
return ResponseEntity.status(ex.getRawStatusCode()).body(ex.getResponseBodyAsString());
}
}
package com.reactboot.coindash.reactivecoindash.webclients;
import com.reactboot.coindash.reactivecoindash.models.Coin;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
@Service
public class CoinMarketClient {
private WebClient webClient;
public CoinMarketClient() {
this.webClient = WebClient.builder()
.baseUrl("https://pro-api.coinmarketcap")
.build();
}
public Mono<Coin> getCoinMetaInfo(String id) {
return webClient.get()
.uri(uriBuilder -> uriBuilder.path("/v1/cryptocurrency/info").queryParam("id", id).build())
.retrieve()
.bodyToMono(Coin.class);
}
public Mono<Coin> getAllCoins(String start, String limit, String convert) {
return webClient.get()
.uri(uriBuilder -> uriBuilder.path("/v1/cryptocurrency/listings/latest")
.queryParam("start", start)
.queryParam("limit", limit)
.queryParam("convert", convert)
.build())
.retrieve()
.bodyToMono(Coin.class);
}
public Mono<Coin> getCoinPriceInfo(String id, String convert) {
return webClient.get()
.uri(uriBuilder -> uriBuilder.path("/v1/cryptocurrency/quotes/latest")
.queryParam("id", id)
.queryParam("convert", convert).build())
.retrieve()
.bodyToMono(Coin.class);
}
public Mono<Coin> getAllCoinIds() {
return webClient.get()
.uri("/v1/cryptocurrency/map")
.retrieve()
.bodyToMono(Coin.class);
}
}
package com.reactboot.coindash.reactivecoindash;
import com.reactboot.coindash.reactivecoindash.controllers.CoinController;
import com.reactboot.coindash.reactivecoindash.models.Coin;
import com.reactboot.coindash.reactivecoindash.webclients.CoinMarketClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
@RunWith(SpringRunner.class)
@WebFluxTest(CoinController.class)
public class CoinControllerTest {
@Autowired
private WebTestClient webTestClient;
@Test
public void shouldGetCoinMetaInfoById() throws Exception {
String expectedResponse = "{\"data\":{\"1\":{\"urls\":{\"website\":[\"https://bitcoin.org/\"],\"twitter\":[],\"reddit\":[\"https://reddit.com/r/bitcoin\"],\"message_board\":[\"https://bitcointalk.org\"],\"announcement\":[],\"chat\":[],\"explorer\":[\"https://blockchain.info/\",\"https://live.blockcypher.com/btc/\",\"https://blockchair.com/bitcoin/blocks\"],\"source_code\":[\"https://github.com/bitcoin/\"]},\"logo\":\"https://s2.coinmarketcap.com/static/img/coins/64x64/1.png\",\"id\":1,\"name\":\"Bitcoin\",\"symbol\":\"BTC\",\"slug\":\"bitcoin\",\"date_added\":\"2013-04-28T00:00:00.000Z\",\"tags\":[\"mineable\"],\"category\":\"coin\"}},\"status\":{\"timestamp\":\"2018-11-02T18:48:46.405Z\",\"error_code\":0,\"error_message\":null,\"elapsed\":4,\"credit_count\":1}}";
this.webTestClient.get().uri("/meta/?id=1").accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo(expectedResponse);
}
}
java.lang.AssertionError: Status <Click to see difference>
at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:200)
at org.springframework.test.web.reactive.server.StatusAssertions.assertStatusAndReturn(StatusAssertions.java:227)
at org.springframework.test.web.reactive.server.StatusAssertions.isOk(StatusAssertions.java:67)
at com.reactboot.coindash.reactivecoindash.CoinControllerTest.shouldGetCoinMetaInfoById(CoinControllerTest.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.AssertionError: Status expected:<200 OK> but was:<404 NOT_FOUND>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.reactive.server.StatusAssertions.lambda$assertStatusAndReturn$4(StatusAssertions.java:227)
at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:197)
... 33 more
答案 0 :(得分:1)
详细的here,@WebFluxText
将自动连接@Controller
bean,但是在您的示例中,您不是自动装配WebTestClient
而是自然而然地触发此行为用CoinController
实例化的new
,这就是IMO问题的原因