Search code examples
c#.netxunit

Can XUnit tests be run from within the project to be tested?


I'm wondering if it's possible to have xUnit tests in the same project as the source code is?
I added the xUnit reference, but when I execute the tests, Visual Studio tells me that the project has no tests. I also tried to use Microsoft.NET.Test.Sdk, but in that case an error was shown because the project had two entry points.

Project explorer showing included packages

public class Test
{
    [Fact]
    public void TestMethod()
    {
    }
}

Implementation and better naming of the test will follow later...


Solution

  • To get a console App with xUnit Test compiling is a little bit tricky. One way to acheive this is to tweak the console App csproj.

    Add the following statement in PropertyGroup section:

    <GenerateProgramFile>false</GenerateProgramFile>
    

    the final csproj should look like this:

    <Project Sdk="Microsoft.NET.Sdk">
    
        <PropertyGroup>
            <OutputType>Exe</OutputType>
            <TargetFramework>net5.0</TargetFramework>
            <GenerateProgramFile>false</GenerateProgramFile>
        </PropertyGroup>
    
      <ItemGroup>
            <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
            <PackageReference Include="xunit" Version="2.4.1" />
            <PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
                <PrivateAssets>all</PrivateAssets>
                <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
            </PackageReference>
      </ItemGroup>
    
    </Project>
    

    For further reading on this subject please refer to this interesting blog post by Andrew Lock : "Program has more than one entry point defined" for console apps containing xUnit tests