Интегрированное модульное тестирование не выполняется в ядре ASP.NET MVC / Web API - PullRequest
0 голосов
/ 16 сентября 2018

Я занимаюсь разработкой веб-API с использованием ядра ASP.Net. Я делаю комплексное тестирование моего проекта. Я перехожу по этой ссылке, https://koukia.ca/integration-testing-in-asp-net-core-2-0-51d14ede3968. Это мой код.

У меня есть контроллер для тестирования в проекте thegoodyard.api.

namespace thegoodyard.api.Controllers
{
   [Produces("application/json")]
   [Route("api/category")]
   public class CategoryController: Controller
   {
      [HttpGet("details/{id}")]
      public string GetCategory(int id = 0)
      {
         return "This is the message: " + id.ToString();
      }
   }
}

Я добавил новый проект модульного тестирования под названием thegoodyard.tests к решению. Я добавил класс TestServerFixture со следующим определением

namespace thegoodyard.tests
{
    public class TestServerFixture : IDisposable
    {
      private readonly TestServer _testServer;
      public HttpClient Client { get; }

      public TestServerFixture()
      {
         var builder = new WebHostBuilder()
                .UseContentRoot(GetContentRootPath())
                .UseEnvironment("Development")
                .UseStartup<Startup>();  // Uses Start up class from your API Host project to configure the test server

         _testServer = new TestServer(builder);
         Client = _testServer.CreateClient();
      }

      private string GetContentRootPath()
      {
         var testProjectPath = PlatformServices.Default.Application.ApplicationBasePath;
         var relativePathToHostProject = @"..\..\..\..\..\..\thegoodyard.api";
         return Path.Combine(testProjectPath, relativePathToHostProject);
      }

      public void Dispose()
      {
         Client.Dispose();
         _testServer.Dispose();
      }
   }
}

Затем снова в тестовом проекте я создал новый класс CategoryControllerTests со следующим определением.

namespace thegoodyard.tests
{
    public class CategoryControllerTests: IClassFixture<TestServerFixture>
   {
      private readonly TestServerFixture _fixture;

      public CategoryControllerTests(TestServerFixture fixture)
      {
         _fixture = fixture;
      }

      [Fact]
      public async Task GetCategoryDetai()
      {
         var response = await _fixture.Client.GetAsync("api/category/details/3");

         response.EnsureSuccessStatusCode();

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

         bool containMessage = false; //responseString.Contains("This is the message: 3"); - I commented on purpose to make the test fails.
         Assert.True(containMessage);
      }
   }
}

Тогда я сразу выбрал метод теста и нажал «Запустить тесты» в опции, чтобы запустить тест. Но ни один из тестов не был запущен. Это выход. enter image description here

Чего не хватает в моем коде? Как мне запустить интегрированный тест?

Ответы [ 3 ]

0 голосов
/ 17 сентября 2018

Возможно, есть ошибка сборки, препятствующая компиляции проекта.Здесь действительно недостаточно информации, чтобы сказать наверняка.Перестройте свое решение и убедитесь, что ошибок нет.

Помимо этого, вы можете удалить некоторые переменные, уменьшив необходимый тестовый код.ASP.NET Core включает в себя WebApplicationFactory<TEntryPoint> прибор из коробки для начальной загрузки тестового сервера.Поэтому вы можете изменить свой тестовый код на:

public class CategoryControllerTests: IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public CategoryControllerTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task GetCategoryDetail()
    {
        var client = _factory.CreateClient();
        var response = await client.GetAsync("api/category/details/3");
        ...

См. Документацию для получения дополнительной информации и более сложных сценариев.

0 голосов
/ 17 сентября 2018

Этот способ отлично работает для интеграционных тестов на основе xUnit, которые используют конфигурацию Startup. Кодовый удар также демонстрирует, как переопределить некоторые настройки в appSetting.json для определенных значений для тестирования, а также как получить доступ к DI сервисам.

using System;
using System.Net.Http;
using MyNamespace.Web;
using MyNamespace.Services;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace MyNamespace.Tests
{
    public class TestServerDependent : IDisposable
    {
        private readonly TestServerFixture _fixture;
        public TestServer TestServer => _fixture.Server;
        public HttpClient Client => _fixture.Client;

        public TestServerDependent()
        {
            _fixture = new TestServerFixture();

            var myService = GetService<IMyService>();
            // myService.PerformAnyPreparationsForTests();
        }

        protected TService GetService<TService>()
            where TService : class
        {
            return _fixture.GetService<TService>();
        }

        public void Dispose()
        {
            _fixture?.Dispose();
        }
    }

    public class TestServerFixture : IDisposable
    {
        public TestServer Server { get; }
        public HttpClient Client { get; }

        public TestServerFixture()
        {
            var hostBuilder = WebHost.CreateDefaultBuilder()
                .ConfigureAppConfiguration(
                    (builderContext, config) =>
                    {
                        var env = builderContext.HostingEnvironment;
                        config
                            .AddJsonFile("appsettings.json", optional: false)
                            .AddJsonFile("appsettings.Testing.json", optional: false,
                                reloadOnChange: true);
                    })
                .ConfigureLogging(
                    (hostingContext, logging) =>
                    {
                        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                        logging.AddConsole();
                        logging.AddDebug();
                    })
                .UseStartup<Startup>();

            Server = new TestServer(hostBuilder);
            Client = Server.CreateClient();
        }

        public void Dispose()
        {
            Server.Dispose();
            Client.Dispose();
        }

        public TService GetService<TService>()
            where TService : class
        {
            return Server?.Host?.Services?.GetService(typeof(TService)) as TService;
        }
    }
}

Как может выглядеть простой интеграционный тест с описанным выше:

using System.Net;
using Xunit;

namespace MyNamespace.Tests
{
    public class SimpleIntegrationTest : TestServerDependent
    {
        [Fact]
        public void RedirectToLoginPage()
        {
            var httpResponseMessage = Client.GetAsync("/").Result;

            // Smoke test to make sure you are redirected (to Login page for instance)
            Assert.Equal(HttpStatusCode.Redirect, httpResponseMessage.StatusCode);
        }
    }
}
0 голосов
/ 16 сентября 2018

Пожалуйста, проверьте следующие пакеты NuGet в вашем проекте:

Microsoft.AspNetCore.TestHost
Microsoft.NET.Test.Sdk
xunit
xunit.runner.visualstudio
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...