Do you put unit tests in same project or another project?

后端 未结 15 1642
失恋的感觉
失恋的感觉 2020-12-02 05:23

Do you put unit tests in the same project for convenience or do you put them in a separate assembly?

If you put them in a separate assembly like we do, we end up wit

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 06:10

    After spending some time in TypeScript projects, where tests are often placed in a file alongside the code they are testing, I grew to prefer this approach over keeping them separate:

    • It is quicker to navigate to the test file.
    • It is easier to remember to rename the tests when you rename the class being tested.
    • It is easier to remember to move the tests when you move the class being tested.
    • It is immediately obvious if a class is missing tests.
    • You don't need to manage two duplicate file structures, one for tests and one for code.

    So when I started a new .NET Core project recently I wanted to see if it was possible to mimic this structure in a C# project without shipping the tests or test assemblies with the final release.

    Putting the following lines in the project file appears to be working well so far:

      
        
      
      
        
        
        
      
    

    The above ensures that in the Release configuration all the files named *.Tests.cs are excluded from compilation, and also that the required unit testing package references are removed.

    If you still want to be able to unit test the classes in their release configuration you can just create a new configuration derived from Release called something like ReleaseContainingTests.


    Update: After using this technique for a while I've also found it's helpful to customize your icons in VS Code to make the tests (and other things) stand out a bit more in the explorer pane:

    To do this, use the Material Icon Theme extension and add something like the following to your VS Code preferences JSON:

    "material-icon-theme.files.associations": {
      "*.Tests.cs": "test-jsx",
      "*.Mocks.cs": "merlin",
      "*.Interface.cs": "yaml",
    }
    

提交回复
热议问题