MongoDB WriteConcernResult如何被嘲笑?

时间:2016-02-14 14:35:04

标签: c# mongodb unit-testing mocking rhino-mocks

我正在尝试模拟通过WriteConcernResult;

返回的Insert()

我的提供商返回WriteConcernResult,并通过添加用户调用Insert()

private readonly IMongoProvider _repository;

public UserRepository(IMongoProvider repository)
{
    _repository = repository.ForCollection("User");
}

public bool AddUser(UserModel user)
{
    var result = _repository.Insert(user);
    return result.DocumentsAffected > 0;
}

MongoDB WriteConcernResult类:

public WriteConcernResult(BsonDocument response)
{
    _response = Ensure.IsNotNull(response, nameof(response));
}

public long DocumentsAffected
{
    get
    {
        BsonValue value;
        return _response.TryGetValue("n", out value) ? value.ToInt64() : 0;
    }
}

因为DocumentsAffected没有setter,所以我不确定如何设置我的mock将返回的值。

{
    var user = new UserModel {Name = "Test"};

    _mockMongoProvider = MockRepository.GenerateMock<IMongoProvider>();

     //mock writeConcernResult

     var result = _repo.AddUser(user);
     Assert.That(result, Is.True);
}

使用setter我可能会这样嘲笑:

_mockMongoProvider.Stub(p => p.Insert(user))
                  .Return(new WriteConcernResult(
                                                    new BsonDocument()
                                                ).DocumentsAffected = 1);

任何指导都会非常有用,欢呼。

1 个答案:

答案 0 :(得分:2)

实际上你根本不需要模拟WriteConcernResult类。

您所要做的就是初始化WriteConcernResult的实例,如下所示:

var document = new BsonDocument();
document.Add("n", new BsonInt64(1));
var writeConcernResult = new WriteConcernResult(document);

然后,您必须设置模拟存储库以返回此实例:

_mockMongoProvider.Stub(p => p.Insert(user))
                  .Return(writeConcernResult );