java - 如何在junit测试中通过服务方法模拟返回对象的字段?

标签 java junit

在 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/

相关文章:

java - 难以定位 Java Profiler 中提到的应用程序中的对象

java - 如何在 Java 中创建一个包含其他数组数据的新数组?

java - 尝试使用 JMockit 部分模拟类时,ClassLoader 抛出 NullPointerException

java - 使用 Mockito NotaMockException 进行 Junit 测试

java - Vaadin 流不支持操作异常 : Confirmed duplicate message from the client

java - 为什么我的程序没有给出预期的输出?

java - Z3py get_vars(f) 相当于 Java

java - 如何测试实用程序项目的 final方法和静态方法?

java - 我可以在单元测试时模拟特定的文件系统吗?

java - 如何集成 Citrus 框架和 BDD Cucumber