简体   繁体   English

如何在 Xunit 中模拟 CreateBatchWrite 对象

[英]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.我正在用 c# 编写单元测试,我需要使用 Moq 模拟 CreateBatchWrite 的响应,但无法实例化 BatchWrite 对象的对象。 I'm doing this: _dbContext.Setup(m => m.CreateBatchWrite<type>(It.IsAny<DynamoDBOperationConfig>())) .Returns(Mock.Of<BatchWrite<type>>());我这样做: _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. 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...由于 BatchWrite 没有默认构造函数,因此您必须将其包装在另一个可以控制的类中,即具有默认构造函数的类...

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.在您的代码中,您现在可以使用 BatchWrite 实例实例化您的包装器类并在包装器实例上进行测试。

Your _dbContext can be set up as follows:您的_dbContext可以设置如下:

_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:在您的代码中,您包装您获得的任何BatchWrite实例,并改用包装器:

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.如果您想更进一步,您还可以包装_dbContext的类型,以便它返回包装的实例而不是它自己的(不可模拟的)实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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