Grouping Unity NUnit tests? - c#

I want to group tests like this:
To get this screenshot I used TestCases, but they don't really apply to my needs.
Obviously I don't want this:
[TestCase(TestName = "ShouldDoSomething")]
[TestCase(TestName = "ShouldDoSomethingElse")]
public void OnJoinRoom()
{ ... }
I want something like this:
[TestGroup("OnJoinRoom")]
public void ShouldDoSomething()
{ ... } 
[TestGroup("OnJoinRoom")]
public void ShouldDoSomethingElse()
{ ... } 
I don't think using subclasses is an option, as the tests are depending on a SetUp method used in the TestFixture class.

In NUnit, TestFixtures are used to group tests as well as to provide a common setup. The normal way to provide a common setup across multiple TestFixtures is to have a common base class like
public class CommonBase
{
[SetUp]
public void CommonSetUp() { }
}
[TestFixture]
public class OnJoinRoom : CommonBase { }
[TestFixture]
public class OnLeaveRoom : CommonBase { }
Notes:
Put all your tests in the derived classes
TestFixture attribute is optional, of course, but do not put it on the base class.
Base class may be abstract if you like.

Related

Use inheritance in MSTest for shared tests

I'm trying to write Unittests for D365 Plugins and CodeActivities (both being classes). There are small tests that should run in every plugin, such as:
[TestMethod]
public void NullLocalPluginContext()
{
XrmFakedContext context = new XrmFakedContext();
Assert.ThrowsException<InvalidPluginExecutionException>(
() => context.ExecutePluginWith<SomePlugin>(null));
}
Where SomePlugin is the class to be tested (which is for each child different) and cannot be abstract (awaits IPlugin). For example here it's a CheckDuplicateOrder in the child:
[TestClass]
public class CheckDuplicateOrderTest
{
[TestMethod]
public void NullLocalPluginContext()
{
XrmFakedContext context = new XrmFakedContext();
Assert.ThrowsException<Exception>(
() => context.ExecutePluginWith<CheckDuplicateOrder>(null));
}
}
For these small tests I'd like to have this parent with Shared tests but I don't know how to reference the 'to-be' child's target.
I prefer MSTest, but any NuGet framework is accepted.
Maybe this helps with understanding
Every plugin would have it's own test class.
Every plugintest class needs the basic.
These basic tests should be inherited from parent (so they don't take up space).
Plugins: Dog, Cat, Mouse
PluginTests: DogTest, CatTest, MouseTest
BasePluginTest -> should have shared tests where SomePlugin in the exmaple is Dog/Cat/Mouse. But I don't know how to reference it. Every plugin would have a function TestWalk() { .. ExecutePluginWith<SomePlugin>}. The Cat should call CatTest, the Dog should call DogTest.
As with a normal class you should favour composition over inheritance. Even
though test-classes do not have to follow the same rules and guidelines as normal classes doesn't mean we cannot implement them.
So when you feel you have some common functionality accross your test-classes you should extract some class that is used by your tests. You would do the same for a normal business-class also, won´t you?
class CommonFunc
{
public static bool NullLocalPluginContext<T, TException>() where T: IPlugIn, TException : Exception
{
XrmFakedContext context = new XrmFakedContext();
try { context.ExecutePluginWith<T>(null)) };
catch (T e) { return true; }
return false;
}
}
[TestClass]
public class CheckDuplicateOrderTests
{
[TestMethod]
public void NullLocalPluginContext()
{
Assert.IsTrue(CommonFunc.NullLocalPluginContext<CheckDuplicateOrder, Exception>(null));
}
}
[TestClass]
public class SomeOtherPluginTests
{
[TestMethod]
public void NullLocalPluginContext()
{
Assert.IsTrue(CommonFunc.NullLocalPluginContext<SomePlugin, InvalidPluginExecutionException>(null));
}
}
You could also make your common method rethrow the exception instead of just returning true or false if you want to log the actual exception being thrown within the test-framework.
Disclaimer: some people won't like this because it abuses class inheritance to save code. It's a potential tool for the job, you can evaluate whether it works for you or not.
This seems like it could be achievable with a base class to define the shared tests. Maybe something like this would achieve what you're trying to do?
// note: no [TestClass] on this type so it doesn't get discovered by MSTest.
// Probably should also be abstract.
public class SharedTests<T> where T : IPlugin
{
[TestMethod]
public void NullLocalPluginContext()
{
XrmFakedContext context = new XrmFakedContext();
Assert.ThrowsException<Exception>(
() => context.ExecutePluginWith<T>(null));
}
}
Your plugin classes would inherit from this class:
[TestClass]
public class CheckDuplicateOrderTests : SharedTests<CheckDuplicateOrder>
{
// NullLocalPluginContext test is inherited from the parent type
}
[TestClass]
public class SomeOtherPluginTests : SharedTests<SomeOtherPlugin>
{
// Also has NullLocalPluginContext test inherited, but for testing SomeOtherPlugin
}

