【发布时间】:2020-05-24 01:24:50
【问题描述】:
我有一个 POJO 类:
@Data @Document
public class RoomPreferences{
private TypeEnum roomType;
private BigDecimal minLen;
private BigDecimal maxLen;
private List<BigDecimal> defaultPrices;
}
我想在测试时填充一个 RoomPreferences 对象,并且我正在使用 Mockito,但我的 RoomPreferences 对象的字段始终是 null。
public class TestingClass {
@Mock private RoomPreferences roomPreferences;
@InjectMocks public RoomServiceImpl roomService;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test() {
when(roomPreferences.getMinLen()).thenReturn(BigDecimal.valueOf(10));
...
}
}
【问题讨论】:
-
是的,因为您正在模拟 RoomPreference 对象,但没有说为对象字段创建模拟值。也许您可以为 RoomPreferences 创建自己的模拟对象构建器类。或者您可以为每个测试类设置一次@BeforeClass 方法中的每个对象字段。
-
谢谢。但是当我这样做时:when(roomPreferences.getMinLen()).thenReturn(BigDecimal.valueOf(10));,我将一个 Mock 值分配给 RoomPreference 模拟的字段。为 minLen::BigDecimal 字段赋值的正确方法是什么?
-
不要模拟值对象,因为它们没有行为;只需创建一个并按照您想要的方式设置其值。
-
尝试细化您的问题。给我们更多的背景;你想测试什么,为什么?这个问题具体与 Spring/Spring-Boot 有什么关系? (可能更新您的标签)。此外(在您的评论中)
What would be the correct way to assign a value to the minLen::BigDecimal field?太宽泛了。在当前状态下回答您的问题很困难(= 我们这边的猜测工作)并且不会得到明确(= 好的)答案;因此,它对未来的其他社区成员不会有太大帮助。看看How do I ask a good question? -
也许字段设置器可以为您提供帮助。 codota.com/code/java/methods/…
标签: java spring spring-boot testing mockito