我在我的一项测试中苦苦挣扎。
这是我正在测试的代码
public async Task Handle(ReceiveEventsFromSalesForceCommand message, IMessageHandlerContext context)
{
var queryResult = await this.GenerateQueryResultAsync(message).ConfigureAwait(false);
await this.DetermineActionAsync(context, queryResult).ConfigureAwait(false);
}
public async Task<QueryResult<EventStore__c>> GenerateQueryResultAsync(ReceiveEventsFromSalesForceCommand message)
{
QueryResult<EventStore__c> queryResult;
if (string.IsNullOrWhiteSpace(message.NextRecordsUrl))
{
queryResult = await this.forceClient.QueryAsync<EventStore__c>(query).ConfigureAwait(false);
this.log.Info($"AFTER: QueryAllAsync<EventStore>(query), found {queryResult?.TotalSize ?? 0} records");
}
else
{
queryResult = await this.forceClient.QueryContinuationAsync<EventStore__c>(message.NextRecordsUrl).ConfigureAwait(false);
this.log.Info("AFTER: QueryContinuationAsync<EventStore>(query)");
}
return queryResult;
}
这是我的单元测试
[TestMethod]
public async Task Test()
{
// arrange
var forceConfig = Substitute.For<ISalesForceCreationHandlerConfig>();
var forceClient = Substitute.For<IForceClient>();
forceClient.QueryAllAsync<EventStore__c>(Arg.Any<string>()).Returns(Task.FromResult(new QueryResult<EventStore__c> { NextRecordsUrl = "Dummy" }));
var messageHandlerContext = Substitute.For<IMessageHandlerContext>();
var handler = new SalesForceBatchCreationHandler(forceClient, null, forceConfig);
// act
await handler.Handle(new ReceiveEventsFromSalesForceCommand(), messageHandlerContext);
// assert
await messageHandlerContext.Received().Send(Arg.Is<ReceiveEventsFromSalesForceCommand>(command => string.IsNullOrWhiteSpace(command.NextRecordsUrl)), Arg.Any<SendOptions>());
await messageHandlerContext.DidNotReceive().SendLocal(Arg.Any<PublishMultipleKlantManagementEnvelopeCreatedEventsCommand>());
}
我的问题是我的GenerateQueryResultAsync
方法的结果是null
,我得到一个NullReferenceException。如何确保结果不为null并避免异常?
答案 0 :(得分:0)
重新构建异步调用的方式。最有可能的是{queryResult.TotalSize}
是罪魁祸首。
public async Task<QueryResult<EventStore__c>> GenerateQueryResultAsync(ReceiveEventsFromSalesForceCommand message) {
QueryResult<EventStore__c> queryResult;
if (string.IsNullOrWhiteSpace(message.NextRecordsUrl)) {
queryResult = await this.forceClient.QueryAsync<EventStore__c>(query).ConfigureAwait(false);
this.log.Info($"AFTER: QueryAllAsync<EventStore>(query), found {queryResult?.TotalSize ?? 0} records");
} else {
queryResult = await this.forceClient.QueryContinuationAsync<EventStore__c>(message.NextRecordsUrl).ConfigureAwait(false);
this.log.Info("AFTER: QueryContinuationAsync<EventStore>(query)" );
}
return queryResult;
}