java - 使用构造函数注入模式对 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 它是一个接口
有没有更好的方法来解决这个问题?
解决方案
使用 Junit 5。它允许具有多个参数的构造函数。
选项 1 需要将 @Autowired 添加到测试构造函数中
推荐阅读
- html - 组合 2 个 html 文件时,html 中的多个脚本标签不起作用
- c# - 我需要检查整数中的每个数字在c#中是偶数还是奇数,返回偶数或奇数
- image - 由于ocr的行删除,填补了汉字的空白
- asp.net-core - 将 WebApi 托管为 IIS 应用程序,以便它运行启动类
- java - 如何将重写规则添加到 Spring Boot 2.3.1
- node.js - 如何通过将所有选项放在 mongodb 的 node.js 驱动程序中的连接字符串中来连接 X509?
- javascript - 如何将键/值对添加到另一个对象中的 JavaScript 对象
- broadcastreceiver - 从 javascript 到原生的 Ionic Android 广播事件
- domain-driven-design - 在 Spine 事件引擎的聚合中应用拒绝
- angular - 如何在模板中显示来自管道的数据?