Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# unit tests and code in same folder: strip out tests from compiled binary

I have read the answers to Do you put unit tests in same project or another project? and the consensus back then (almost 10 years ago) is to put unit tests in a separate project from the code they are testing. The main reason given is to avoid non-production code from being deployed, which is fairly sound.

Things have moved on a lot since then, and at least for JavaScript based projects, having our tests next to the code is the norm, and indeed most consider it highly desirable. But I won't go into the advantages here as it's not what this question is about.

Assuming we want the same thing for C#, but still avoid deploying test code to prod, is there some post-compilation magic we can weave at the IL level to strip out the tests from the binary as part of the build process? For example could we search and destroy all classes from the binary with the [TestFixture] attribute?

Could we harness some feature of Roslyn to achieve the same?

Alternatively, is there some other approach we can take?

like image 478
Mike Chamberlain Avatar asked Oct 29 '25 11:10

Mike Chamberlain


1 Answers

One option is to use MSBuild conditions to exclude the test files from the final build.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>netstandard2.0</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup>
    <Compile Condition=" '$(Configuration)' == 'Release' " Remove="Test\**\*.cs" />
  </ItemGroup>

</Project>

This could all be done with a single statement using globs, which is simpler than having to put an #if DEBUG statement in every single test file.

Of course, that means you need to build again after you test in order to apply the conditional compilation and it effectively means the changes applied in Release mode are untested. Since floating point rounding errors and other compiler optimizations aren't tested, you may miss something important in your tests.

NOTE: Unlike what the case may be in JavaScript, it is highly desirable in .NET to separate the test code from the production code so you don't have to re-compile before deployment, effectively negating any testing you may have done.

like image 138
NightOwl888 Avatar answered Nov 01 '25 01:11

NightOwl888



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!