在.NET CORE中,如何执行XUnit测试以检查和验证是否从AppSetting.json

时间:2019-03-14 09:53:30

标签: c# .net-core xunit

我正在使用在.NET CORE应用程序中运行的带有SendGrid Azure规范的XUnit测试。我是测试世界的新手,因此非常了解它背后的哲学。

我是EmailService类,负责执行电子邮件发送功能。

在我的第一个测试中,我想检查是否从appsetting.json文件中加载了正确的配置。

appsetting.json

 "SendGridEmailSettings": {
 "SendGrid_API_Key": "xxx",
 "SenderConfig": {
   "From": "info@myOrganization.ltd",
   "Name": "my organization"
 }
}

测试类

using Xunit;
using Xunit.Extensions;

namespace Services.Specs
{
  public class EmailServiceSpec: Specification
  {

    protected override void Observe()
    {
        var configuration = Substitute.For<IConfiguration>();
        Bag.Configuration = configuration;
    }
}

public class EmailServiceShould: EmailServiceSpec
{
    public EmailServiceShould()
    {
        Observe();
    }

    [Fact]
    public void Load_Valid_Configuration_From_AppSetting()
    {
        //var SendGrid_API_Key = Configuration["SendGridEmailSettings:SendGrid_API_Key"]; this doesn't work
    }
 }
}

电子邮件服务配置类

public interface IEmailConfig
{
     string SendGrid_API_Key { get; set; }
    SenderEmailConfig SenderConfig { get; set; }
}

电子邮件服务类别

 public interface IEmailService
{       
    Task SendEmail(EmailMultipleAudience email);
    Task SendEmail(EmailSingleAudience email);
}

public class EmailData
{
    public string Subject { get; set; }
    public string PlainTextContent { get; set; }
    public string HtmlContent { get; set; }
}

public class EmailSingleAudience: EmailData
{
    public EmailAddress To { get; set; }
}

public class EmailMultipleAudience : EmailData
{
    public List<EmailAddress> To { get; set; }
}

1 个答案:

答案 0 :(得分:2)

如果您有单独的项目,请在XUnit测试项目中复制appsettings.json(否则请跳过此步骤)。然后加载它:

var Configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();

然后您就可以使用它了。

var SendGrid_API_Key = Configuration["SendGridEmailSettings:SendGrid_API_Key"];