我在
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
实现在此类中的其他测试方法中运行得很好,只是在这个特定的测试用例中失败了。
我哪里出错了?
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();
}