• 请不要在回答技术问题时复制粘贴 AI 生成的内容
asanelder
V2EX  ›  程序员

springboot 项目, 使用了 feign, 写测试时, 如何 mock feign 注解的接口?

  •  
  •   asanelder · Mar 17, 2021 · 2000 views
    This topic created in 1883 days ago, the information mentioned may be changed or developed.

    俺的一个项目使用了 feign, 相关代码如下

    @EnableFeignClients
    @SpringBootApplication
    public class FoobarApp {
        public static void main(String[] args) {
            SpringApplication.run(FoobarApp.class, args);
        }
    }
    
    @FeignClient(value = "service-name") 
    public interface BookService {
         Book getBook(int book_id);
    }
    
    
    @RestController
    public class BookController {
    
        @Autowired BookService bookService;
    
        // 其它使用 bookService 的地方
    }
    

    然后俺写的测试是

    @SpringBootTest(classes = FoobarApp.class) 
    public class DemoTest {
    
        @Autowired BookController controller;
    
    }
    

    现在的问题是, 跑测试时, controller 中注入的是自动生成的 BookService 代理实现, 现在俺想测试的时候, 注入一个假的 BookService 实现, 但不知怎么做.

    有没有铁子指导一下?

    PS: 好像这个 EnableFeignClients 注解自动为接口生成了代理并注入到了容器中, 但俺想跑测试的时候, 注入俺自已写的假的实现

    2 replies    2021-03-17 22:47:54 +08:00
    chendy
        1
    chendy  
       Mar 17, 2021
    如果可以的话,扔了 SpringBootTest,上 mockito 自己 mock 自己组装 bean
    oaix
        2
    oaix  
       Mar 17, 2021
    是在找 @MockBean 吗?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5832 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 62ms · UTC 01:58 · PVG 09:58 · LAX 18:58 · JFK 21:58
    ♥ Do have faith in what you're doing.