Выполните тестовое приспособление для интеграции ядра tnet, вызывающее ошибку синтаксического анализа json - PullRequest
0 голосов
/ 15 апреля 2020

Итак, я создаю шаблон API-проекта и в настоящее время работаю над добавлением некоторых интеграционных тестов.

В тот момент, когда я запускаю свой тест, по какой-то причине он возвращает ошибку разбора JSON:

Newtonsoft. Json .JsonReaderException: неожиданный символ, обнаруженный при разборе значения: A. Path '', строка 0, позиция 0.

Это похоже на то, что проблема с моей конечной точкой, но она прекрасно работает, когда я просто запускаю localhost с обычной подпрограммой запуска, так что я думаю, что это потому, что я не могу получить свой прибор правильно. особенно потому, что, когда я пытаюсь использовать другой прибор (указанный ниже), он больше не выдает ошибку и просто зависает.

Сам тест можно найти здесь .

namespace Foundation.Api.Tests.IntegrationTests
{
    using FluentAssertions;
    using Foundation.Api.Data;
    using Foundation.Api.Models;
    using Foundation.Api.Tests.Fakes;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc.Testing;
    using Microsoft.AspNetCore.TestHost;
    using Microsoft.Extensions.DependencyInjection;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using Xunit;

    public class GetValueToReplaceIntegrationTests : IClassFixture<CustomWebApplicationFactory<Startup>>
    {
        public GetValueToReplaceIntegrationTests(CustomWebApplicationFactory<Startup> factory)
        {
            _factory = factory;
        }

        private readonly CustomWebApplicationFactory<Startup> _factory;
        [Fact]
        public async Task GetValueToReplaces_ReturnsSuccessCodeAndResourceWithAccurateFields()
        {
            var fakeValueToReplaceOne = new FakeValueToReplace { }.Generate();
            var fakeValueToReplaceTwo = new FakeValueToReplace { }.Generate();

            var appFactory = _factory;
            using (var scope = appFactory.Services.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService<ValueToReplaceDbContext>();
                context.Database.EnsureCreated();

                context.ValueToReplaces.RemoveRange(context.ValueToReplaces);
                context.ValueToReplaces.AddRange(fakeValueToReplaceOne, fakeValueToReplaceTwo);
                context.SaveChanges();
            }

            var client = appFactory.CreateClient(new WebApplicationFactoryClientOptions
            {
                AllowAutoRedirect = false
            });

            var result = await client.GetAsync($"api/v1/ValueToReplaceLowers")
                .ConfigureAwait(false);
            var responseContent = await result.Content.ReadAsStringAsync()
                .ConfigureAwait(false);
            var response = JsonConvert.DeserializeObject<IEnumerable<ValueToReplaceDto>>(responseContent);

            // Assert
            result.StatusCode.Should().Be(200);
            response.Should().ContainEquivalentOf(fakeValueToReplaceOne);
            response.Should().ContainEquivalentOf(fakeValueToReplaceTwo);
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Прибор можно найти здесь .

namespace Foundation.Api.Tests
{
    using Foundation.Api.Data;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc.Testing;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;

    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder
            .ConfigureServices(services =>
            {
                // Remove the app's ValueToReplaceDbContext registration.
                var descriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                        typeof(DbContextOptions<ValueToReplaceDbContext>));

                if (descriptor != null)
                {
                    services.Remove(descriptor);
                }

                // Add ValueToReplaceDbContext using an in-memory database for testing.
                services.AddDbContext<ValueToReplaceDbContext>(options =>
                {
                    options.UseInMemoryDatabase("TestingDb");
                });

                // Build the service provider.
                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                // context (ValueToReplaceDbContext).
                using (var scope = sp.CreateScope())
                {
                    var scopedServices = scope.ServiceProvider;
                    var db = scopedServices.GetRequiredService<ValueToReplaceDbContext>();

                    // Ensure the database is created.
                    db.Database.EnsureCreated();

                    try
                    {
                        db.RemoveRange(db.ValueToReplaces);
                        // Seed the database with test data.
                        //Utilities.InitializeDbForTests(db);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            });
        }
    }
}

Я также попробовал приспособление , например, , вдохновленное этим который просто истекает.

namespace Foundation.Api.Tests
{
    using Foundation.Api.Data;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc.Testing;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.DependencyInjection;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;

    public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder
            .ConfigureServices(services =>
            {
                // Create a new service provider.
                var serviceProvider = new ServiceCollection()
                    .AddEntityFrameworkInMemoryDatabase()
                    .BuildServiceProvider();

                // Add a database context using an in-memory 
                // database for testing.
                services.AddDbContext<ValueToReplaceDbContext>(options =>
                {
                    options.UseInMemoryDatabase("InMemoryDbForTesting");
                    options.UseInternalServiceProvider(serviceProvider);
                });

                services.AddScoped(provider => provider.GetService<ValueToReplaceDbContext>());

                var sp = services.BuildServiceProvider();

                // Create a scope to obtain a reference to the database
                using var scope = sp.CreateScope();
                var scopedServices = scope.ServiceProvider;
                var context = scopedServices.GetRequiredService<ValueToReplaceDbContext>();

                // Ensure the database is created.
                context.Database.EnsureCreated();

                try
                {
                    // Seed the database with test data.
                    //Utilities.InitializeDbForTests(context);
                }
                catch (Exception ex)
                {
                    //logger.LogError(ex, "An error occurred seeding the " +
                    //                    $"database with test messages. Error: {ex.Message}");
                }
            })
                .UseEnvironment("Test");
        }
    }
}

Репо можно найти здесь .

...