Reputation: 1610
This is my class :
public class Foo {
@Value("${myapp.foo}")
private String foo;
void fooValue(){
// some code
}
}
This is my test class :
@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@InjectMocks
private Foo foo;
@Before
public void setUp() {
ReflectionTestUtils.setField(foo, "myappfoo", "foo");
}
@Test
public void testFoo() {
// some test code
}
}
When I am running the test I get the below error :
java.lang.IllegalArgumentException: Could not find field 'myapp.foo' of type [null] on target object [Foo@18271936] or target class [class Foo]
at org.springframework.test.util.ReflectionTestUtils.setField(ReflectionTestUtils.java:185)
at org.springframework.test.util.ReflectionTestUtils.setField(ReflectionTestUtils.java:120)
Also I want to use the string variable foo in my test method. How to do that.
Upvotes: 0
Views: 2107
Reputation: 181
ReflectionTestUtils receive the second parameter as the field name, you can just directly code
ReflectionTestUtils.setField(foo, "foo", "foo");
the first argument is the target, second is field name, the third is the value
Upvotes: 2