首页 > 解决方案 > 使用构造函数注入模式对 springboot 进行集成测试

问题描述

我正在尝试使用构造函数注入依赖模式

我想知道在集成测试类上注入 JPA 存储库的正确方法是什么:

我有我的源代码:

回购类

@Repository
public interface MyClassRepo extends JpaRepository<MyClass, Long> {
... methods ...
}

构造函数注入后的服务

public class MyClassService {

  private final MyClassRepo myClassRepo;

  public DeviceServiceImpl(final MyClassRepo myClassRepo) {
    this.myClassRepo = myClassRepo;
  }

  public boolean myMethodToTest() {
    ... whatever...
  }
}

测试它:(这是我的问题)

SpringRunner 类选项 1:构造函数注入

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyTestConfigClass.class) // With necessary imports
@SpringBootTest
public class MyClassTester {
  private final MyClassService myClassService;
  private final MyClassRepository myClassRepository;

  public MyClassTester (final MyClassRepository deviceRepository) {
    this.myClassRepository = myClassRepository;
    this.myClassService= new myClassService(myClassRepository); 
  } 

}

不起作用,因为控制台输出显示:

测试类应该只有一个公共的零参数构造函数

SpringRunner 类选项 2:自动装配注入

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyTestConfigClass.class) // With necessary imports
@SpringBootTest
public class MyClassTester {
    @Autowired
    private MyClassRepository myClassRepository;

    private MyClassService myClassService = new myClassService(myClassRepository);

}

我觉得它打破了预期的模式。

SpringRunner 类选项 3:空构造函数

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyTestConfigClass.class) // With necessary imports
@SpringBootTest
public class MyClassTester {

  private final MyClassService myClassService;
  private final MyClassRepository myClassRepository;

  public MyClassTester () {
    this.myClassRepository = new MyClassRepository(); // Obviously NOT working, since its an interface
    this.myClassService= new myClassService(myClassRepository); 
  } 
}

正如评论:显然不工作,因为 MyClassRepository 它是一个接口

有没有更好的方法来解决这个问题?

标签: javaspringspring-bootspring-testspring-boot-test

解决方案


使用 Junit 5。它允许具有多个参数的构造函数。

选项 1 需要将 @Autowired 添加到测试构造函数中


推荐阅读