1

I followed the tutorial here but it seems like the start up file does not recognize the appsetting.json file.

So when I run the actual project, the Iconfiguration have 7 properties. enter image description here

But when I run the test, it only has one property. enter image description here

So I was thinking maybe I missed something in the test method to configure the AppSetting.json file..

Here's my test method:

  public class StudentServiceRequestsTest
    {
        private readonly TestServer _server;
        private readonly HttpClient _client;

        public IndividualServiceRequestsTest()
        {
            // Arrange
            _server = new TestServer(new WebHostBuilder()
                .UseStartup<Startup>());
            _client = _server.CreateClient();
        }
        [Fact]
        public async Task GetStudentsByDeptShould()
        {
            try
            {
                //Act
                var response = await _client.GetAsync("/api/department/200/students");
                response.EnsureSuccessStatusCode();

                var responseString = await response.Content.ReadAsStringAsync();

                //Assert
                Assert.Equal("hi", responseString);
            }
            catch (Exception e)
            {
                throw;
            }

        }

Here's my startup class, apprently I added the json file which includes all the keys and secrets required in the Web API.

namespace CIS.API.Student
{
    public class Startup
    {

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }


        public IConfiguration Configuration { get; set; }
            services.AddSingleton(Configuration);
            services.AddMvc();
        }


        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(x => x
                 .AllowAnyOrigin()
                 .AllowAnyMethod()
                 .AllowAnyHeader()
                 .AllowCredentials());

            app.UseMvc();

        }
    }
}

Anyone knows why it would happen?

superninja
  • 3,114
  • 7
  • 30
  • 63
  • 1
    Have you created a file link of your project's configuration file into the test project? – Jonathon Chase Apr 23 '18 at 23:26
  • @JonathonChase no i didn't. I will do that and see if it works. Thanks! – superninja Apr 23 '18 at 23:27
  • 1
    You may also find [this post helpful](https://stackoverflow.com/questions/41382978/appsettings-json-for-integration-test-in-asp-net-core), particularly the link in the answered question to [this page](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-2.1). Pretty deep down in the Integration Testing section it shows examples of using the `WebHostBuilder`'s `UseContentRoot`. – Jonathon Chase Apr 23 '18 at 23:38
  • @JonathonChase I am still trying to understand how the TestFixture class do. How can it fix the issue of not having appsetting.json? – superninja Apr 24 '18 at 06:06
  • 1
    In your constructor, you build the test server with `_server = new TestServer(new WebHostBuilder().UseStartup());`. I'm assuming your tests are in a different project. ASP.NET is looking for appsettings relative to the location of the running assembly. In the case of a test project, this will likely be in a location that the appsettings.json does not exist, as it wasn't copied on build. – Jonathon Chase Apr 24 '18 at 16:34

1 Answers1

5

After some research, including the tutorial: Integration tests in ASP.NET Core, I made it working.

Step 1: Copy the "appsetting.json" file to the integration test project.

Step 2: Modify the test class constructor to:

 public class StudentServiceTest 
    {
        private readonly TestServer _server;
        private readonly HttpClient _client;
        public StudentServiceTest()
        {
            var config = new ConfigurationBuilder().SetBasePath(Path.GetFullPath(@"..\..\..\..\Student.IntegrationTest"))
                                                   .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                                   .AddEnvironmentVariables();
            var builtConfig = config.Build();
            config.AddAzureKeyVault(
                    $"https://{builtConfig["Vault"]}.vault.azure.net/",
                    builtConfig["ClientId"],
                    builtConfig["ClientSecret"]);
            var Configuration = config.Build();

            _server = new TestServer(WebHost.CreateDefaultBuilder()
                .UseConfiguration(Configuration)
                .UseStartup<Startup>());
            _client = _server.CreateClient();
            _client.BaseAddress = new Uri("http://localhost:xxxxx");
        }

        [Fact]
        public async Task StudentShould()
        {
            try
            {
                //Act
                var response = await _client.GetAsync("/api/getStudentByID/200");
                response.EnsureSuccessStatusCode();

                var responseString = await response.Content.ReadAsStringAsync();

                //Assert
                Assert.Equal("bla bla", responseString);
            }
            catch (Exception e)
            {
                throw;
            }

        }
}
superninja
  • 3,114
  • 7
  • 30
  • 63