我想使用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的构造函数,它可能有类似的味道。