在 Spring 引导中模拟 @Value 注释时出错
Error Mocking a @Value annotation in Spring boot
这是我的 class :
public class Foo {
@Value("${myapp.foo}")
private String foo;
void fooValue(){
// some code
}
}
这是我的测试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
}
}
当我进行 运行 测试时,出现以下错误:
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)
我还想在我的测试方法中使用字符串变量 foo。怎么做。
ReflectionTestUtils接收第二个参数作为字段名,直接code
即可
ReflectionTestUtils.setField(foo, "foo", "foo");
第一个参数是目标,第二个是字段名,第三个是值
这是我的 class :
public class Foo {
@Value("${myapp.foo}")
private String foo;
void fooValue(){
// some code
}
}
这是我的测试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
}
}
当我进行 运行 测试时,出现以下错误:
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)
我还想在我的测试方法中使用字符串变量 foo。怎么做。
ReflectionTestUtils接收第二个参数作为字段名,直接code
即可ReflectionTestUtils.setField(foo, "foo", "foo");
第一个参数是目标,第二个是字段名,第三个是值