gpt4 book ai didi

c# - 单元测试 MongoWriteExceptions

转载 作者:可可西里 更新时间:2023-11-01 10:02:49 25 4
gpt4 key购买 nike

我想使用 Mongo 驱动程序测试我对 MongoWriteException 的处理,这里是一个示例方法:

    private void Update()
{
try
{
var find = Builders<Filter>.Filter.Eq(e => e.Id, "someId");
var update = Builders<Filter>.Update.Set(e => e.SomeValue, "AValue");
_documentStore.MongoCollection<Filter>().UpdateOne(find, update, new UpdateOptions { IsUpsert = true }, CancellationToken.None);
}
catch (MongoWriteException mongoWriteException)
{
if (mongoWriteException.WriteError.Category != ServerErrorCategory.DuplicateKey)
{
throw;
}
}
}

有人知道如何模拟 MongoWriteException 吗?我试着像这样构造它:

var mongoWriteException = new MongoWriteException(new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("d", 2)), 0), new WriteError(), // <- Protected constructor

但是 WriteError 类有一个内部构造函数

最佳答案

一个基于the driver's own tests 的小例子但是使用反射来访问内部构造函数

static class MockMongoCollection // : IMongoCollection<TDocument>
{
private static readonly MongoWriteException __writeException;

static MockMongoCollection()
{
var connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2);
var innerException = new Exception("inner");
var ctor = typeof (WriteConcernError).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0];
var writeConcernError = (WriteConcernError)ctor.Invoke(new object[] { 1, "writeConcernError", new BsonDocument("details", "writeConcernError") });
ctor = typeof (WriteError).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic)[0];
var writeError = (WriteError) ctor.Invoke(new object[] {ServerErrorCategory.Uncategorized, 1, "writeError", new BsonDocument("details", "writeError")});
__writeException = new MongoWriteException(connectionId, writeError, writeConcernError, innerException);
}

public static void UpdateOne()
{
throw __writeException;
}
}

class ExampleTests
{
[Test]
public void UncategorizedWriteExceptionTest()
{
Assert.Throws<MongoWriteException>(MockMongoCollection.UpdateOne);
}
}

还有一个使用 SerializationInfo 的构造函数可能有类似的味道。

关于c# - 单元测试 MongoWriteExceptions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com