0

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ! And how to use the field name string variable foo in the test nethod ?
use the ReflectionTestUtils.getField(foo, "foo") method, you need to cast it since it returns Object. The first param is the target and the second is the field name. @Som

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.