【问题标题】:Injecting one MockBean into another将一个 MockBean 注入另一个
【发布时间】:2020-02-19 18:15:35
【问题描述】:

我有一个典型的 SpringApplication,我正在尝试通过 MockMvc 进行测试。该应用程序包含一些数据库调用和一些第三方 api 调用,我想模拟所有这些,同时测试端到端流程,第三方除外

这是我创建的 -

控制器类

public class PortfolioController {

private final PortfolioService portfolioService;
}

服务类

public class PortfolioService {

private final PortfolioTransactionRepository portfolioTransactionRepository;
private final AlphavantageService alphavantageService;
}

AlphaVantageService

public class AlphavantageService {

private ApiConfig apiConfig;

private final RestTemplate restTemplate;

public Map<String, List<Candle>> getStockQuotes(List<String> symbols) {
    return symbols.stream().collect(Collectors.toMap(symbol -> symbol, symbol -> getQuotes(symbol)));
}
}

现在是测试-

@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = PortfolioController.class)
class PortfolioControllerTest {

private List<PortfolioTransaction> transactions;

@MockBean
private AlphavantageService alphavantageService;

@MockBean
private PortfolioService portfolioService;

@Autowired
private PortfolioController portfolioController;

@Autowired
private MockMvc mockMvc;
}

问题是,当我尝试在服务器上执行任何 mvc 调用时,AlphaVantageService 没有注入到 PortfolioService 中,所以直到级别 1,我注入了 bean,但在更进一步的级别上,我没有得到相同的结果。

这是设计使然还是我遗漏了什么?我们应该如何测试这样的测试用例?

【问题讨论】:

    标签: spring mocking junit5


    【解决方案1】:

    实际上在尝试了一些选项之后,我找到了解决方案。

    就像@MockBean一样,spring也有一个叫做@SpyBean的概念。这解决了我的问题。所以现在我的测试如下所示

    @ExtendWith(SpringExtension.class)
    @WebMvcTest(controllers = PortfolioController.class)
    @MockBeans(value = {@MockBean(AlphavantageService.class), 
    @MockBean(PortfolioTransactionRepository.class)})
    @SpyBeans(value = {@SpyBean(PortfolioService.class)})
    class PortfolioControllerTest {
    
    private List<PortfolioTransaction> transactions;
    
    @Autowired
    private AlphavantageService alphavantageService;
    
    @Autowired
    @SpyBean
    private PortfolioService portfolioService;
    
    @Autowired
    private PortfolioController portfolioController;
    
    @Autowired
    private MockMvc mockMvc;
    }
    

    这就像一个魅力,我可以在测试中使用完全成熟的依赖注入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-20
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多