ReflectionTestUtils.setfield不会覆盖本地项目属性属性

时间:2017-04-16 17:44:38

标签: java spring microservices

我正在努力解决如何覆盖.yml文件中的属性文件

我们使用Spring框架并使用注释(例如@InjectMocks)。

我在配置项目YML文件中声明了一个名为&#34; one-platform-properties&#34;叫paysafe-ss-fx-service.yml。它设置了一个名为<table border="1" id="orderForm"> <tr> <th colspan="2">Customer Details</th> </tr> <tr> <td id="font">Customer Name</td> <td><input type="text" id="customerName"></td> </tr> </table> <button type="button" id="button1" onClick="window.clear()">Clear</button>的变量。它本质上是一个缓冲区的时间。

maxRecoveryAge=0

问题是我希望能够在我的测试中在运行时调整它。使缓冲液达到1小时,5小时和24小时。

我在测试中使用 oneplatform: environment: local publisher: rates: maxRecoveryAge: 0 interPublishDelay: 500 调用来调整时序,但是值没有被覆盖。当我对变量进行监视时,它在我的测试工具中工作,但是一旦测试运行渗透到微服务代码中,被覆盖的值就会丢失。关于如何在所有测试中保持覆盖值的任何想法都会持续存在?

我的目标是在测试运行中使用不同的变体:

ReflectionTestUtils.setfield(PublisherClass, "maxDocumentAge", 1, int.class)

并且基本上覆盖项目定义的属性文件中定义的值。

3 个答案:

答案 0 :(得分:1)

ReflectionTestUtils.setField(producerConfiguration, "messageProducer", realProducer);
Object target = AopTestUtils.getUltimateTargetObject(fxRatesEventPublisher);
int recoveryAge = -1;
ReflectionTestUtils.setField(target, "maxRecoveryAge", recoveryAge);

答案 1 :(得分:0)

为什么不使用@TestPropertySource#properties

  

以下示例演示了如何声明内联属性。

@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" })
public class MyIntegrationTests {
    // class body...
}

请注意javadocs

  

@TestPropertySource是一个类级别的注释

这意味着您需要为要使用的不同配置值设置不同的类。

答案 2 :(得分:0)

我认为您没有遵循最新的春季惯例和最佳做法告诉我们prefer constructor based injection over field based injection

如果您的bean声明如下:

public class FxRatesEventPublisher {
    private final Integer maxRecoveryAge;
    private final SomeDependency someDependency;

    public FxRatesEventPublisher(@Value("${publisher.rate.maxRecoveryAge}") Integer maxRecoveryAge, @Autowired SomeDependency someDependency) {
        this.maxRecoveryAge = maxRecoveryAge;
        this.someDependency = someDependency;
    }
}

然后你可以像这样实例化它:

// Create an instance with your test values injected. Note that you could inject mocked dependency here as well as the real one.
FxRatesEventPublisher fxRatesEventPublisher = new FxRatesEventPublisher(24, mockDependency); 

在这种情况下,测试组件要容易得多,因为您可以将任何值传递给构造函数。我同意这似乎不比基于房产的注射更漂亮,但至少值得一看。