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

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

所以我想编写一组针对这两种服务运行的测试。(不想写重复的代码)

构建我的测试以完成此任务的最佳方法是什么?

(我标记了 junit4,因为这是我目前受限的版本。)


宝慕林4294392
浏览 141回答 3
3回答

婷婷同学_

这里的其他答案都很棒,但并不完全符合我的喜好。我最终结合了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 };}@ClassRulepublic static final SpringClassRule springClassRule = new SpringClassRule();@Rulepublic final SpringMethodRule springMethodRule = new SpringMethodRule();@Beforepublic void setUp() {     // logic to choose the injected service based on the true/false param}

慕容3067478

几个选项:您可以将所有类存储在一个常量中,例如List<Class<? extends YourInterface>> classes = Arrays.asList(Implementation.class)遍历这些类并为每个类调用该方法您可以使用反射来查找实现特定接口的所有类并为每个类循环。

慕无忌1623718

您可以创建一个 bean 来保存 JavaConfig 中的实现列表:public class TestConfig {&nbsp; &nbsp; @Bean&nbsp; &nbsp; MyService myService1(){&nbsp; &nbsp; &nbsp; &nbsp; return new MyService1();&nbsp; &nbsp; }&nbsp; &nbsp; @Bean&nbsp; &nbsp; MyService myService2(){&nbsp; &nbsp; &nbsp; &nbsp; return new MyService2();&nbsp; &nbsp; }&nbsp; &nbsp; @Bean&nbsp; &nbsp; public List<MyService> myServices(MyService myService1, MyService myService2){&nbsp; &nbsp; &nbsp; &nbsp; List<MyService> allServices = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; allServices.add(myService1);&nbsp; &nbsp; &nbsp; &nbsp; allServices.add(myService2);&nbsp; &nbsp; &nbsp; &nbsp; return allServices;&nbsp; &nbsp; }}并最终在您的测试中迭代此列表:@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes=TestConfig.class)public class ServicesTest {&nbsp; &nbsp; @Autowired&nbsp; &nbsp; private List<MyService> allServices;&nbsp; &nbsp; @Test&nbsp; &nbsp; public void testAllServices(){&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; for (MyService service : allServices) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Test service here&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java