【发布时间】:2021-01-15 03:04:15
【问题描述】:
我正在将代码库迁移到 Java 11 和 JPMS / Jigsaw,但在模拟时遇到了一些问题。
这是我要运行的测试。
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class DbTest {
@Mock
private Connection connection;
@Mock
private PreparedStatement preparedStatement;
@Captor
private ArgumentCaptor<Timestamp> dateCaptor;
@Test
public void setTimestamp_instant() throws SQLException {
Instant inputTime = Instant.parse("2018-03-12T10:25:37.386Z");
when(connection.prepareStatement(anyString())).thenReturn(preparedStatement);
PreparedStatement preparedStatement = connection.prepareStatement("UPDATE fakeTable SET time = ? WHERE TRUE");
RowPack rowPack = new RowPack(preparedStatement, DatabaseType.MYSQL);
rowPack.setTimestamp(inputTime);
verify(preparedStatement).setTimestamp(anyInt(), dateCaptor.capture(), Mockito.any(Calendar.class));
}
}
在 Eclipse 中运行此测试时它通过了,但是当我通过 maven 运行它时它失败了,因为 mockito 无法使用反射找到一些资源。
org.mockito.exceptions.base.MockitoException: Problems setting field connection annotated with @org.mockito.Mock(name="", stubOnly=false, extraInterfaces={}, answer=RETURNS_DEFAULTS, serializable=false, lenient=false)
Caused by: java.lang.IllegalAccessException: class org.mockito.internal.util.reflection.ReflectionMemberAccessor cannot access a member of class foo.bar.DbTest (in module foo.bar) with modifiers "private"
我正在使用 Surefire 3.0.0-M5、junit 5.7.0 和 mockito 3.5.10。
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
不用说,在切换到使用 JPMS 进行模块化之前,这在 maven 中运行良好。
我已阅读 Testing in the modular world 并尝试使用 junit-platform-maven-plugin 作为surefire 的替代品,但在使用 mockito 时遇到了类似的问题。
我们将不胜感激。
【问题讨论】:
-
仅仅基于测试私有的东西没有意义......只测试公共接口......是的模块可以防止这种情况,因为它比私有/受保护/包等更难一般Java 世界
标签: java maven junit mockito java-platform-module-system