【发布时间】:2021-09-16 17:27:08
【问题描述】:
如何对这个类进行单元测试?或者应该如何将其重构为可单元测试?
public class DomainEventsMigrator : IDomainEventsMigrator
{
private readonly string _sourceDbConnectionString;
private readonly string _destinationDbConnectionString;
private readonly ILogger<DomainEventsMigrator> _logger;
public DomainEventsMigrator(string sourceDbConnectionString, string destinationDbConnectionString, ILogger<DomainEventsMigrator> logger)
{
_sourceDbConnectionString = sourceDbConnectionString;
_destinationDbConnectionString = destinationDbConnectionString;
_logger = logger;
}
public async Task MoveBatchAsync(MigrationBatch batch)
{
Stopwatch stopWatch = Stopwatch.StartNew();
try
{
using SqlConnection sourceConnection = new(_sourceDbConnectionString);
await sourceConnection.OpenAsync();
var query =
@"SELECT StreamId, MessageId, EventDate, EventDataType, EventPayloadJson, IsActive
FROM dbo.tblExecutionPathDomainEvents WITH (NOLOCK)
WHERE Id >= @FromId AND Id < @ToId
ORDER BY Id";
SqlCommand commandSourceData = new(query, sourceConnection);
commandSourceData.Parameters.AddWithValue("@FromId", batch.FromId);
commandSourceData.Parameters.AddWithValue("@ToId", batch.ToId);
SqlDataReader reader = await commandSourceData.ExecuteReaderAsync();
stopWatch.Stop();
_logger.LogInformation($"Read attempt successful in {stopWatch.Elapsed}, FromId = {batch.FromId}, ToId = {batch.ToId}");
stopWatch = Stopwatch.StartNew();
using SqlConnection destinationConnection = new(_destinationDbConnectionString);
await destinationConnection.OpenAsync();
using SqlBulkCopy bulkCopy = new(destinationConnection);
bulkCopy.DestinationTableName = "dbo.tblExecutionPathDomainEvents";
bulkCopy.BulkCopyTimeout = 3600;
bulkCopy.BatchSize = 1000;
try
{
await bulkCopy.WriteToServerAsync(reader);
stopWatch.Stop();
_logger.LogInformation($"Write attempt successful in {stopWatch.Elapsed}, FromId = {batch.FromId}, ToId = {batch.ToId}");
}
catch (Exception e)
{
stopWatch.Stop();
_logger.LogError(e, $"Write attempt failed in {stopWatch.Elapsed}, FromId = {batch.FromId}, ToId = {batch.ToId}");
}
finally
{
reader.Close();
}
}
catch (Exception ex)
{
stopWatch.Stop();
_logger.LogError(ex, $"Read attempt failed in {stopWatch.Elapsed}, FromId = {batch.FromId}, ToId = {batch.ToId}");
}
}
}
【问题讨论】:
-
你想测试什么行为?
-
比如说,调用 bulkCopy.WriteToServerAsync 方法时抛出的异常应该被捕获。 @彼得邦斯
标签: c# database unit-testing mocking sqlconnection