【发布时间】:2026-01-06 20:35:01
【问题描述】:
如何模拟mongoTemplate.aggregation().getUniqueMappedResults()?
为什么在RepoClass中返回NullPointerException?
mongoTemplate.aggregate(aggregation, COLLECTION_NAME,ScreenDetailsEntity.class);
我是 Spring 新手,第一次编写测试用例。我非常疲倦。 请帮忙。提前致谢。
RepoTestClass的Test函数:
@Test
public void testValidGetScreenDetails() {
ReflectionTestUtils.setField(
screenDetailsRepoService, "screenFields",
ClassUtil.getFieldName(ScreenDetailsEntity.class));
Aggregation aggregation1 = Aggregation.newAggregation(
match(where(PAGE).is("Bookings")),
project(ClassUtil.getFieldName(ScreenDetailsEntity.class)),
limit(1)
);
MongoTemplate mongoTemplate = Mockito.mock(MongoTemplate.class);
Aggregation aggregation = Mockito.mock(Aggregation.class);
ScreenDetailsEntity screenDetailsEntity = Mockito.mock(ScreenDetailsEntity.class);
AggregationResults<ScreenDetailsEntity> aggregationResultsMock = Mockito
.mock(AggregationResults.class);
Mockito.when(aggregationResultsMock.toString()).thenReturn(new String());
Mockito.doReturn(aggregationResultsMock).when(mongoTemplate).aggregate(aggregation1, COLLECTION_NAME, ScreenDetailsEntity.class);
Mockito.doReturn(screenDetailsEntity).when(aggregationResultsMock).getUniqueMappedResult();
screenDetailsRepoService.getScreenDetails(
"Bookings", "Web8", "List/View", "en", 45429, 121);
}
回购类:
public class ScreenDetailsRepoService {
@Autowired
private MongoTemplate mongoTemplate;
private String[] screenFields;
@PostConstruct
public void init() {
screenFields = ClassUtil.getFieldName(DetailsEntity.class);
}
public ScreenDetailsEntity getScreenDetails(final @NonNull String page,
final @NonNull String client, final String module,
final String locale, final Integer hotelId, final Integer countryId
) throws NoDataFoundException {
ScreenDetailsEntity screenDetailsEntity;
Aggregation aggregation = newAggregation(
match(where(PAGE).is(page)),
project(screenFields),
limit(1)
);
long t1 = System.currentTimeMillis();
screenDetailsEntity = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, ScreenDetailsEntity.class).getUniqueMappedResult();
log.info(
"DB Query: ScreenDetailsRepoService : getScreenDetails - Time taken for db requests : {} milliseconds",
(System.currentTimeMillis() - t1));
if (screenDetailsEntity == null) {
log.error(
"ScreenDetailsRepoService::getScreenDetails - No data found for for page {} ,module {}, locale {}, hotel {}, country {}",
page, module, locale, hotelId, countryId);
throw new NoDataFoundException("No data found");
}
return screenDetailsEntity;
}
【问题讨论】:
标签: java mongodb spring-boot mockito aggregation