gpt4 book ai didi

java - 使用 mockito 将模拟注入(inject)抽象类

转载 作者:搜寻专家 更新时间:2023-11-01 03:49:33 24 4
gpt4 key购买 nike

我正在模拟如下抽象类:

myAbstractClass = Mockito.mock(MyAbstractClass.class, Mockito.CALLS_REAL_METHODS);

问题是 MyAbstractClass 有一些通过 EJB 注释注入(inject)的依赖项,但没有 setter 。有没有办法注入(inject)依赖项?

@InjectMocks 不适用于抽象类。

最佳答案

我为此使用 junit5。

我所做的是在 @BeforeEach 中使用 new abstractClass() 实例化抽象类,如果方法是通过 super 调用方法不是抽象的(使用它是因为我有 protected 方法),之后我使用 ReflectionUtils.setField() 在抽象类中设置模拟并测试每个方法和工作很不错。我留下一个有效的简单示例。

抽象类

public abstract class AbstractClass {
@Autowired
private Environment environment;

protected String getProperty(String property){
return environment.getRequiredProperty(property);
}
}

抽象类测试

@ExtendWith(MockitoExtension.class)
class AbstractClassTest {

AbstractClass abstractClass;

@Mock
Environment environment;

@BeforeEach
void setUp() {
abstractClass = new AbstractClass() {
@Override
public String getProperty(String property) {
return super.getProperty(property);
}
};
ReflectionTestUtils.setField(abstractClass, "environment", environment);
}

@Test
void shouldReturnProperty() {
String propertyValue = "this property";
when(environment.getRequiredProperty("property")).thenReturn(propertyValue);
String property = abstractClass.getProperty("property");
assertEquals(propertyValue, property);
}
}

这里只是用mockito和junit5来测试。请记住在使用 new AbstractClass() 实例化类后调用 ReflectionUtils,否则将不会注入(inject)模拟。

欢迎对此实现进行任何改进 :D。

关于java - 使用 mockito 将模拟注入(inject)抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32133102/

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