【问题标题】:Mocks are not returning values properly with mockitoextension.class (Junit5)模拟没有使用 mockitoextension.class 正确返回值(Junit5)
【发布时间】:2021-03-05 10:56:40
【问题描述】:

所以我有这段代码,我试图在其中模拟参加者收到通知:

 @Mock
    Event event;

    @Mock
    Attendee attende;

    @InjectMocks
    EventNotificationServiceImpl eventNotificationService;

    @Test
    public void checkIfAttendesAreNotified() {

        event.addAttendee(attende);

        eventNotificationService.announce(event);

        System.out.println(attende.getNotifications());

        List<Notification> notifications = attende.getNotifications();

        for (Notification notification : notifications) {

            assertEquals("The next big event is coming!", notification.getMessage());

        }
    }

但是在这里我没有看到参加者收到任何通知。但是当我输入此代码时,我看到参加者收到通知:

  @Mock
    Event event;

    @Mock
    Attendee attende;

    @InjectMocks
    EventNotificationServiceImpl eventNotificationService;

    @Test
    public void checkIfAttendesAreNotified() {
        attende = new Attendee(1L,"sara", "sara@example.com");
        event = new Event();
        event.addAttendee(attende);

        eventNotificationService.announce(event);

        System.out.println(attende.getNotifications());

        List<Notification> notifications = attende.getNotifications();

        for (Notification notification : notifications) {

            assertEquals("The next big event is coming!", notification.getMessage());

        }
    }

我想知道为什么没有初始化模拟。我不想在测试中创建事件和参与者对象,因为这给我带来了问题,因为当我尝试验证时,参与者和事件不被识别为模拟。如果有人可以帮助我,我将非常感激! :)))

【问题讨论】:

    标签: java testing junit mocking mockito


    【解决方案1】:

    您没有在 eventattendee 模拟上存根任何方法调用。 因此,Mockito 将其默认行为应用于未存根的方法 - 它根据方法返回类型返回默认值。

    How about some stubbing?

    默认情况下,对于所有返回值的方法,mock 将根据需要返回 null、原始/原始包装器值或空集合。例如 0 表示 int/Integer,false 表示 boolean/Boolean。

    因此,您的测试行为如下:

    // Do nothing - return value ignored
    event.addAttendee(attende);
    
    // Do nothing - return value ignored
    eventNotificationService.announce(event);
    
    // Print empty list
    System.out.println(attende.getNotifications());
    
    // Store empty list in a variable
    List<Notification> notifications = attende.getNotifications();
    
    // Loop over empty list
    for (Notification notification : notifications) {
        assertEquals("The next big event is coming!", notification.getMessage());
    }
    

    【讨论】:

    • 但我不想更改参加者的返回值,我只想初始化作为具有自定义值的对象的参加者,...不知道用存根是否有意义?
    • 不,您通常会模拟被测对象的协作者在测试中具有您不希望的行为(如 http 请求、数据库请求、长时间计算等)。对于易于构建且没有不良行为的对象,您最好使用真实对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多