V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
asanelder
V2EX  ›  程序员

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

  •  
  •   asanelder · 2021-03-17 18:17:38 +08:00 · 1439 次点击
    这是一个创建于 1135 天前的主题,其中的信息可能已经有所发展或是发生改变。

    俺的一个项目使用了 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 条回复    2021-03-17 22:47:54 +08:00
    chendy
        1
    chendy  
       2021-03-17 19:05:39 +08:00
    如果可以的话,扔了 SpringBootTest,上 mockito 自己 mock 自己组装 bean
    oaix
        2
    oaix  
       2021-03-17 22:47:54 +08:00
    是在找 @MockBean 吗?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1058 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 22:19 · PVG 06:19 · LAX 15:19 · JFK 18:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.