为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

宝慕林4294392 2021-08-04 17:14:20
我的应用程序中有两个服务 bean,它们都实现了一个接口。对于该接口,所有方法都必须执行相同的操作(但内部结构不同)。所以我想编写一组针对这两种服务运行的测试。(不想写重复的代码)构建我的测试以完成此任务的最佳方法是什么?(我标记了 junit4,因为这是我目前受限的版本。)
查看完整描述

3 回答

?
婷婷同学_

TA贡献1844条经验 获得超8个赞

这里的其他答案都很棒,但并不完全符合我的喜好。我最终结合了

  • JUnit @RunWith(@Parameterized)(运行两个服务的测试)

  • Spring 的新规则(保持@RunWith(SpringRunner.class)容器、appcontext、webmvc 和注入功能)

以下是片段:

@RunWith(Parameterized.class)


...


@Parameters(name = "Cached = {0}")

public static Boolean[] data() {

    return new Boolean[] { Boolean.TRUE, Boolean.FALSE };

}


@ClassRule

public static final SpringClassRule springClassRule = new SpringClassRule();


@Rule

public final SpringMethodRule springMethodRule = new SpringMethodRule();


@Before

public void setUp() {

     // logic to choose the injected service based on the true/false param

}


查看完整回答
反对 回复 2021-08-04
?
慕容3067478

TA贡献1773条经验 获得超3个赞

几个选项:

  1. 您可以将所有类存储在一个常量中,例如List<Class<? extends YourInterface>> classes = Arrays.asList(Implementation.class)遍历这些类并为每个类调用该方法

  2. 您可以使用反射来查找实现特定接口的所有类并为每个类循环。


查看完整回答
反对 回复 2021-08-04
?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

您可以创建一个 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

        }    

    }

}


查看完整回答
反对 回复 2021-08-04
  • 3 回答
  • 0 关注
  • 140 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信