Search code examples
c#asp.net-mvcunit-testingxunit

Failed XUnit tests (ASP.NET Core 7 MVC)


I tried to make unit tests for my project, but I ran into the problem of missing testhost.deps.json, although it should have been installed with Microsoft.AspNetCore.Mvc.Testing. As I was told the error may be related to shadow copy, but no matter what I tried to do the error is still displayed just during the creation of the client.

How do I fix this error? Thank you in advance for your answer.

System.InvalidOperationException : Can't find 'C:\Users\flybe\OneDrive\Desktop\HomeworkProject\HomeworkTest\bin\Debug\net7.0\testhost.deps.json'.

using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.VisualStudio.TestPlatform.TestHost;

namespace HomeworkTest
{
    public class UnitTest1 :IClassFixture<WebApplicationFactory<Program>>
    {
        private readonly WebApplicationFactory<Program> _factory;

        public UnitTest1(WebApplicationFactory<Program> factory)
        {
            _factory = factory;
        }

        [Fact]
        public void Test1()
        {
            var client = _factory.CreateClient();
        }
    }
}

I tried to repeat what was in the training video. I also tried doing a test according to the documentation and the JetBrains article, where this problem was solved with ReSharper, but nothing helped.


Solution

  • Make sure testhost.deps.json file exists in the bin folder. if it's missing make sure you have

    <PreserveCompilationContext>true</PreserveCompilationContext>
    

    in your .csproj file.

    and if that's not work try to remove the below line from your code.

    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>