Search code examples
c#visual-studionugetprojects-and-solutions

Importing NuGet references through a local project reference


Let's say I have a "main" C# project that uses NuGet to manage its third-party dependencies.

Now let's say I create a unit-testing project alongside the main project that includes the main project as a reference.

Unfortunately, it seems that I need to re-add dependencies that are included via nuget in the main project in order to use them to write code for the unit tests in the unit test project.

My question is: Is there a way to automatically include the "main" nuget references in the testing project?


Solution

  • it seems that I need to re-add dependencies that are included via nuget in the main project in order to use them to write code for the unit tests in the unit test project.

    That because Visual Studio / MSBuild tries to be smart and only bring references over into project unit-testing that it detects as being required by project "main". It does this to avoid indirect reference pollution in project unit-testing. You can refer the accepted answer for more detail.

    My question is: Is there a way to automatically include the "main" nuget references in the testing project?

    The simple answer is yes, but not sure whether this method is effective for you. I post it here, hope it can give you some help.

    You can copy the package list which you want to add to UI-testing from package.config in the "main" project to the package.config in the UI-testing project, like:

      <package id="EntityFramework" version="6.1.3" targetFramework="net452" />
      <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net452" />
      <package id="NUnit" version="3.7.1" targetFramework="net452" />
    

    Then nuget will restore those packages when you build the UI-testing, what you need to do is use the NuGet command line in the Package Manager Console:

    Update-Package -Reinstall -ProjectName [name of your target project]
    

    to force reinstall the package references into UI-testing project.