1

I’m writing a unit test in c# and I need to mock the response of CreateBatchWrite using Moq but not able to instantiate an object of the BatchWrite object. I’m doing this: _dbContext.Setup(m => m.CreateBatchWrite<type>(It.IsAny<DynamoDBOperationConfig>())) .Returns(Mock.Of<BatchWrite<type>>());

I'm currently trying this but getting error : System.NotSupportedException: Parent does not have a default constructor. The default constructor must be explicitly defined. Can anyone help me on this?

Biswajit Maharana
  • 531
  • 1
  • 8
  • 23

1 Answers1

0

As BatchWrite has no default constructor, you have to wrap it in another class that you can control, i.e., one with a default constructor...

For example:

public class BatchWriteWrapper<T>
{
    private readonly BatchWrite<T> _batchWrite;

    public BatchWriteWrapper()
    { }

    public BatchWriteWrapper(BatchWrite<T> batchWrite)
    {
        _batchWrite = batchWrite;
    }

    public void MethodFromBatchWrite()
    {
        _batchWrite.MethodFromBatchWrite();
    }
    
    // etc.
}

In your code you can now instantiate your wrapper class with BatchWrite instance and test on the wrapper instance.

Your _dbContext can be set up as follows:

_dbContext.Setup(m => m.CreateBatchWrite<type>(It.IsAny<DynamoDBOperationConfig>()))
.Returns(Mock.Of<BatchWriteWrapper<type>>());

And in your code, you wrap any BatchWrite instance you get, and use the wrapper instead:

var batchWrite = new BatchWriteWrapper(_dbContext.CreateBatchWrite<type>(...));

If you want to take it a step further, you can also wrap the type of your _dbContext so that it returns wrapped instances instead of its own (non-mockable) instances.

kalu93
  • 226
  • 2
  • 4