Reasonable to remove TestContext from a unit test? - visual-studio

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!

Related

Prevent AOP(AspectJ) code to be triggered while running test

In my spring boot project, I am using MockMVC to test controller(web) layer. But I also have AOP(AspectJ) logic in my project, when I run unit test for controller with MockMVC, the test also triggers AOP code, how can I prevent AOP code to be triggered while running unit test for controller?
#Test
public void testMyControllerMethod() {
...
// myRequest hits an endpoint function of my controller, there is also AOP intercept the function call, how can I disable AOP to be triggered while running test?
mockMVC.perform(myRequest).andExpect(okStatus)
}
Question is in my code comment :)
I have checked this answer, I understand to use the if() expression, but I don't get TestMode.ACTIVE, there is no such thing in Spring boot. If someone could let me know how to check whether code is running unit test or not at runtime, I would know how to prevent AOP logic run as well.
What I meant in the other answer, as Simon already tried to explain to you, is something like this:
package de.scrum_master.app;
public class TestMode {
public static boolean ACTIVE = false;
}
But actually there I also listed a few other options such as environment variables and system properties. If I were you I would use one of those because in your Maven or Gradle build it would be very easy to set properties or environment variables via configuration. Your if() pointcut could access those variables.
Especially in the context of Spring there is an even simpler option: a test application configuration. Just provide a configuration without aspects to your tests. That way you can have different configurations for
production environment,
unit tests (no aspects),
integration tests (e.g. with aspects but different from unit test and production).
et cetera.
The advantage here is that you don't need any if() pointcuts or build any other knowledge about test/production environments into your aspects, which is quite ugly. My other answer only shows what you can do, it does not say it is the best solution.

What happened to TestContext in MSTest V2?

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.

How to unit test the Private Actions in MVC application?

Can we unit test the action which are having access specifier as private? If possible how can we unit test the private actions?
You can but why do you have private action methods? I'd rethink that architecture a little bit more. If you forget to make it private it becomes URL addressable.
However if you really want to do this right click on the method and add a unit test. The unit test project will add an item to the apps assemblyinfo.cs [InternalsVisibleTo] so it's private methods can be accessed via a proxy that's created in the test project.
It's a bit messy may as well pull that out into a separate class and make it public or internal etc
One option is make the action public and decorate it with NonActionAttribute.

Unit Testing While Using Entity Framework

I have a web application that has been created using MVC 3 and Entity Framework. I would like to start using unit testing, but so far I have not been able to run any unit tests due to the way the system talks to the database.
I have a BaseController, which defines a DataContext as a variable:
public class BaseController : Controller
{
public Models.MyEntities DataContext = new Models.MyEntities();
Each controller then inherits the BaseController, thereby making the DataContext variable available to all controllers without redefining it:
public class ErrorController : BaseController
{
When I run a unit test, I receive an error about the object reference not being set to an instance of an object, each time referring to the line where I access DataContext.
Most references to unit testing say you should be abstracting your database layer, and using fake data for testing. This seems counter-intuitive to me, but that is a different discussion.
My question is - is it possible to use unit testing with the system configured the way it is? I am open to using any testing framework available, either MSTest, NUnit / XUnit etc.

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