Java 在一个测试类中实现服务接口的两个bean的单元测试Spring引导

Java 在一个测试类中实现服务接口的两个bean的单元测试Spring引导,java,spring,unit-testing,spring-boot,dependency-injection,Java,Spring,Unit Testing,Spring Boot,Dependency Injection,在SpringBootWeb应用程序的服务层上,我有一个带有几个方法和两个实现bean的服务接口 interface VehicleService { } @Service class CarServiceImpl implements VehicleService {} @Service class BycicleServiceImpl implements VehicleService {} 我已经为其中一个服务生成了单元测试 @RunWith(SpringRunner.class) pu

在SpringBootWeb应用程序的服务层上,我有一个带有几个方法和两个实现bean的服务接口

interface VehicleService { }
@Service
class CarServiceImpl implements VehicleService {}
@Service
class BycicleServiceImpl implements VehicleService {}
我已经为其中一个服务生成了单元测试

@RunWith(SpringRunner.class)
public class CarServiceTest {

  @TestConfiguration
  static class VehicleServiceTestContextConfiguration {
      @Bean
      public VehicleService vehicleService() {
         return new CarServiceImpl();
      }
  }

  @Autowired
  private VehicleService vehicleService;

  @Test
  public void getCar() throws Exception {
    //tests here with CarServiceImpl object
  }

}

当我想运行测试BicycleServiceImpl bean时,我必须复制并粘贴同一个类,并更改@bean以返回BicycleServiceImpl,这似乎不是最好的解决方案。有没有办法让我运行同一个测试类两次,然后逐个注入每个bean。如果您有任何建议,我们将不胜感激。

您为什么要使用Spring,而不仅仅是对服务类运行简单的单元测试?此外,对于任何现实世界的示例,您的两个不同的服务类应该有某种不同的行为,或者有什么意义?并且您的单元测试应该相应地有所不同。我编辑了我的帖子,我实际上是在测试提供REST服务的Spring Boot应用程序的服务层。您是对的,这两个服务的行为略有不同,但没有什么不能用simple if-else控制的,因此,如果我能够找出如何使用两个实现bean运行每个测试两次,那么应该尽可能使用setAvoid条件,特别是当您使用它们在类型之间切换时。为测试创建抽象基类,并使用抽象方法将特定于实现的行为委托给特定于实现的测试类。