【问题标题】:Error creating bean when testing a Spring测试 Spring 时创建 bean 时出错
【发布时间】:2018-11-03 01:23:47
【问题描述】:

我在尝试在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());
    }
}

CoinMarketClient

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);
    }

}

CoinControllerTest

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

【问题讨论】:

  • 您正在使用 new 自己创建 CoinController。所以它不是 Spring 管理的 bean,所以没有任何东西是自动装配的。在您的测试中自动连接控制器。
  • 你应该打电话给/coins/meta 对吧?一定是404的原因。另外,当您编辑问题时,现在我的回答变得毫无意义,原始问题丢失了。
  • 不,它仍然会产生同样的问题。
  • 您删除了@MockBean,所以您想对整个产品进行整体测试?也许您缺少@WebFluxTest 未包含的一些配置,您应该使用@SpringBootTest 这已成为一个单独的问题哈哈。您应该创建一个新的并回滚对此的更改并接受我的回答以使用 @WebFluxTest 至少 IMO
  • 阅读this,说Using this annotation will disable full auto-configuration and instead apply only configuration relevant to WebFlux tests (i.e. @Controller, @ControllerAdvice, @JsonComponent, Converter/GenericConverter, and WebFluxConfigurer beans but not @Component, @Service or @Repository beans).

标签: java spring spring-webflux


【解决方案1】:

详细here@WebFluxText 将自动装配您的 @Controller bean,但在您的示例中,您不会自动装配 WebTestClient,这会自然触发此行为,而是使用实例化的 CoinController 构建它只有new,这是IMO问题的原因

【讨论】:

猜你喜欢
  • 2018-02-02
  • 2016-06-24
  • 2013-10-06
  • 2020-01-24
  • 1970-01-01
  • 2017-02-03
  • 2015-05-28
  • 2020-02-23
  • 2016-03-18
相关资源
最近更新 更多