【发布时间】:2016-02-08 20:34:58
【问题描述】:
我有点困惑编写单元测试来测试 MongoDB WriteOneAsync()。 我尝试在 MongoDB 示例上运行单元测试,该示例将文档写入 MongoDB,但无法将文档写入数据库。
下面是我的代码。我试着等待 mc.savetomongo();但它不能等待无效。
这只是我用来演示问题的示例。我的实际代码使用接口和数据层,但同样的问题。
如果我从它自己的项目类或表单项目中调用 savetomongo(),我应该说代码可以正常工作。问题似乎只存在于单元测试时。
任何帮助都将不胜感激!
非常感谢
我有一个单元测试项目如下,
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using mongotestclass;
namespace UnitTestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public async void TestMethod1()
{
Mongoclass mc = new Mongoclass();
mc.savetomongo();
}
}
}
我还有一个单独的类项目,其中包含以下内容。
using MongoDB.Bson;
using MongoDB.Driver;
using System;
namespace mongotestclass
{
public class Mongoclass
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
public async void savetomongo()
{
Uri con;
Uri.TryCreate("mongodb://" + "DESKTOP-263RHTL:27017", UriKind.Absolute, out con);
_client = new MongoClient(new MongoClientSettings
{
ConnectTimeout = new TimeSpan(0, 0, 0, 5, 0),
Server = new MongoServerAddress(con.Host, con.Port)
});
_database = _client.GetDatabase("SchemaTest3");
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertOneAsync(document);
}
}
}
【问题讨论】:
标签: c# mongodb unit-testing async-await