Profiling tests in Visual Studio Community 2015 - visual-studio

Posts on the web suggest that you can profile tests in Visual Studio by right-clicking and selecting "Profile Test": http://adamprescott.net/2012/12/12/performance-profiling-for-unit-tests/ But I only see "Run Test" and "Debug Test" for my NUnit tests, and the same for xUnit.NET. What am I missing in order to profile tests? Is this just not supported in Community edition, or I am missing some configuration or component?
(It would seem odd if it's not supported in Community, given I can profile executables in Community, and thus could painfully work around this issue by creating an executable that runs the test, and profile that. Why support profiling executables but not profiling tests?)
Steps to reproduce for NUnit: created new C# library project in Visual Studio Community 2015, pasted content of http://nunit.org/index.php?p=quickStartSource&r=2.6.4 into new file, installed NuGet packages as follows:
<packages>
<package id="NUnit" version="2.6.4" targetFramework="net452" />
<package id="NUnit.Runners" version="2.6.4" targetFramework="net452" />
<package id="NUnitTestAdapter" version="2.0.0" targetFramework="net452" />
</packages>
Even restarted Visual Studio. Tests show up in Test Explorer and can be run, but no "Profile Test" option available on right-click menu. Also tried equivalent steps for xUnit.net, but no joy.

This ishow I was able to profile an NUnit test in VS Community 2015 earlier today.
Profiling the NUnit Test Runner as an executable
Be sure you're running VS2015 as Administrator.
Click Analyze > Performance Profiler... from the Toolbar.
Choose Performance Wizard and click Start.
Page 1: In my case, I wanted to see allocations so I clicked .NET memory allocation.
Page 2: Leave the option An executable (.EXE file) checked and continue.
Page 3: On this page you have to define the executable to run.
This will be the test runner nunit3-console.exe for NUnit, or whatever the equivalent is for your test framework.
What is the full path to the executable? C:\Program Files (x86)\NUnit.org\nunit-console\nunit3-console.exe
Command-line arguments: bin\Debug\Test.dll --inprocess --test TestNamespace.TestClassName.Test_Method_Name
Working directory: \\MAC\Home\Documents\GitHub\ApplicationName\Test
You will need to substitute these paths with ones that make sense for your system. The --inprocess switch causes the tests to be run inline from the NUnit process. Without that switch, a child process is spawned and even though the profiler will appear to work, you'll just be profiling nunit3-console.exe, not your own code.
Page 4: Click Finish.
Keep in mind that the profiler will generate report files and save them to your working directory. In my case, since my working directory was a UNC share, it required me to pick a local folder path to save the reports to before the profiler would start.
A terminal window should appear briefly with the NUnit runner output in it. The window auto-closes, so if you see a flash of red text, you won't have time to read the error before it is gone. You can copy the command from Page 3 into a command prompt for more leisurely reading.
After the command runs (whether it succeeded or not), you should get a report where you can track how many allocations your test caused.
Unfortunately, allocations in a small test will probably get overshadowed by the allocations caused by the NUnit.Framework itself. I clicked around to see if there was a way to exclude them from the results, but didn't find a way to do it, so I just ignored them.
If you want to profile a different test, you can open the Performance Explorer and right-click nunit3-console.exe > Properties to change the command line arguments and then click Actions > Start Profiling to refresh the report.
Conclusion
This solution succeeds at profiling the results of a single NUnit test, but that statement comes with some caveats.
It was only marginally less obnoxious than creating a separate executable to profile, and that fact that the NUnit allocations appear in the report could make it a non-starter if you need to do some really sensitive profiling.
Maybe someone with more VS 2015 experience can help me improve this answer with some tips on how to exclude the NUnit.Framework dll from the report?

It's possible to profile MSTest tests (can also profile nunit/xunit with test adapters) using vstest.console.exe
Select executable program as the target from Analyze -> Performance Profiler
Provide the path of the vstest.console.exe (usually lives in C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow)
Provide parameters as <full path to test dll file>.dll /TestCaseFilter:"FullyQualifiedName~<namespace>.<test class>" as the parameters
If you are using nUnit or xUnit, then provide nunit test adapter,or xunit test adapter path using /TestAdapterPath argument to vstest.console.exe
More info on how to provide parameters to vstest.exe

The answer appears to be in a comment on the Adam Prescott page referenced in the question:
August 16, 2013 at 4:57 pm
Unfortunately, per MSDN, this feature is
only available in the Premium and Ultimate editions.
http://msdn.microsoft.com/en-us/library/ms182372.aspx
The link in the comment currently refers to the 2015 edition of Visual Studio. The 2010 edition of the page clearly shows which versions of Visual Studio 2010 support profiling. The pages for the 2012 and later version omit a clear statement of which versions support profiling.

Related

Unable to profile tests in Visual Studio 2013 when assembly path contains spaces

Whenever I try to profile a test in Visual Studio 2013, by Right-Clicking on the test in Test Explorer, and selecting the "Profile Test" option, the test successfully executes (and passes), but the performance analysis fails with the following messages.
File contains no data buffers
File contains no data buffers
Analysis failed
I am using Windows 7 64.
I can successfully profile the application itself (both Instrumentation and Sampling) with no problems.
So it turns out the problem is that if any of the assemblies that you hope to instrument over have spaces in their names, the "Profile Test" option fails to instrument them, which in turn means that no data is collected (because "Profile Test" appears to only use Instrumentation).
Obviously the workaround is to just not have assemblies with spaces in their names.
I logged a bug on Microsoft Connect.
Try to change the vstest processor architecture to x86 on Visual Studio.
It worked for me. I'm using VS2015.
Test > Test Settings > Default processor architecture > x86
This error can also occur when the assembly is signed with strong name key. I had this issue recently with VS2017

Unit Test Adapter threw exception: Unable to load one or more of the requested types

I am attempting to run SpecFlow tests from the Visual Studio 2010 Command Prompt, and I am getting a rather obtuse error message:
Unit Test Adapter threw exception:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information..
Some info about my VS2010 Project setup:
Windows 7 Enterprise, 64 bit (Version 6.1.7601 Service Pack 1 Build 7601)
Visual Studio 2010 Premium (v10.0.40219.1 SP1Rel)
Using Coded UI Tests
Using SpecFlow 1.9.0, which delegates to the CodedUI test API
MSTest
.NET v4.0.30319
Whole solution is compiling to 32 bit code (I have coworkers using XP still)
I have a post-build event that copies a few DLL files from my NuGet packages directory to the target dir:
copy $(SolutionDir)packages\SpecBind.1.2.1.71\lib\net45\SpecBind.dll $(TargetDir)
copy $(SolutionDir)packages\SpecBind.CodedUI.1.2.1.71\lib\net45\SpecBind.CodedUI.dll $(TargetDir)
Without this, mstest somehow couldn't load a number of SpecFlow assemblies.
Relevant Parts of Test Project's App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="specFlow" type="TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" />
<section name="specBind" type="SpecBind.Configuration.ConfigurationSectionHandler, SpecBind" />
</configSections>
<connectionStrings>
...
</connectionStrings>
<specFlow>
<!-- For additional details on SpecFlow configuration options see http://go.specflow.org/doc-config -->
<unitTestProvider name="MsTest" generatorProvider="Specflow.CodedUI.MsTestCodedUiGeneratorProvider, Specflow.CodedUI" runtimeProvider="TechTalk.SpecFlow.UnitTestProvider.MsTest2010RuntimeProvider, TechTalk.SpecFlow" />
<stepAssemblies>
<!-- This attribute is required in order to use StepArgument Transformation as described here;
https://github.com/marcusoftnet/SpecFlow.Assist.Dynamic/wiki/Step-argument-transformations -->
<stepAssembly assembly="SpecFlow.Assist.Dynamic" />
<stepAssembly assembly="SpecBind" />
</stepAssemblies>
</specFlow>
<specBind>
<browserFactory provider="SpecBind.CodedUI.CodedUIBrowserFactory, SpecBind.CodedUI" browserType="IE" />
<!-- For additional details on SpecBind configuration options see the project site. -->
</specBind>
</configuration>
The command I was using to start the tests:
C:\path\to\bin\Debug> mstest /testcontainer:MyTests.dll /test:SpecFlowFeatureName
Loading MyTests.dll
Starting Execution...
Results Top Level Tests
-------- ------------------
Failed ...
Failed ...
Failed ...
...
I've been searching high and low for a solution, and all I keep finding is references to VS2008 and disabling Code Coverage. I have VS2010 and Code Coverage is not enabled in my local test settings.
Windows Event Log Viewer
After rooting around in my Windows Event Log viewer, I finally came across more info (I've heard people complain they can't find a stack trace with this error -- look in your Event Viewer)
The description for Event ID 0 from source VSTTExecution cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.
If the event originated on another computer, the display information had to be saved with the event.
The following information was included with the event:
(QTAgent32.exe, PID 6920, Thread 213) Unit Test Adapter threw exception: System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestExecuter.GetAssemblyInfo(Assembly assembly)
at Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestExecuter.GetTypeInfo(Type type, Boolean checkAlreadyExaminedType)
at Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestExecuter.ResolveMethods()
at Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestExecuter.Initialize(UnitTestResult result, UnitTestRunner runner, ConsoleOutputRedirector redirector)
at Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestRunner.Run(UnitTestElement test, ITestContext testContext, Boolean isLoadTest, Boolean useMultipleCpus)
the message resource is present but the message is not found in the string/message table
I don't know how to resolve this error. SpecFlow tests run fine from inside Visual Studio when I right-click in a .feature file loaded in the editor and choose "Run SpecFlow Scenarios..." but I can't run them from the command line.
Any ideas, or additional information I could post?
As a side note, this stemmed from my earlier question: How do you run SpecFlow scenarios from the command line using MSTest?
Update #1
I did a little more poking around, and found this blog post: MSTest and 64bit. I checked my local test settings, and it is forcing the tests to run in 32 bit.
Now using this command:
mstest /testcontainer:MyTests.dll /testsettings:"..\..\..\Local.testsettings"
Error message:
Test method Blah.Dee.Blah threw exception:
System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.TestTools.UITest.Extension, Version=11.0.0.0, Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
TestCleanup method Blah.Dee.Blah.ScenarioTearDown threw exception. BoDi.ObjectContainerException: BoDi.ObjectContainerException: Interface cannot be resolved: SpecBind.BrowserSupport.IBrowser.
Update #2
I removed the reference to Microsoft.VisualStudio.TestTools.UITest.Extension and added it back. Cleaned. Rebuilt. Ran the same command again. Still getting the same error.
For some reason it's trying to load the Microsoft.VisualStudio.TestTools.UITest.Extension assembly as Version 11, and I have Version 10 installed on my machine. I'm trying to track down where this version is being specified so I can change it.
Just in case anyone else comes across this, for me it was because code coverage was enabled. Disabling it resolved the issue:
http://blogs.msdn.com/b/danielvl/archive/2010/02/16/enable-code-coverage-in-visual-studio.aspx
Open the .testsettings file
Under "Test Settings", click "Data and Diagnostics"
Uncheck "Code Coverage"
Hit "Apply"
With the help of #jessehouwing's comment above, I've got this fixed. I was running into two problems.
The error I originally referenced was actually caused by mstest attempting to run the tests in a 64bit process (QTAgent.exe). I needed it to run as a 32 bit process because the project was compiled as 32 bit code on my 64 bit Windows 7 machine.
In Visual Studio 2010:
Click the "Test" menu -> "Edit Test Settings" -> "Local (local.testsettings)"
Click "Hosts" in the left hand panel
Make sure "Force tests to run in 32 bit process" is chosen in the "Run tests in 32 bit or 64 bit process" drop down. For me this was the default
In the Visual Studio Command Prompt, run the tests by referencing the local.testsettings file generated by Visual Studio:
mstest /testcontainer:foo.dll /testsettings:"path/to/solution/local.testsettings" /test:SpecFlowFeatureName
The second problem I had was my own fault. Earlier I was playing around with Coded UI tests and SpecFlow and had installed SpecBind, which threw a bunch of settings in App.config for my test project. This NuGet package is only for .NET 4.5, and we use .NET 4.0. I removed that NuGet package and settings from App.config, cleaned and rebuilt. This fixed this issue completely.
So in short, I:
Forced mstest to run in a 32 bit process, and referenced this local.testsettings file from the command line
Removed all references to SpecBind because I got a little NuGet-happy earlier and installed a package incompatible with my .NET runtime.
As you can see by looking at the assembly references required by these packages (I use Reflector for this, but IlSpy or JetBrains' DotPeek will work as well), you'll see that they depend on the v11 version, which is the version that ships with Visual Studio 2012. These can't be used in Visual Studio 2010.
Removing SpecBind will probably help, or finding a version that depends on an older version of CodedUI (you're probably looking for a much older version of SpecBind in this case).
As for your 32-bit issue, you should probably set your project's CPU configuration to AnyCPU, there is normally no need to fix it to x86, unless you're dependent on native methods or if you're referencing other assemblies that are specifically set to use x86 as their target architecture.
This is so troubling.....
I had Test Agent for Visual Studio 2015 installed on my test machine, since we were planning to use it - while on my local machine I had 2013. The tests ran so perfectly with MsBuild on local, that I couldn't understand what could have happened given that I always assumed Microsoft always maintained backward compatability.
MsBuild on test server failed to give any information as to what assemblies were missing (I added Newtonsoft.Json just because it complained initially, but after that I never saw the names of anything else missing). The error message was truncated, stacktrace and debugtrace options never worked...
Once I installed Test Agent for Visual Studio 2013 on the test machine, it ran like a charm.

Can't debug NUnit tests with Visual Studio

Trying to debug an NUnit test in VS2010 and is not stopping on the breakpoint. It was working the last time I tried need to debug the test (maybe 1 yr ago) but now it doesn't work.
I've tried the following:
How to debug with vs.net 2008 and nunit?
http://erraticdev.blogspot.com/2012/01/running-or-debugging-nunit-tests-from.html
I've tried attaching, rechecking my installation, updated the config file so it's using the 4.0 runtime, still doesn't hit the breakpoint.
What am I missing?
You can debug nunit tests in VS studio community version only. For this you need to install Nunit3testAdpter. You can add this in Tools -> Extension and updates. or from Nuget packages.
This is a long overdue question but I haven't seen the solution to debug NUnit tests directly within Visual Studio. This is quite easily possible and without any third party tools. All you have to do is configure your test project (which is just a plain old Class library project) so it will start NUnit test runner whenever you hit F5 or Ctrl-F5 (just run, no debugging).
Particularly you will have to configure your project properties to start an external program:
Step by step configuration is very well described in this blog post. It advises you to use NuGet to obtain NUnit test runner and configure project to execute the runner when you try running your library project. As simple as that. Using no specific tools which are usually not free.
There are multiple reasons why this may happen. If your application's target framework is different from NUnit's, then you won't be able to debug, because the tests are actually being run by nunit-agent.exe.
For me, my application was using 4.5, but NUnit's was using 3.5. (You can find this from one of the NUnit GUI applications -> Help -> About)
To fix this, change the nunit.exe.config file to include the following, inside the configuration section:
<startup>
<requiredRuntime version="4.0.30319" />
</startup>
This can also happen when your PDB generation is set to embedded. Switching it to full will allow the nunit test adapter to start with the debugger attached. At that point it can be switched back to embedded and it will debug again.
The setting is on the project properties pages, in the Build tab, then click the Advanced button. I always choose "All Configurations" at the top, so I make sure I'm emitting a useful PDB (or embedding the info) when building Release configuration assemblies too.
The other day I failed to hit a breakpoint in my NUnit debugging. It took me a while to realize that someone had copy/pasted the test into a different file and I was running a different test than the one that the breakpoint was in.
I recently had a similar problem. Changing the project's platform to AnyCPU solved it for me. Also worth checking:
1) Check NUnit's latest version (I was using 2.5.7, updated to 2.6.2)
2) The Target Framework for your test project. I was using .NET 4.0 (you can find it under Properties -> Application, on VS2010)
At least up to vs2010 the debugger can only debug 32 bit apps but not 64 bit apps.
With vs2010 I am using a 32bit nunit.exe version and use "attach to debugger". This workes well for me.
Please upgrade NUnit Test Extension and close the Visual studio so Visx (probably spell) will run and update NUnit tool.
After this you can open your project and run NUnit test project.
It will run.
I tested accurately.
Try changing the test to x64. From the menu do
Test -> Test Settings -> Default Processor Architecture -> x64.
i think u cant debug with Visual studio. better u install TestDriven.NET.
then
Put the BreakPoint on the test method
Right click on the test
method.
select TestWith->Debugger

BDD with Machine.Specifications in Visual Studio 2010

I'm beginning to get the grips of BDD and MSpec, but I'm still really bugged by the fact that I'm unable to debug my tests/specs, and that I have to leave the IDE to go to a html report file to see the results.
Currently, I have a post build event configured to run mspec.exe $(TargetFileName) --html “$(ProjectDir)Report.html”, but there must be some better way to do this.
Does anyone know any good add-ins, test runners or whatever that will let me
debug tests, instead of just running them
show the test results in a nice way inside Visual Studio
(Footnote: I'm running VS2010 Professional on Windows 7, if that matters.)
There are basically three options you have:
You can set up a custom tool in
Tools | External Tools to start
mspec.exe with the current project's
assembly to run the contexts and
generate the HTML report.
Install TestDriven.Net and
ensure that
Machine.Specifications.dll.tdnet
and
Machine.Specifications.TDNetRunner.dll
are in your project's copy of MSpec.
You can then run and debug your
contexts from the context menu: "Run
Tests", "Run With | Debugger" without further installation.
There's an example of what the MSpec folder
looks like for all of my projects.
If you use ReSharper 4.1, 4.5, 5.0
or the latest 5.1 EAP (== beta)
there are runners for each of these
versions.
The ZIP download
contains batch files that install
the runner for each respective
version of ReSharper. ReSharper's
unit test support is pretty
extensive in terms of UI
widgets/shortcut support, the reporting
tree view and debugging.
If you're
a dotTrace user you can also profile
right from within Visual Studio.
dotCover (another JetBrains product)
allows you to calcualate code
coverage results from your MSpec
runs.
On top of that, you get
all the nice coding and navigation features that ReSharper provides.
Be aware that only the first option will generate the HTML report as both the TestDriven.Net and ReSharper runners do not support HTML report generation. From my point of view this isn't an issue since the TD.Net and ReSharper runners offer fairly complete reporting mechanisms through the Visual Studio UI.
Another option that might work (I haven't used it myself) is to leverage the Gallio support that MSpec has. Gallio is a runner/framework for several testing frameworks; it might as well support debug runs with MSpec. Contact #smaclell if you have questions about Gallio support.

NUnit tests in a separate project, same solution

I have a solution containing my main project and a test project using NUnit. Everything compiles but when I run NUnit I get the exception below after the tests load, and the tests fail. I've added the main project as a reference, and I have $(ProjectDir)bin/Debug/$(TargetName)$(TargetExt) in the arguments for NUnit in the external tools setup, with a blank initial directory.
MyMainProjectTests.Database.TestAddDelete:
System.BadImageFormatException : Could not load file or assembly 'MyMainProject,
Version=1.1.1.0, Culture=neutral, PublicKeyToken=null' or one of its
dependencies. An attempt was made to load a program with an incorrect format.
TearDown : System.Reflection.TargetInvocationException : Exception has been
thrown by the target of an invocation.
----> System.BadImageFormatException : Could not load file or assembly
'ChickenPing, Version=1.1.1.0, Culture=neutral, PublicKeyToken=null' or one
of its dependencies. An attempt was made to load a program with an incorrect
format.
After scouring for hours the only thing I've found is a bug in VS2005 which mentions the /bin and /obj directories, but the answer provided didn't help.
Any solutions?
Instead of setting up NUnit as an External Tool, I set the unit test project as the StartUp project. In the project's Properties screen, set the Start Action to "Start external program" and point it to nunit.exe. In the Start Options section, I specify the test assembly (no path necessary) in the "Command line arguments" box. At this point, simply press F5 to start up NUnit.
Use the nunit-x86.exe instead of nunit.exe as your runner.
A better longer term solution may be to buy ReSharper that includes a much nicer test runner for NUnit that fully integrates into Visual Studio. It auto detects your .NET project type (x68 or x64). ReShaper comes with tons of other features of which unit testing is just one. Their test runner also integrates with their DotCover code coverage analyser.
You may find that you'll need a later version of Visual Studio to use ReSharper. The latest version works with Visual Studio 2013 Community Edition that you can get for free though I understand you may have issues upgrading some project features from such a rather old VS2005 project.
I don't have any affiliation with ReSharper.
Are you running on x64? You will get that error if loading a x64 bit from x86 and vise versa. Also, the path you are trying to create should be the $(TargetPath) macro.
Just set "Platform target" of Tests project to "x86".
Is your main project a .exe or a .dll? Older versions of .NET couldn't reference an .exe, so that might be the problem.
In either case, I'd expect problems if the main assembly didn't end up somewhere accessible by your test assembly (for example, in the same directory). You could check that, and if not make it so, perhaps by having Visual Studio copy the referenced (main) assembly to the local directory.
The "An attempt was made to load a program with an incorrect format." makes me wonder if the "missing assembly" theory is right, but without more info, it's the best guess I can think of.
Go the the NUnit install (example: C:\Program Files (x86)\NUnit 2.6.3\bin) location and open nunit-86.exe.

Resources