【问题标题】:Unit Testing MongoDB WriteOneAsync() Fails to create document单元测试 MongoDB WriteOneAsync() 无法创建文档
【发布时间】: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


    【解决方案1】:

    问题在于您的测试提前结束,因为您没有等待任何异步任务。因此,在插入文档和终止测试之间存在竞争条件。

    您实际上需要做的是公开一个async Task 操作,而不是async void,这将允许您在测试的调用链中向上await

    public Task SaveToMongoAsync()
    {
        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");
        return collection.InsertOneAsync(document);
    }
    

    现在也让你的测试 async Taskawait 在里面:

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public async Task TestMongoInsertionAsync()
        {
            Mongoclass mc = new Mongoclass();
            await mc.SaveToMongoAsync();
        }
    }
    

    作为旁注,我会改进这个测试,并返回一个你可以在测试中断言的值,以确保文档被正确插入。

    【讨论】:

    • 你好尤瓦尔。感谢您的极快响应!!!你的回答者工作了一个款待!我最初确实在等待单元测试,但我必须将返回类型设置为 Task return true。尽管它起作用了,但这似乎有点混乱。我也确实使用了一个断言来测试写入,但为了清楚起见,将其从我的示例中省略了。你的回答很有道理!而且我想真的只适用于期望返回某种描述的单元测试,因为从单元测试外部调用该方法时一切正常。再次感谢奈杰尔
    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多