Is this sort of structure/scenario in a unit test project possible?

I'm new to the concept of unit testing and have started using xUnit framework to write my tests. I have a question that I would like to ask about unit testing.
In my test project, I'm going to have an interface which contains all the common test scenarios which will then be implemented by a base class. I didn't want to repeat writing the same code for the same test over and over in each test class files so in the base class I will have the implementation for each of the methods outlined in the interface but marked as virtual as it can be overwritten by the concrete test class when it needs to be.
For example:
public interface IPersonTests
{
void ValidateAge();
void ValidateExperience();
void ValidateAddress();
}
public abstract class BasePersonTests : IPersonTests
{
public virtual void ValidateAge()
{
// method implementation
}
public virtual void ValidateExperience()
{
// method implementation
}
public void ValidateAddress()
{
// method implementation
}
}
public class PersonA : BasePersonTests
{
[Fact]
public override void ValidateAge()
{
// different method implementation to the one specified in the base class
}
}
Is it okay to have a code structure like the above for a unit test project?

Nunit base class with common tests

I am using nunit to do some tests for some classes.
There are a couple of operations that are common for all the test classes but require different parameters to work.
So I added the tests in a base class and virtual methods in the base class to provide the parameters.
In the derived test classes I overriden the virtual methods to provide specific parameters for the tests in the base class.
Now my problem is that I want the tests in the base class to be executed only from the derived classes. I am currently using the ignore attribute on the base class to ignore the tests but this causes some warnings when the tests are ran and there is a policy that does not allow me to submit the changes to svn if there are a number of ignored tests.
So how can I run the tests from the base class in the derived classes only without using the ignore attribute on the base class.
You should be able to mark your base class as abstract, this will stop nunit running the tests in that class - meaning you no longer need the ignore attribute.
namespace MyTests
{
[TestFixture]
public abstract class BaseTestClass
{
[Test]
public void CommonTest()
{
}
}
[TestFixture]
public class TestClass1 : BaseTestClass
{
[Test]
public void OtherTest1()
{
}
}
[TestFixture]
public class TestClass2 : BaseTestClass
{
[Test]
public void OtherTest2()
{
}
}
}

used in multiple [TestFixture]s

I'm in the process of setting up tests in NUnit and have a newbie question.
Is it possible to have a Test/s that could be used in multiple [TestFixture]s?
So
[Test]ValidateString(string bob)
Could be called in a series of different [TestFixture]?
That doesn't sound like a test to me. Tests are typically parameterless (unless you're using [TestCase]s) and running it within a context of a single fixture would typically be enough -- it either passes once and that's good or it doesn't and it's a broken test.
If you just have a method that does some validation on a string, you could set it up as a static method on some class (e.g. TestHelpers) and call it from whatever tests (in multiple test fixtures) need it.
Here's another idea: inheritance. You can have a base fixture that has all your tests, and then fixtures that inherit from it that set up whatever variables you need. The tests will run for each fixture. I'm not familiar with Selenium RC, but you should be able to adapt the code below to set up whatever variables you need in various fixtures.
[TestFixture]
public class BaseFixtureTests
{
protected IMyClass _myClass;
[TestFixtureSetUp]
public void FixtureSetup()
{
_myClass = ConfigureMyClass();
}
protected virtual IMyClass ConfigureMyClass()
{
// fixtures that inherit from this will set up _myClass here as they see fit.
}
[Test]
public void MyClassTest1()
{
// test something about _myClass;
}
}
[TestFixture]
public class MySpecificFixture1 : BaseFixtureTests
{
protected override IMyClass ConfigureMyClass()
{
return new MySpecificMyClassImplementation();
}
}
public class MySpecificMyClassImplementation : IMyClass
{
//some implementation
}
You can also add extra tests in each fixture as well that don't test common functionality and don't need to be reused across fixtures.
The newer version of NUnit supports generics. This is a great fit if what you are testing doesn’t need to be configured (only created) from your test code. Here is an example copied from http://nunit.net/blogs/:
[TestFixture(typeof(ArrayList))]
[TestFixture(typeof(List<int>))]
public class IList_Tests<TList> where TList : IList, new()
{
private IList list;
[SetUp]
public void CreateList()
{
this.list = new TList();
}
[Test]
public void CanAddToList()
{
list.Add(1); list.Add(2); list.Add(3);
Assert.AreEqual(3, list.Count);
}
}
I’ve also used Anna’s approach of inheritance. One possible refinement to her example (depending on personal preference): Don’t mark the base class as a TestFixture, only the child classes. Each class that you mark as a TestFixture will be displayed as a set of tests in the NUnit client. You will probably never want to run the base class methods directly because the child is providing all of the setup code. If you remove TestFixture from the base class, running invalid tests won’t be an option in the UI. This allows you to run all the tests and see all green… always a nice feeling.
You might be able to achieve what you want with inheritance.
using NUnit.Framework;
namespace ClassLibrary1
{
[TestFixture]
public class TestFixtureBase
{
[SetUp]
public virtual void Setup()
{
// setup code here
}
[Test]
public void CommonTest1()
{
Assert.True(true);
}
[Test]
public void CommonTest2()
{
Assert.False(false);
}
}
public class MyClassTests : TestFixtureBase
{
[SetUp]
public override void Setup()
{
base.Setup();
// additional setup code
}
[Test]
public void MyClassTest1()
{
Assert.True(true);
}
}
}
You can write a method to be called from multiple [Test] methods. But I don't think there is a way to have the same [Test] included in multiple [TestFixture]s.
[TestFixture]
public class TestsOne{
[Test] public void TryOne(){
Helpers.ValidateString("Work?");
}
}
[TestFixture]
public class TestsTwo{
[Test] public void TryTwo(){
Helpers.ValidateString("Work?");
}
}
public static class Helpers{
public static void ValidateString(string s){
Assert.IsNotNull(s);
}
}

