gpt4 book ai didi

java - 使用构造函数注入(inject)模式对 spring boot 进行集成测试

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:22:02 24 4
gpt4 key购买 nike

我正在尝试使用 Constructor Injection dependency pattern .

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

我有我的源代码:

repo 类

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

构造函数注入(inject)后的服务

public class MyClassService {

private final MyClassRepo myClassRepo;

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

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

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

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

@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);
}

}

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

Test class should have exactly one public zero-argument constructor

SpringRunner 类选项 2:自动注入(inject)

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

private MyClassService myClassService = new myClassService(myClassRepository);

}

I feel like it is breaking the desired pattern.

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);
}
}

As commented: Obviously NOT working, since MyClassRepository its an interface

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

最佳答案

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

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

关于java - 使用构造函数注入(inject)模式对 spring boot 进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com