What happened to TestContext in MSTest V2? - mstest

I am running some Selenium tests and I want to take a screen shot and upload it to Azure DevOps. I am using MSTest V2 and it does not appear to set the property "TestContext" to the test context. It is always null.
I have created a property
public TestContext TestContext { get; set; }
I have tried it in my Base class, and in my inherited classes. I have tried it with a backing variable, and with out and I have tried Initializing it in a class Initialization (even though this seems wrong).
This line
Console.WriteLine($"the TestContext is null {(TestContext == null).ToString()}");
Always returns TestContext is null
It then goes on to fail (obviously).

Not sure what was wrong, but fixing it involved uninstalling the nuget packages and then reinstalling them. I tried reverting to MSTest and it started working. Then I went back to MSTest V2 and it was still working.

Related

0 Total Tests - 0 passed,0 failed ,0 skipped even after having tests in the class

While running unit test in Visual studio , i was getting 0 Total Tests - 0 passed,0 failed ,0 skipped even after having tests in the class.
In Nunit, if there is an exception in loading test setup or execution it will result in above. From Visual studio menu open debug=>output and select Test window and see are there any exceptions thrown when tests are run. In my case in project1 i have nunit2 (refernce), in project2 i have nunit3 which referred project1 which is causing conflict and unable to execute.
if you resolve the exception it should work
Check if you have runsettings file in your solution or if there is one selected under
VS -> Test -> Configure Run Settings. If this is chosen, uncheck it. Remove the file. This fixed for me.
Ensure the access modifier of the class is public instead of internal. If it is internal none of the [Fact]s in the class will register as tests within the Test Explorer, nor will they run.
Installing Microsoft.NET.Test.Sdk package from nuget package manager solved my issue.
I also have xunit and xunit.runner.visualstudio package installed.
In Case anyone is still struggling with this, installing "MSTest.TestAdapter" solved my issue.
For me a simple "Clean Solution" worked.
Here in my case the issue was different . In VS Unit tests are being identified based on Test class. In my case , there were no access modifier for the class and which caused the issue .VS unable to identify the test methods for the particular class.
class ControllerTests
{
public Controller _Controller;
[TestMethod()]
}
After adding public to the class ,it worked fine.
Public class ControllerTests
{
public Controller _Controller;
[TestMethod()]
}
For MSTest users - if you have a method marked with the [ClassInitialize] attribute, make sure that it is both public and static, and has a single parameter of type TestContext, otherwise the test file will not run.
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{​​
// initialization code...
}
For C#/.NET Playwright:
I've seen this a couple times and my issue was that the return type of an async test method was void, instead of Task. It should be as follows:
[TestMethod]
public async Task TestMethod1()
{

Wicket DropDownChoice not working after Wicket migration from 6.9.0 to 7.10.0

My unit test have been running ok before this migration process, but not after it. No code changes, no unit test changes done in my side. I did not notice any changes related to this in Wicket migration 7.x guide.
What could be the reason for failing unit tests?
In code I have:
private final DropDownChoice<ModificationSource> sourceChoice = createModificationSourceDropDown("source",
new PropertyModel<ModificationSource>(this, "selectedSource"));
private DropDownChoice<ModificationSource> createModificationSourceDropDown(final String id,
final IModel<ModificationSource> model) {
List<ModificationSource> sources = modificationSourceService.findAll();
DropDownChoice<ModificationSource> choice = new DropDownChoice<ModificationSource>(id, model, sources,
new ModificationSourceChoiceRenderer());
choice.setRequired(true);
choice.setNullValid(false);
return choice;
}
I am also adding DropDownChoice component to form:
form.add(sourceChoice);
In unit test I have:
FormTester formTester = tester.newFormTester("form");
formTester.select("source", 0);
In my unit test I get error that source has not been set. There are also same issues when using the application, so this is not unit test issue, but code issue.
Maybe there is something that has been changed in Wicket 6.x -> Wicket 7.x that makes this issue occur...? Maybe I should use DropDownChoice component differently now.
ps. I have DropDownChoice failures also in other places in the code. It seems that for e.g. selecting value from DropDownChoice elsewhere does not start data loading at all anymore after migration to 7.0 and my unit tests fail.

ServiceLocatorImplBase.cs not found

When my WebAPI controller is called from a client, I run into the following errors:
ServiceLocatorImplBase.cs not found error
An exception of type 'Microsoft.Practices.ServiceLocation.ActivationException' occurred in Microsoft.Practices.ServiceLocation.dll but was not handled in user code
The WebAPI controllers use constructor injection to inject a repository dependency which should be resolved by StructureMap IoC. Interestingly, the same code runs fine on my another development machine. Here is my stack trace. Thanks for your help.
System.ArgumentNullException was unhandled by user code
HResult=-2147467261
Message=Value cannot be null.
Parameter name: httpContext
Source=System.Web
ParamName=httpContext
StackTrace:
at System.Web.HttpContextWrapper..ctor(HttpContext httpContext)
at WebApi2.DependencyResolution.StructureMapDependencyScope.get_HttpContext() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 69
at WebApi2.DependencyResolution.StructureMapDependencyScope.get_CurrentNestedContainer() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 55
at WebApi2.DependencyResolution.StructureMapDependencyScope.DisposeNestedContainer() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 90
at WebApi2.DependencyResolution.StructureMapDependencyScope.Dispose() in c:.........\WebApi2\DependencyResolution\StructureMapDependencyScope.cs:line 85
at WebApi2.App_Start.StructuremapMvc.End() in c:.........\WebApi2\App_Start\StructuremapMvc.cs:line 44
Thanks for your reply. Both machines are running integrated mode. The error is really misleading and threw me off to a wrong track. I spent hours trying to find where this ServiceLocatorImplBase.cs resides. I happened to look into the deeply nested inner exceptions, and found that the inner most exception (5th level) complains some entities generated by POCO generator have no identity key. This is because I manually added the foreign key relationship among some entities with
public virtual RelatedEntity1 {get;set;}
public virtual RelatedEntity2 {get;set;}
without setting [key] attributes in the related entities. I am not sure if this can be fixed but the exception message should not lead people to the wrong track.
The problem you are running into is because you are attempting to resolve HttpContext at the point in time that the application is composed (typically done in the Application_Start event of Global.asax). HttpContext is part of the application's runtime state. It is null at the point in time when the application is being composed.
The reason why it seems to work in your development environment is likely because your development environment's application pool is running in classic mode. Most likely the other environments are (correctly) running in integrated mode. So, this is a design issue, not a problem with deployment as you might expect.
The solution is to use an Abstract Factory so you can defer instantiating of the HttpContextWrapper until runtime. Then you can inject the abstract factory rather than HttpContextWrapper into your services.
public interface IHttpContextFactory
{
HttpContextBase Create();
}
public class HttpContextFactory
: IHttpContextFactory
{
public HttpContextBase Create()
{
return new HttpContextWrapper(HttpContext.Current);
}
}
See this answer and this answer for a complete examples including usage.

Reasonable to remove TestContext from a unit test?

All my unit test classes have been created by Visual Studio 2008 from a built-in unit test template that includes a "TestContext" property. So far I have not used a test context and this field is upsetting Resharper and code coverage.
Is it ok to remove TestContext or would doing that indicate my unit tests are poorly structured?
If you don't need it, remove it. You can always introduce it again afterwards. I've hardly used it too...
No harm in retaining the TestContext property, particularly if your unit test class makes use of data-driven test methods. Particularly useful if you use this type of statement:
Assert.AreEqual(myValue, this.TestContext.DataRow["ExpectedValue"].ToString())
Conversely, if you're using a hand-coded test class (i.e. not one generated by the VS "Add New Item" menu option), adding a property declaration as follows gives you instant access to the record of test data as it relates to the current unit test:
public TestContext TestContext { get; set; }
Hope that helps!

MSTest & AppDomains

In some my project I notice that during executing unit tests under VSTS2008 its VSTestHost's memory consuming grows. As I have very many tests in my solution it leads to OutOfMemroyException eventually.
That looks very strange for me as I was sure that MSTest creates a new AppDomain for each unit test. Otherwise how would it reset static fields?
But if AppDomain is being created for each test than memory shouldn't leak. But it does.
So the question is: Should VS create AppDomain for each test class or not? If yes than how can I check that it does it.
I tried tracing through ProcessExpolorer and Performance snap-in. A value of "Total appdomain unloaded" is always 0 during test run.
MsTest creates one-app domain per Test assembly, unless you are using noisolation, in which case there is no AppDomain Isolation.
If you are seeing leaks, its probably a but in either your test code, or your product code. Make sure you aren't stuffing things into dictionaries and leaving them there.
I don't think the unit test engine creates a new AppDomain for each test. Since creating an AppDomain is a relatively expensive operation, doing so for each test would slow down execution of unit tests considerably!
Visual Studio 2008 uses a seperate executable called vstesthost.exe to run unit tests. VS communicates with vstesthost.exe (how it does this I don't know) to tell it what tests to run. vstesthost.exe returns the execution results to VS which displays those results.
If you are getting OutOfMemoryExceptions when running your unit tests I would say that's a strong indicator that your code under test is actually not cleaning things up. Are you sure that you aren't retaining handles to unmanaged objects/memory? I would recommend running your unit tests under a Performance Analysis (you can do that by finding the unit test under the "Test View", right-clicking on it, and selecting "Create Performance Session"). This might shed some light at least on your object allocations.
I was wrong about having separate AppDomains for each unittest.
Here's evidence:
a singleton
public class Singleton
{
public static Singleton Instance = new Singleton();
private Guid _token;
private Singleton()
{
_token = Guid.NewGuid();
}
public Guid Token
{
get { return _token; }
}
}
and two tests:
[TestClass]
public class UnitTest2
{
[TestMethod]
public void TestMethod1()
{
Console.WriteLine(Singleton.Instance.Token);
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Console.WriteLine(Singleton.Instance.Token);
}
}
During executing both tests output the same guid.
Seen the same problem with large test runs. My theory is the following. Memory exhaustion in this case is due to the fact that MSTest test result files are XML. Therefore it needs to keep all the log results in memory until the end of the test run before serializing to disk. Hurray for XML :-)
I have posted this problem as a connect issue a while back and it should have been fixed in MSTest 10 (going 64 bit) but I haven't been able to verify this yet because of all the other problems we have moving to VS2010 and .NET 4.0.
The only way to dispose of a singleton is to dispose the appDomain. A singleton is a static holding onto itself, so it's basically a circular reference. True singletons do not get disposed until the appdomain goes away.
This does not seem to be solved in MSTest 2010. I am experiencing a lot of similar issues like this. Why does garbage collection not work in unit test?
My understanding was that the UT framework took care of disposing of all executed tests, but this does not seem to be the case with some singleton patterns that we have in code.

Resources