How can I inherit an inner class using an abstract base class?

I'm trying to create a test class which organizes its test methods using inner classes. I would like for this class to be abstract with the ability to set a static property so this property can be injected. Here's an example of what I'm talking about:
[TestClass]
public abstract class BaseUnitTest
{
public static string InjectedProperty;
public static string GetInjectedString()
{
return InjectedProperty;
}
[TestClass]
public class WhenFoo
{
[TestMethod]
public void TestFoo()
{
string str = GetInjectedString();
}
}
}
[TestClass]
public class DeriverdUnitTest : BaseUnitTest
{
[ClassInitialize]
public void SetUp()
{
InjectedProperty = "Injected Property";
}
}
However, I don't see a DerivedUnitTest+WhenFoo+TestFoo() class show up in my unit test view. I'm using Visual Studio 2010. I'm guessing when I override BaseUnitTest, I don't override its inner classes as well. I suppose I could make its inner classes abstract and override them later, but as the complexity of my test class increases this will get really annoying. Could somebody please explain why this is occuring and how I can fix it?
Thanks.
Edit:
I feel like I need to better explain my reasons for wanting to do this. We'd like to implement a testing standard which is very verbose in its naming. Therefore a test class would look something like this:
[TestClass]
public abstract class BaseUnitTest
{
public static string InjectedProperty;
public static string GetInjectedString()
{
return InjectedProperty;
}
[TestClass]
public class WhenFooIsCalled
{
[TestClass]
public class AndTheArgumentIsNull
{
[TestMethod]
public void AnArgumentNullExceptionShouldBeThrown()
{
string str = GetInjectedString();
}
}
}
}
The advantage of this is when you open up the test view in Visual Studio and display the method name and class name columns you get something that looks like this:
BaseUnitTest+WhenFooIsCalled+AndTheArgumentIsNull AnArgumentNullExceptionShouldBeThrown()
This makes it a lot easier to glance to tell what a failing test among a few hundred pass tests is supposed to do.
The main reason I want to be able to override the abstract BaseUnitTest is because when I do all of the tests which were contained in the BaseUnitTest are all added to the DerivedUnitTest and show up in the Test View in Visual Studio.
Thanks again.
In the C# language, nested classes have no special relationship with the class in which they are nested. It is a completely different type. There is only one good reason you'd ever do this: you can declare the class private. Which helps you to create a little worker class to get a job done on behalf of the outer class, a class that is completely invisible from the outside. Very useful, you cannot otherwise declare a private class at outer class scope, the best you can do is internal.
What follows is that it in no way plays a role in the inheritance of the outer class. A class you derive from the outer has no visibility to the nested class inside the base class at all. Which was the intention, declaring it private was the reason to nest it in the first place.
Punt: if you need that class in the derived one just declare it internal or public.
Nested types don't work that way. You can't "override" types.
It's not clear what you're trying to achieve here, but I don't think it's going to work.
You can accomplish the kind of rich, verbose, BDD-style test repriting with xUnit.NET and SubSpec. SubSpec is included in the xUnit.NET extras download these days. You can read more about SubSpec and BDD testing at the following article:
http://haacked.com/archive/2008/08/24/introducing-subspec.aspx
How about using a config file? For Example
[TestClass]
public class WhenFoo
{
[TestMethod]
public void TestFoo()
{
string str = ConfigurationManager.AppSettings["WhenFooTestFooString"];
}
}

Categories

Resources