DotNet Core Xunit总是可以使用

时间:2018-12-10 13:11:28

标签: c# asp.net-core .net-core asp.net-core-mvc xunit

当我通过邮递员调用api时,数据已成功插入mongodb中。但是我正在运行xunit测试类,它显示mongodb null异常。为什么我遇到这个问题。以下是我的测试类和项目源代码。

XUnit

    [Fact]
    public async void Test1()
    {
        JObject jObject = new JObject();
        jObject.Add("name", "Satheesh");
        jObject.Add("email", "sat@sat.com");

        JObject finaljObject = new JObject();
        finaljObject.Add("data", jObject);

        Console.WriteLine("************ "+finaljObject);
        var content = JsonConvert.SerializeObject(finaljObject);
        var stringContent = new StringContent(content, Encoding.UTF8, "application/json");

        // Act
        var response = await _client.PostAsync("/api/Values/User", stringContent);

        // Assert
        var result = await response.Content.ReadAsStringAsync();
        var responseString = await response.Content.ReadAsStringAsync();
        Assert.Contains("Data Successfully Retrived", responseString);
    }

项目源

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        private readonly IMongoDatabase _database = null;
        // GET api/values


        public ValuesController(IOptions<Settings> settings)
        {
            try
            {
                var client = new MongoClient(settings.Value.ConnectionString);
                if (client != null)
                    _database = client.GetDatabase(settings.Value.Database);
            }
            catch(MongoException e)
            {
                Console.WriteLine("DB Connection Error "+e.StackTrace);
            }
        }


        [HttpPost]
        [Route("User")]
        public async Task <dynamic> RegisterUser([FromBody] JObject value)
        {
            //User Registeration
            BsonDocument ReturnData = new BsonDocument();
            try
            {
                dynamic jObject = JObject.FromObject(value);
                dynamic data = jObject.data;
                BsonDocument Document = BsonDocument.Parse(data.ToString());
                _database.GetCollection<BsonDocument>("User").InsertOne(Document);
                if(Document["_id"].AsObjectId != null)
                {                    
                    return ReturnData.Add("message","Successfully Inserted").Add("Success",1).Add("data",Document["_id"].AsObjectId).ToJson();
                }
                else
                {
                    return ReturnData.Add("message","Error During Insert Document").Add("Success",0).ToJson();
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.StackTrace);
                return ReturnData.Add("message","Error").Add("Success",e.StackTrace).ToJson();
            }
        }
   }

错误:

 DB Connection Error    at MongoDB.Driver.Core.Misc.Ensure.IsNotNull[T](T value, String paramName)
   at MongoDB.Driver.Core.Configuration.ConnectionString..ctor(String connectionString)
   at MongoDB.Driver.MongoUrlBuilder.Parse(String url)
   at MongoDB.Driver.MongoUrl..ctor(String url)
   at MongoDB.Driver.MongoClient..ctor(String connectionString)
   at test3.Controllers.ValuesController..ctor(IOptions`1 settings)

如何解决此问题。任何人都可以帮助我。

谢谢...

1 个答案:

答案 0 :(得分:1)

我想原因是您的Test Project没有配置Settings选项。

在主项目的Startup中(我们将其称为App Project),您可以通过以下方式配置该选项:

services.Configure<Settings>(Configuration) 

Startup本身不会加载appsettings.jsonHostBuilder将其加载,然后将Configuration注入到Startup中。

让我们回顾一下您的测试项目:

private readonly HttpClient _client; 
public UnitTest1() { 
    _server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
    _client = _server.CreateClient(); 
}

测试项目根本没有为Configuration设置TestServer

要解决此错误,您需要在测试项目中为Configuration构建WebHostBuilder

    var configuration = new ConfigurationBuilder()
         // ... load the config file manually  
         //   , or copy your appsettings.json file to the test project
         //   , and custom it as you like
        .SetBasePath("path/to/your/App/proj")    
        .AddJsonFile("appsettings.json")
        .Build();

    var builder = new WebHostBuilder()
        .UseConfiguration(configuration)
        .UseStartup<App.Startup>();

    var server = new TestServer(builder);
    _client = server.CreateClient();