有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java针对两种不同的注入依赖项运行单元测试

我的应用程序中有两个服务bean,它们都实现了一个接口。对于该接口,所有方法都必须执行相同的操作(尽管内部结构不同)

因此,我想编写一组针对这两种服务的测试。(不想写重复的代码)

为了实现这一点,构建测试的最佳方式是什么

(我已经标记了junit4,因为这是我目前限制使用的版本。)


共 (1) 个答案

  1. # 1 楼答案

    您可以创建一个bean,其中包含JavaConfig中的实现列表:

    public class TestConfig {
    
        @Bean
        MyService myService1(){
            return new MyService1();
        }
    
        @Bean
        MyService myService2(){
            return new MyService2();
        }
    
        @Bean
        public List<MyService> myServices(MyService myService1, MyService myService2){
            List<MyService> allServices = new ArrayList<>();
            allServices.add(myService1);
            allServices.add(myService2);
            return allServices;
        }
    }
    

    并最终在测试中重复这个列表:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes=TestConfig.class)
    public class ServicesTest {
        @Autowired
        private List<MyService> allServices;
        @Test
        public void testAllServices(){    
            for (MyService service : allServices) {
                // Test service here
            }    
        }
    }