如何在XUnit测试项目中读取appsettings.json?

时间:2019-06-07 09:32:16

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

我正在尝试为用MVC控制器编写的方法之一编写测试用例,在该方法中,我正在读取AppSettings.json文件。如下

    public class MemberController : ControllerBase
    {
        IMemberRepository _memberRepository;
        public PayPalKeys payPal;
        public ActiveDirectory activeDirectory;
        private static GraphServiceClient _graphServiceClient;
        public MemberController(IMemberRepository member, IOptions<PayPalKeys> payPal, IOptions<ActiveDirectory> activeDirectory)
        {
            _memberRepository = member;
            this.payPal = payPal.Value;
            this.activeDirectory = activeDirectory.Value;
        }

        private IConfigurationRoot LoadAppSettings()
        {
           try{
             var config = new ConfigurationBuilder()
                .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false, true)
                .Build();
                -
                -
                -
               }
           catch(Exception ae){}
       }
    }

以下是我的测试代码

        [Fact]
        public void Payment()
        {
            var memberRepositoryManagerMock = new Mock<IMemberRepository>();     
            var members = new Members() {};
            var controller = new MemberController(memberRepositoryManagerMock.Object, GetPayPalConfigurationMock().Object, GetActiveDirectoryConfigurationMock().Object);
            var result = controller.MakePayment(members);
        }

,并且来自控制器的该方法给出异常,因为找不到配置文件'appsettings.json',它不是可选的。物理路径为“ F:\ API.Test \ bin \ Debug \ netcoreapp2.2 \ appsettings.json”。

在这里,我不了解如何在测试用例代码中模拟“ appsettings.json”部分。

1 个答案:

答案 0 :(得分:0)

右键单击Visual Studio中的设置文件,然后将“复制到输出目录”设置为“始终复制”或“从不复制”。

enter image description here

要更精确地确定文件位置,请更改您的configuration-builder来做到这一点:

var config = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", false, true)
    .Build();