【问题标题】:How to use Mockito to populate POJO如何使用 Mockito 填充 POJO
【发布时间】: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


【解决方案1】:

我从这个测试课中读到的内容:

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));
       ...
   }
}

类型为RoomServiceImplroomService 具有RoomPreferences 类型的属性。并且这个属性将被注入模拟对象“roomPreferences”。

模拟对象不会填充真实类的任何值。

你要做的是定义当一个方法(如在真实类中)被调用时,模拟应该做什么:

when(roomPreferences.getMinLen()).thenReturn(BigDecimal.valueOf(10));

如果你想为一个属性赋值,那么不要模拟这个类,而是使用真正的类。

我猜您面临的问题是在 roomService 对象中设置 RoomPreferences 属性。如果是这种情况,您应该将该类添加到问题中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多