簡體   English   中英

測試 Spring 時創建 bean 時出錯

[英]Error creating bean when testing a Spring

我在嘗試在CoinControllerTest運行測試時遇到了這個錯誤, 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());
    }
}

CoinMarket客戶端

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

}

CoinController測試

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

詳見這里@WebFluxText將自動裝配你@Controller豆,但在你的榜樣,你是不是自動裝配WebTestClient這自然會引發這種行為,但與構建它CoinController被實例化,只有一個new ,這是的原因問題海事組織

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM