简体   繁体   中英

How to mock CreateBatchWrite object in Xunit

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. System.NotSupportedException: Parent does not have a default constructor. The default constructor must be explicitly defined. Can anyone help me on this?

As BatchWrite has no default constructor, you have to wrap it in another class that you can control, ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM