在 Spring Boot 中,我有服务 myService
,方法如下:
@Service
public class MyService {
...
public FooBarInterface getNewFooBarInstance(boolean x) {
return x ? new Foo() : new Bar();
}
}
Foo 和 Bar 有一个字段:
@Value(...)
String loremPath;
从 application.yml
读取(Foo 的值为 ./src/java/resources/ipsum.txt
,Bar 的值为 ./src/java/resources/dolor.txt
)
现在我想为使用该方法的服务编写测试,但我希望有不同的 loremPath
值,例如。 ./src/test/resources/test.txt
@ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@InjectMocks
MyService myService;
...
}
我尝试过这个:
@Mock Foo foo;
@Mock Bar bar;
...
ReflectionTestUtils.setField(foo,"loremPath",".../test.txt");
ReflectionTestUtils.setField(bar,"loremPath",".../test.txt");
但这不起作用,我在 loremPath 中有一个 null
值。
我也尝试这样做:
String testPath = ".../test.txt";
when(foo.getLoremPath()).thenReturn(testPath);
when(bar.getLoremPath()).thenReturn(testPath);
但我仍然有 null
值。
最佳答案
您可以模拟该值的 getter。
when(foo.getValue()).thenReturn("mockvalue")
不要忘记在类(class)中使用所需的运行者
@RunWith(MockitoJUnitRunner.class)
关于java - 如何在junit测试中通过服务方法模拟返回对象的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61953340/