提问者:小点点

模拟使用从属性文件读取可配置值的其他成员变量设置成员变量的构造函数


我有一个Spring mvc应用程序。有一个A类如下所示:

public class A extends X {

    private final RetryRegistry retryReg;

    @value("${retry.attempts:5}")
    private int retryAttempts;

    @value("${retry.delay:5000}")
    private int retryDelay;

    public A( B b, C c, D d){
        super(b,c,d);
        
        this.retryReg = RetryRegistry.of(RetryConfig.custom()
                         .maxAttempts(this.retryAttempts)   
                         .waitDuration(Duration.ofMillis(this.retryDelay))
                         .build());
    }
    
    .......
}

A类的测试类如下图:

@PrepareForTest(A.class)
@runWith(PowerMockRunner.class)
@SupressWarnings("unchecked")
public class ATest {

    @InjectMocks
    private A a;

........

}

现在,当测试类注入mock并调用A的构造函数时,构造函数内部retryAttempt的值为0,因此会引发异常。

当注入mock尝试构造A时,似乎没有读取可配置属性(来自servlet-context中提到的路径的属性文件)。

我尝试了许多方法,例如将@TestProperty tySource添加到我的测试文件中,但它不起作用。

@TestPropertySource(locations="classpath:SettingsTest.properties")
@PrepareForTest(A.class)
@runWith(PowerMockRunner.class)
@SupressWarnings("unchecked")
public class ATest {

    @InjectMocks
    private A a;

........

}

我做错了什么,还是@TestProperty tySource仅支持Springboot应用程序。关于如何在@InjectMocks尝试访问类A'构造函数之前设置可配置属性的任何建议。


共1个答案

匿名用户

您如何在@Configuration中将注册表创建为bean?

// this will automatically be initialized with yours properties
@ConfigurationProperties(prefix="retry)
class RetryProperties {
    private int attempts;
    private int delay;
}
@Configuration
class RetryConfiguration {
    @Bean RetryRegistry registry(RetryProperties props) {
        return RetryRegistry.of(RetryConfig.custom()
                 .maxAttempts(retryProperties)
                 .waitDuration(Duration.ofMillis(this.retryDelay))
                 .build());
    }
}
@Component // I assume, otherwise the @Value properties wouldn't work
public class A extends X {
    private final RetryRegistry retryReg;

    public A( B b, C c, D d, RetryRegistry reg){
        super(b,c,d);
        this.retryReg = reg;
    }
    .......
}

现在您可以模拟和注入注册表。

总的来说,你的结构看起来有点到处都是,一些构造函数自动装配,构造函数中的一些初始化,一些字段从属性中读取。你可能应该坚持其中一个。此外super(b, c,d)看起来很可疑,我很少看到类层次结构是组件的好主意(至少有三个参数)。

相关问题