问题描述
在Spring Boot应用中,我通过R2DBC的DatabaseClient实现了一个Repository类,核心数据库操作代码如下:
return client.sql(sqlToSearch)
.bind("alternateCodeType", alternateCodeType)
.bind("alternateCode", alternateCode)
.map(locationR2DBCMapper::apply).one();
其中locationR2DBCMapper是自定义的BiFunction映射类,代码如下:
public class LocationR2DBCMapper implements BiFunction<Row, Object, Location> {
@Override
public Location apply(Row row, Object o) {
if(row.get(0)!=null)
{
Location location = new Location();
location.setId(row.get("location_id", Long.class));
location.setLocationName(row.get("location_name", String.class));
location.setLocationType(row.get("location_type", String.class));
location.setProjectionMsg(row.get("projection_msg", String.class));
location.setIsFacility(row.get("is_facility",Boolean.class));
return location;
}
else {
return new Location();
}
}
}
我想为这个Repository类编写JUnit测试用例,Mock上述数据库调用。尝试的Mock代码如下:
@BeforeEach
void setUp() {
databaseClientMock = Mockito.mock(DatabaseClient.class);
locationR2DBCMapperMock = Mockito.mock(LocationR2DBCMapper.class);
DatabaseClient databaseClientMock = mock(DatabaseClient.class);
DatabaseClient.GenericExecuteSpec executeSpecMock = mock(DatabaseClient.GenericExecuteSpec.class);
Mono<Location> monoResultMock = mock(Mono.class);
locationCustomRepositoryImplMock = new LocationCustomRepositoryImpl(databaseClientMock,locationR2DBCMapperMock);
}
@Test
public void getLocationByLocationTypeTest()
{
RowsFetchSpec<?> rowsFetchSpecMock = mock(RowsFetchSpec.class);
when(databaseClientMock.sql(anyString())).thenReturn(executeSpecMock);
when(executeSpecMock.map(Mockito.any(BiFunction.class))).thenReturn(rowsFetchSpecMock);
Flux<Object> resultFluxMock = Flux.empty(); // Replace this with your own Flux instance
when(rowsFetchSpecMock.all()).thenReturn(resultFluxMock);
//Mockito.when(databaseClientMock.sql(anyString())).thenReturn(Flux.just(Location.builder().locationName("someName").id(Long.valueOf(123)).build()));
}
但在when(rowsFetchSpecMock.all()).thenReturn(resultFluxMock)这一行报错,提示“Cannot resolve method 'thenReturn(Flux