首页 > 解决方案 > NetCore 2.1 TestServer 返回 500 内部服务器错误

问题描述

我正在尝试为我的 API 编写集成测试,并且我正在尝试在 .netCore 上使用 TestServer 并使用 xunit。

但我总是从请求中得到 500 错误。我还尝试请求在线测试链接(https://jsonplaceholder.typicode.com/users),但即使这样我也得到了 500。

顺便说一句,当我运行我的 api 并检查我要测试的方法是否达到 200 并且运行良好时。

这是我得到的所有信息。


测试名称:RepoCore.TEST.IntegrationTests.IntegrationTest.QueryFromEntitiyTestAsync

测试全名:RepoCore.TEST.IntegrationTests.IntegrationTest.QueryFromEntitiyTestAsync

测试源:C:\Users\Sercan\source\repos\RepoCore.API\RepoCore.TEST\IntegrationTests\IntegrationTest.cs:第 0 行

测试结果:失败 测试持续时间:0:00:04,645

结果 StackTrace
在 RepoCore.TEST.IntegrationTests.IntegrationTest.QueryFromEntitiyTestAsync() --- 从先前抛出异常的位置结束堆栈跟踪---

结果消息:Assert.Equal() 失败

预期:好的

实际:InternalServerError


 public class IntegrationTest : IDisposable
 {

    private DataContext _context;
    private readonly HttpClient _client;

        public IntegrationTest()
        {
            var configuration = new ConfigurationBuilder().SetBasePath(Path.GetFullPath(@"../../../../../../")).Build();

            var server = new TestServer(new WebHostBuilder().UseStartup<Startup>().UseConfiguration(configuration));

            var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer().BuildServiceProvider();


            var builder = new DbContextOptionsBuilder<DataContext>();
            builder.UseSqlServer("Server=xyz;Database=xyz; User ID=xyz;Password=1; Trusted_Connection=True;").UseInternalServiceProvider(serviceProvider);
            _context = new DataContext(builder.Options, _logContext);
            _context.Database.Migrate();


            _client = server.CreateClient();
        }




        [Fact]
        public async Task QueryFromEntitiyTestAsync()
        {
            API.Models.Repos newrepo = new API.Models.Repos { RepoName = "TestName2", RepoAdress = "Some Street", IsActive = 1 };

            _context.Repos.Add(newrepo);
            _context.SaveChanges();


            var response = await _client.GetAsync("/api/Repo/GetRepoById?RepoId=" + newrepo.RepoID);

           //var response = await _client.GetAsync("https://jsonplaceholder.typicode.com/users");


            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        }
 }

标签: c#asp.net-coreintegration-testingxunit

解决方案


推荐阅读