在单元测试期间填充Spring @Value [英] Populating Spring @Value during Unit Test

查看:674
本文介绍了在单元测试期间填充Spring @Value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的程序中用于验证表单的简单bean编写单元测试。 bean使用 @Component 进行注释,并且有一个使用 @Value($ {this.property.value})私有化的类变量String thisProperty;



我想为这个类中的验证方法编写单元测试,但是,如果可能的话我想这样做不使用属性文件。我的理由是,如果我从属性文件中提取的值发生变化,我希望这不会影响我的测试用例。我的测试用例是测试验证值的代码,而不是值本身。



有没有办法在我的测试类中使用Java代码初始化Java类并在该类中填充Spring @Value属性然后用它来测试? / p>

我确实发现这个似乎很接近的操作方法但仍使用属性文件。我宁愿一切都是Java代码。



谢谢

解决方案

如果可能,我会尝试在没有Spring Context的情况下编写这些测试。如果你在没有spring的测试中创建这个类,那么你可以完全控制它的字段。



设置 @value 字段你可以使用Springs ReflectionTestUtils - 它有一个方法 setField 设置私有字段。



@see JavaDoc:ReflectionTestUtils.setField(java.lang.Object,java.lang.String,java.lang.Object)


I'm trying to write a Unit Test for a simple bean that's used in my program to validate forms. The bean is annotated with @Component and has a class variable that is initialized using @Value("${this.property.value}") private String thisProperty;

I would like to write unit tests for the validation methods inside this class, however, if possible I would like to do so without utilizing the properties file. My reasoning behind this, is that if the value I'm pulling from the properties file changes, I would like that to not affect my test case. My test case is testing the code that validates the value, not the value itself.

Is there a way to use Java code inside my test class to initialize a Java class and populate the Spring @Value property inside that class then use that to test with?

I did find this How To that seems to be close, but still uses a properties file. I would rather it all be Java code.

Thanks

解决方案

If possible I would try to write those test without Spring Context. If you create this class in your test without spring, then you have full control over its fields.

To set the @value field you can use Springs ReflectionTestUtils - it has a method setField to set private fields.

@see JavaDoc: ReflectionTestUtils.setField(java.lang.Object, java.lang.String, java.lang.Object)

这篇关于在单元测试期间填充Spring @Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