以通用功能接口作为参数的模拟方法 - Mockito
Mocking method with generic functional interface as an argument - Mockito
我正在开发应用程序,我决定使用 JUnit5 和 Mockito 对其进行测试。我有一个功能界面 FunctionSQL<T, R>
:
@FunctionalInterface
public interface FunctionSQL<T, R> {
R apply(T arg) throws SQLException;
}
我还有 DataAccessLayer class - 获取 databaseURL
和 connectionProperties
的构造函数由于可读性问题而被省略:
public class DataAccessLayer {
private String databaseURL;
private Properties connectionProperties;
public <R> R executeQuery(FunctionSQL<Connection, R> function){
Connection conn = null;
R result = null;
try {
synchronized (this) {
conn = DriverManager.getConnection(databaseURL, connectionProperties);
}
result = function.apply(conn);
} catch (SQLException ex) { }
finally {
closeConnection(conn);
}
return result;
}
private void closeConnection(Connection conn) {
try {
if (conn != null)
conn.close();
} catch (SQLException ex) { }
}
和抽象存储库class:
public abstract class AbstractRepository {
protected DataAccessLayer dataAccessLayer;
public AbstractRepository() {
dataAccessLayer = new DataAccessLayer();
}
}
我还创建了存储库的实现:
public class ProgressRepository extends AbstractRepository {
public List<ProgressEntity> getAll() {
String sql = "SELECT * FROM progresses";
return dataAccessLayer.executeQuery(connection -> {
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery();
List<ProgressEntity> progresses = new ArrayList<>();
while (result.next()){
ProgressEntity progressEntity = new ProgressEntity();
progresses.add(progressEntity);
}
statement.close();
return progresses;
});
}
我试图找到一个解决方案来模拟 DataAccessLayer
class 中的 executeQuery(...)
方法。我想更改用作 lambda 参数的 connection
。
我试过这个:
class ProgressRepositoryTest {
@Mock
private static DataAccessLayer dataAccessLayer = new DataAccessLayer();
private static Connection conn;
@BeforeEach
void connecting() throws SQLException {
conn = DriverManager.getConnection("jdbc:h2:mem:test;", "admin", "admin");
}
@AfterEach
void disconnecting() throws SQLException {
conn.close();
}
@Test
void getAllTest(){
when(dataAccessLayer.executeQuery(ArgumentMatchers.<FunctionSQL<Connection, ProgressEntity>>any())).then(invocationOnMock -> {
FunctionSQL<Connection, ProgressEntity> arg = invocationOnMock.getArgument(0);
return arg.apply(conn);
});
ProgressRepository progressRepository = new ProgressRepository();
progressRepository.getAll();
}
}
但是我收到一个错误:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
如果我的问题得到解决,我将不胜感激。
提前感谢您的帮助!
几件事。您是否使用 MockitoAnnotations.initMocks(this);
或 @ExtendWith(MockitoExtension.class)
初始化模拟?你声明了一个 @Mock
但你马上初始化了一个 class 的实例。
@Mock
private static DataAccessLayer dataAccessLayer = new DataAccessLayer();
应该是:
@Mock
private DataAccessLayer dataAccessLayer;
此外,DataAccessLayer 是最终的 class,除非包含 mockito-inline,否则您无法对其进行模拟。
我正在开发应用程序,我决定使用 JUnit5 和 Mockito 对其进行测试。我有一个功能界面 FunctionSQL<T, R>
:
@FunctionalInterface
public interface FunctionSQL<T, R> {
R apply(T arg) throws SQLException;
}
我还有 DataAccessLayer class - 获取 databaseURL
和 connectionProperties
的构造函数由于可读性问题而被省略:
public class DataAccessLayer {
private String databaseURL;
private Properties connectionProperties;
public <R> R executeQuery(FunctionSQL<Connection, R> function){
Connection conn = null;
R result = null;
try {
synchronized (this) {
conn = DriverManager.getConnection(databaseURL, connectionProperties);
}
result = function.apply(conn);
} catch (SQLException ex) { }
finally {
closeConnection(conn);
}
return result;
}
private void closeConnection(Connection conn) {
try {
if (conn != null)
conn.close();
} catch (SQLException ex) { }
}
和抽象存储库class:
public abstract class AbstractRepository {
protected DataAccessLayer dataAccessLayer;
public AbstractRepository() {
dataAccessLayer = new DataAccessLayer();
}
}
我还创建了存储库的实现:
public class ProgressRepository extends AbstractRepository {
public List<ProgressEntity> getAll() {
String sql = "SELECT * FROM progresses";
return dataAccessLayer.executeQuery(connection -> {
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet result = statement.executeQuery();
List<ProgressEntity> progresses = new ArrayList<>();
while (result.next()){
ProgressEntity progressEntity = new ProgressEntity();
progresses.add(progressEntity);
}
statement.close();
return progresses;
});
}
我试图找到一个解决方案来模拟 DataAccessLayer
class 中的 executeQuery(...)
方法。我想更改用作 lambda 参数的 connection
。
我试过这个:
class ProgressRepositoryTest {
@Mock
private static DataAccessLayer dataAccessLayer = new DataAccessLayer();
private static Connection conn;
@BeforeEach
void connecting() throws SQLException {
conn = DriverManager.getConnection("jdbc:h2:mem:test;", "admin", "admin");
}
@AfterEach
void disconnecting() throws SQLException {
conn.close();
}
@Test
void getAllTest(){
when(dataAccessLayer.executeQuery(ArgumentMatchers.<FunctionSQL<Connection, ProgressEntity>>any())).then(invocationOnMock -> {
FunctionSQL<Connection, ProgressEntity> arg = invocationOnMock.getArgument(0);
return arg.apply(conn);
});
ProgressRepository progressRepository = new ProgressRepository();
progressRepository.getAll();
}
}
但是我收到一个错误:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
如果我的问题得到解决,我将不胜感激。 提前感谢您的帮助!
几件事。您是否使用 MockitoAnnotations.initMocks(this);
或 @ExtendWith(MockitoExtension.class)
初始化模拟?你声明了一个 @Mock
但你马上初始化了一个 class 的实例。
@Mock
private static DataAccessLayer dataAccessLayer = new DataAccessLayer();
应该是:
@Mock
private DataAccessLayer dataAccessLayer;
此外,DataAccessLayer 是最终的 class,除非包含 mockito-inline,否则您无法对其进行模拟。