MockedStatic:需要但未调用实际上,与此模拟的交互为零

问题描述 投票:0回答:1

我在

Mockito
MockedStatic
方面遇到了一些麻烦,尽管我的
static
方法被使用正确的参数调用(通过放置调试打印语句进行验证),Mockito 仍然在抱怨

这是我的主题代码

import com.company.project.bo.requests.MyRequest;
import com.company.project.bo.responses.MyResponse;
import com.company.project.util.LoggingHelper;

class MySubjectClass {
    ..
    // this is the entry-point function
    public MyResponse enact(final MyRequest request) {
        logInputs(request);
        ..
    }

    private void logInputs(final MyRequest request) {
        ..
        // I verified by adding debug print statements here to verify
        // that indeed this is getting invoked (with correct arguments)
        LoggingHelper.recordEntityId(request.getEntityId());
        ..
    }
..
}

这是我的单元测试:

import com.company.project.bo.EntityId;
import com.company.project.bo.responses.MyResponse;
import com.company.project.util.LoggingHelper;

import org.junit.Test;
import org.mockito.MockedStatic;

class TestMySubjectClass {
    private static final EntityId ENTITY_ID = EntityId.of("XYZ0123PQR789LMN");
    private final MyClass subject = new MyClass(); // subject: object of class under test
    ..

    @Test
    public void myTestMethod() {
        ..
        final MyResponse response = subject.enact(request);
        try (final MockedStatic<LoggingHelper> mockedStatic = Mockito.mockStatic(LoggingHelper.class)) {
            ..
            mockedStatic.verify(() -> LoggingHelper.recordEntityId(ENTITY_ID.value()));
            mockedStatic.verifyNoMoreInteractions();
        }   
    }
}

这是我收到的错误:

Wanted but not invoked:
LoggingHelper.class.recordEntityId(
    "XYZ0123PQR789LMN"
);
-> at com.company.project.util.LoggingHelper.recordEntityId(LoggingHelper.java:214)
Actually, there were zero interactions with this mock.

令人费解的是,相同的

mockedStatic
实现在此类中的其他测试方法中运行得很好,只是在这个特定的测试用例中失败了。

我哪里出错了?

mockito
1个回答
0
投票
  • 我的错。 我在 MockedStatic
    try
    之外调用我的
    被测方法
  • 将调用(触发整个函数被单元测试)移动到
    try
    块内后,它开始通过

错了

..
final MyResponse response = subject.enact(request); // this was placed outside try-block
try (final MockedStatic<LoggingHelper> mockedStatic = Mockito.mockStatic(LoggingHelper.class)) {
    ..
    mockedStatic.verifyNoMoreInteractions();
}

正确

..
try (final MockedStatic<LoggingHelper> mockedStatic = Mockito.mockStatic(LoggingHelper.class)) {
    final MyResponse response = subject.enact(request); // it was supposed to be inside try-block
    ..
    mockedStatic.verifyNoMoreInteractions();
}
© www.soinside.com 2019 - 2024. All rights reserved.