3 回答
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
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
}
![?](http://img1.sycdn.imooc.com/533e564d0001308602000200-100-100.jpg)
TA贡献1773条经验 获得超3个赞
几个选项:
您可以将所有类存储在一个常量中,例如
List<Class<? extends YourInterface>> classes = Arrays.asList(Implementation.class)
遍历这些类并为每个类调用该方法您可以使用反射来查找实现特定接口的所有类并为每个类循环。
![?](http://img1.sycdn.imooc.com/5458620000018a2602200220-100-100.jpg)
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
}
}
}
添加回答
举报