Java 如何通过class.methods调用模拟@Inject?

Java 如何通过class.methods调用模拟@Inject?,java,dependency-injection,Java,Dependency Injection,我想对一个类进行单元测试,该类通常由javax.Inject.Inject中的@Inject注释创建一些配置 相反,我在测试开始时通过调用一些class.methods来考虑配置实例。这应该是可能的,因为类的构造函数被调用了 而不是 @Inject @Named ("reportsprops") protected Configuration reportsprops; ,在META-INF.spring中描述为: <bean id="reportsprops" class="o

我想对一个类进行单元测试,该类通常由javax.Inject.Inject中的@Inject注释创建一些配置

相反,我在测试开始时通过调用一些class.methods来考虑配置实例。这应该是可能的,因为类的构造函数被调用了

而不是

@Inject
@Named ("reportsprops")
protected Configuration reportsprops;
,在META-INF.spring中描述为:

<bean id="reportsprops"
    class="org.apache.commons.configuration.PropertiesConfiguration">
    <constructor-arg type="java.lang.String"
        value="file:${spr.root.dir}/reports.properties" />
    <property name="encoding" value="UTF-8" />
    <property name="throwExceptionOnMissing" value="true" />
    <property name="reloadingStrategy">
        <bean
            class="org.apache.commons.configuration.reloading.FileChangedReloadingStrategy" />
    </property>
</bean>
由于配置非常好,我需要在Spring填充它时从文件中填充它,而不需要手动模拟数百个单独的属性。像


createClass(配置,BeanProperties文件)

我更喜欢的方式是用Mockito为您打针

@ExtendWith(MockitoExtension.class) // or @RunWith(MockitoJUnitRunner.class) for junit 4
class YourTest {
    @InjectMocks
    private YourTestedClass sut;

    // this is a mock that will get injected into the sut
    @Mock
    private Configuration yourConfig;

    @BeforeEach
    void mockConfigData() {
        when(yourConfig.getPropertyX()).thenReturn("value");
    }
}
当然,您可以实际创建
配置的实例
并手动初始化它

class YourTest {
    private YourTestedClass sut;
    private Configuration configuration;

    @BeforeEach
    void initSut() {
        configuration = new Configuration();
        sut = new YourTestedClass(configuration);
    }
}

你是说
配置
构造函数代码做了一些测试运行所需的事情,所以仅仅模拟它是不够的?如果你使用基于构造函数的注入,这是非常简单(但非常乏味)的。我正在从事的项目是一个真实的、古老的、大量的代码和设置。该配置有数百个属性。因此,用手嘲笑他们是不可能的。第二条路给了我一个空的物体。我需要在Spring填充时从文件中填充它,而不需要手动模拟数百个单独的属性。无论如何,感谢您的尝试。@Gangnus和运行Spring测试,实际上
@Autowire
ing也是不可能的?这些确实需要更长的时间运行,但听起来这可能是你能做的最好的了。
class YourTest {
    private YourTestedClass sut;
    private Configuration configuration;

    @BeforeEach
    void initSut() {
        configuration = new Configuration();
        sut = new YourTestedClass(configuration);
    }
}