gpt4 book ai didi

java - Spring:对同时具有字段和构造函数注入(inject)的类进行单元测试

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:35:42 29 4
gpt4 key购买 nike

我有以下类(class)设置。

class Base {
@Autowired
private BaseService service; //No getters & setters
....
}

@Component
class Child extends Base {
private final SomeOtherService otherService;

@Autowired
Child(SomeOtherService otherService) {
this.otherService = otherService;
}
}

我正在为 Child 类编写单元测试。如果我使用 @InjectMocks,则 otherService 结果为空。如果我在测试设置中使用 Child 类的构造函数,则 Base 类中的字段将变为 null

我知道所有关于字段注入(inject)是邪恶的争论,但我更想知道是否有一种方法可以在不改变 BaseChild 方式的情况下解决这个问题类注入(inject)它们的属性?

谢谢!!

最佳答案

只需这样做:

public class Test {
// Create a mock early on, so we can use it for the constructor:
OtherService otherService = Mockito.mock(OtherService.class);

// A mock for base service, mockito can create this:
@Mock BaseService baseService;

// Create the Child class ourselves with the mock, and
// the combination of @InjectMocks and @Spy tells mockito to
// inject the result, but not create it itself.
@InjectMocks @Spy Child child = new Child(otherService);

@Before
public void before() {
MockitoAnnotations.initMocks(this);
}
}

Mockito 应该做正确的事。

关于java - Spring:对同时具有字段和构造函数注入(inject)的类进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045357/

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