How to debug / unit test webAPi in one solution

Is there a way to unit test or debug web api in one vs solution? I consume WebAPI using HttpClient and have two VS instances for this.

in 1 instance of VS I have unit test, in the second instance of vs I have webapi working in localhost.

Is there a better way to do this?

Is unit test referencing a WebAPI project the preferred way?

I want to use it with httpClient and not reference it in the UnitTest project.

so in my UnitTest method it will have baseAddress from http: // localhost: 1234 "

WebAPI will be hosted here if it is launched from the same solution.

In the current method that I am debugging, I need to start a second instance of Visual Studio with the same loaded solution and start the WebAPI project, and another Visual Studio starts the unit test project.

+10
c # unit-testing visual-studio asp.net-web-api2
source share
7 answers
  • Start Debugging Unit Test
  • On the first line of your test code or before calling your local api web project
  • Right click on your api web project and debug> Start a new instance
+6
source share

As stated by Daniel Mann, this is not unit testing. This is integration testing. You start the whole project and check everything.

If you want to use unit test your webapi controllers, simply add the unit test project to your webapi project and create unit tests. You want to focus on testing only one class at a time. Mock / Fake any dependencies of this class.

Here is a good example from Microsoft http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-with-aspnet-web-api

but if what you are looking for runs a test that you have in one solution. Just put both projects in the same solution. Right-click on a solution in the solution explorer. Select Set StartUp Projects. select "multiple launch projects" and at the same time select the projects you want to run.

+4
source share

So, a colleague and I just tried the suggested answers to no avail. However, we did find a solution for this that works well by joining the IIS process when you are in debug mode in your test. Here are the steps:

  • Ensure that your test project and Web API project are in the same solution.
  • Make sure that your solution is configured for one run in the properties section (i.e. leave it by default).
  • Add a breakpoint to the endpoint in the controller method that you want to debug.
  • Add the breakpoint in your test that you want to debug, and then right-click and click on "Debug Tests" (or use your favorite test runner, like ReSharper for debugging).
  • As soon as your capture point hits, click "Debug" | Join the process ...
  • Locate and click on the local IIS process for this service, then click "Attach"
  • Continue debugging and see how your breakpoint hits your service

For added simplicity, we downloaded the extension for joining IIS, which automatically provided us with a menu in the Tools menu.

For superior ease, we've customized the toolbar section to add a menu command to the toolbar to attach one simple click to IIS.

+4
source share

You can host the web api yourself, as Mike mentioned,

var config = new HttpSelfHostConfiguration("http://localhost:8080"); config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); using (HttpSelfHostServer server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Press Enter to quit."); Console.ReadLine(); } 

for more details, http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api

you can start hosting when you initialize your unit test package and turn it off while cleaning up the test suite.

+1
source share

If you have an API project and you have created an end-to-end unit test project for the API (this means that you are testing the API directly using HttpClient, WebClient, or other http client wrappers), you need to enable the "Multiple Launch Projects" for the solution. Follow these steps:

  • Right-click the solution file and select properties.
  • Select the Multiple Running Projects radio button.
  • Select the "Start" action from the drop-down list for the web api project and unit test project.
  • F5 to run in debug mode.
  • A dialog box appears with the message "The project with the class library of the output type cannot be started directly." This is great, since the unit test project is just a class library (not an executable, so there is no main / start way). Just click OK.
  • In the unit test you want to test, right-click and select "Debug Unit Tests" to start debugging.
0
source share

In the current version of ASP.Net Core, the official solution is to use the Microsoft.AspNetCore.TestHost Nuget assembly, which creates a simulated web server that hosts the web project in the test project.

Details on use can be found here: https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testing

On the one hand, this seems like a little fiction, because by what definition it is genuine integration testing if a real web server is not involved, on the other hand, it at least works quite easily as soon as you configure it.

0
source share

I tried selft hosting but i was having some problems 1.

 HttpContext.Current is null 
  1. I have a custom error handler in the web API and do not work in self-hosted ones

IisExpress solution works very well for me

bat file for deployment in iis

 @Echo off set msBuildDir=C:\Program Files (x86)\MSBuild\14.0\Bin ::compile web api project call "%msBuildDir%\msbuild.exe" solutionFilePath.sln /t:projectName /p:Configuration=Debug;TargetFrameworkVersion=v4.5 /l:FileLogger,Microsoft.Build.Engine;logfile=Manual_MSBuild_ReleaseVersion_LOG.log /p:Platform="Any CPU" /p:BuildProjectReferences=false call "C:\Program Files (x86)\IIS Express\iisexpress.exe" /path:"pathToRootOfApiProject" /port:8888 /trace:error 

I work with Nunit frameWork

  [SetUpFixture] public class SetUpTest { private Process process = null; private Process IisProcess = null; private System.IO.StreamWriter sw = null; string programsFilePath = Environment.GetEnvironmentVariable(@"PROGRAMFILES(X86)"); [OneTimeSetUp] public void Initialize() { //compile web api project List<string> commands = new List<string>(); commands.Add( $@ "CD {programsFilePath}\MSBuild\14.0\Bin\"); commands.Add( $@ "msbuild ""pathToYourSolution.sln"" /t:ProjrctName /p:Configuration=Debug;TargetFrameworkVersion=v4.5 /p:Platform=""Any CPU"" /p:BuildProjectReferences=false /p:VSToolsPath=""{programsFilePath}\MSBuild\Microsoft\VisualStudio\v14.0"""); RunCommands(commands); //deploy to iis express RunIis(); } [OneTimeTearDown] public void OneTimeTearDown() { if (IisProcess.HasExited == false) { IisProcess.Kill(); } } void RunCommands(List<string> cmds, string workingDirectory = "") { if (process == null) { InitializeCmd(workingDirectory); sw = process.StandardInput; } foreach (var cmd in cmds) { sw.WriteLine(cmd); } } void InitializeCmd(string workingDirectory = "") { process = new Process(); var psi = new ProcessStartInfo(); psi.FileName = "cmd.exe"; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.UseShellExecute = false; psi.WorkingDirectory = workingDirectory; process.StartInfo = psi; process.Start(); process.OutputDataReceived += (sender, e) => { Debug.WriteLine($"cmd output: {e.Data}"); }; process.ErrorDataReceived += (sender, e) => { Debug.WriteLine($"cmd output: {e.Data}"); throw new Exception(e.Data); }; process.BeginOutputReadLine(); process.BeginErrorReadLine(); } void RunIis() { string _port = System.Configuration.ConfigurationManager.AppSettings["requiredPort"]; if (_port == 0) { throw new Exception("no value by config setting for 'requiredPort'"); } IisProcess = new Process(); var psi = new ProcessStartInfo(); psi.FileName = $@ "{programsFilePath}\IIS Express\iisexpress.exe"; psi.Arguments = $@ "/path:""pathToRootOfApiProject"" /port:{_port} /trace:error"; psi.RedirectStandardInput = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.UseShellExecute = false; IisProcess.StartInfo = psi; IisProcess.Start(); IisProcess.OutputDataReceived += (sender, e) => { Debug.WriteLine($"cmd output: {e.Data}"); }; IisProcess.ErrorDataReceived += (sender, e) => { Debug.WriteLine($"cmd output: {e.Data}"); if (e.Data != null) { throw new Exception(e.Data); } }; IisProcess.BeginOutputReadLine(); IisProcess.BeginErrorReadLine(); } } 

attach to iisexpress

Then run a debug test, then go to "Debug"> "Attach to Process"> in the application to select enter image description here click "OK",

search iisexpress and click attach

0
source share

All Articles