karan chavan
karan chavan

Reputation: 265

How to mock DynamodbContext BatchWrite for unit testing in net

I have a method that adds Items in the DynamoDb table using DynamoDbContext.

var batchWriteObj = context.CreateBatchWrite<myDynamoDBModel>
                                            (new DynamoDBOperationConfig { TableNamePrefix = "abc" });
                    batchWriteObj.AddPutItem(myDynamoDBModel);

I want to test this piece in my Unit test. Since BatchWrite does not have any constructor, and also its properties are not virtual. I am unable to create a mock for it.

Is there any way I can test this piece of code? maybe by mocking the BatchWrite?

Upvotes: 2

Views: 1745

Answers (2)

beautifulcoder
beautifulcoder

Reputation: 11340

I had to write a simple wrapper for this.

public interface IBatchWriteWrapper<T>
{
  IBatchWriteWrapper<T> CreateBatchWrite();
  void AddPutItems(List<T> items);
  Task ExecuteAsync(CancellationToken cancellationToken = default);
}

public class BatchWriteWrapper<T>(IDynamoDBContext _dynamoDb) : IBatchWriteWrapper<T>
{
  private BatchWrite<T>? _batchWrite;

  public IBatchWriteWrapper<T> CreateBatchWrite()
  {
    _batchWrite = _dynamoDb.CreateBatchWrite<T>();
    return this;
  }

  public void AddPutItems(List<T> items)
  {
    _batchWrite?.AddPutItems(items);
  }

  public Task ExecuteAsync(CancellationToken cancellationToken = default)
  {
    return _batchWrite?.ExecuteAsync(cancellationToken) ?? Task.CompletedTask;
  }
}

Upvotes: 0

Jason Wadsworth
Jason Wadsworth

Reputation: 8885

Have you considered using DynamoDB local to run tests? It has the added advantage of validating that your calls are doing what you expect them to do. I created a helper package for it a while back (https://www.nuget.org/packages/Wadsworth.DynamoDB.TestUtilities/). It just manages spinning up the DynamoDB local in a Docker container. You can see the source for it here, which includes an example.

Upvotes: 1

Related Questions