NUNIT is ignoring my tests? Why? - nunit

I Have a really simple test class as below.
For some reason my test is being ignored by the GUI and coming up yellow.
I have updated the framework and runner to 2.4.8 as I thought it might have been differences between versions being the problem.
using System;
using NUnit.Framework;
namespace TestRunner
{
[TestFixture]
class TestMe
{
[Test]
public void TestBob()
{
Assert.IsTrue(true);
}
}
}

Your TestMe class needs to be public.
Here is some documentation on the requirements for classes marked with the TestFixture attribute that discusses the conditions under which a class may not be recognized as a test fixture.

You didn't specify an access modifier for your class; therefore, your class is internal by default and NUnit does not see your class.
If you specify the public access modifier for your class that contains the Tests, then it should just work:
[TestFixture]
public class TestMe
{
[Test]
public void TestBob()
{
Assert.AreEqual ("Bob", "Bob");
}
}

Related

Test with AutoData from base test fixture isn't run

I use Autofixture 3.21.0 and AutoFixture.NUnit2 3.21.0 along with NUnit 2.6.3 and Resharper 8.2.3 runner.
I have implemented the generic base test fixture which contains a common set of tests for several production classes. It's something like the following:
[TestFixture]
public class TestsBase<T>
{
[Test]
public void Test_in_base_class()
{
Assert.Pass();
}
[Test, AutoData]
public void Test_in_base_class_with_autodata( T obj )
{
// this test is not run !!!
Assert.NotNull( obj );
}
}
One example concrete test fixture class which inherits from base test fixture class can be implemented as shown below:
[TestFixture]
public class DerivedTests : TestsBase<string>
{
[Test]
public void Test_in_derived_class()
{
Assert.Pass();
}
[Test, AutoData]
public void Test_in_derived_class_with_autodata( string obj )
{
Assert.NotNull( obj );
}
}
When I run this derived test fixture using R# 8.2.3 runner, test method from base class which is attributed with AutoDataAttribute (named Test_in_base_class_with_autodata) is not run. All other test methods are invoked as expected but that from base class with AutoDataAttribute.
Have you had the same problem? Is it AutoFixture.Nunit2 bug? Is there a workaround for this issue? Please for help.

Generated moles type for a static internal class is not accessible in test class

I am trying to get access to an internal static class to override some of its methods so that I can test classes that depend on that class
From what I read that should be possible but I am not obviously not understanding everything as even a simple example seems to fail to generate a mole type for the internal static class.
I have two classes in a namespace and assembly
namespace SimpleClassToTest
{
public class Class1
{
public string SayOla() { return Class2.ReturnMe("Ola"); }
}
}
namespace SimpleClassToTest
{
internal static class Class2
{
static public string ReturnMe(string m)
{
return m;
}
}
}
In AssemblyInfo.cs I also have
[assembly: InternalsVisibleTo("SimpleClassToTest")]
[assembly: InternalsVisibleTo("SimpleClassToTest.Moles")]
In the test project I have a single test class
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SimpleClassToTest;
using SimpleClassToTest.Moles;
namespace SimpleClassToTest.Moles
{
[TestClass]
public class UnitTest1
{
public UnitTest1()
{
}
[TestMethod]
[HostType("Moles")]
public void TestMethod1()
{
Class1 c1 = new Class1();
Assert.AreEqual(c1.SayOla(), "Ola");
MClass2.ReturnMeString = (ignored) => { return "ReturnMe"; };
Assert.AreEqual(c1.SayOla(), "ReturnMe");
}
}
}
Unfortunately that is not compiling. The error is
UnitTest1.cs(25,13): error CS0122: 'SimpleClassToTest.Moles.MClass2' is inaccessible due to its protection level
Any tips to get this going would certainly be appreciated!
Thanks!
Peter
PS Tried this both on VS2008 and on VS2010 with moles version Microsoft Moles v0.94.51023.0
(Edit : From Comment Below)
As a workaround, in the unit test:
Type mClass2Type = typeof(SimpleClassToTest.Moles.MClass1)
.Assembly.GetType("SimpleClassToTest.Mole‌​s.MClass2");
PropertyInfo returnMeProp = mClass2Type.GetProperty("ReturnMeString");
Microsoft.Moles.Framework.MolesDelegates.Func<String, String> molesDelegate =
(ignore) => { return "ReturnMe"; };
returnMeProp.SetValue(mClass2Type, molesDelegate, null);
Assert.AreEqual(c1.SayOla(), "ReturnMe");
If your assembly under test is strongly signed, then the moles assembly is also strongly signed, and you must specify the public key in the InternalsVisibleTo attribute. See the section "Code Generation and Compilation" of the moles reference manual for details.
Here is a quote that might be relevant:
... use this snippet as a
starting point to add InternalsVisibleTo attribute to your project.
[assembly: InternalsVisibleTo(“FileSystem.Moles, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e92decb949446f688ab9f6973436c535bf50acd1fd580495aae3f875aa4e4f663ca77908c63b7f0996977cb98fcfdb35e05aa2c842002703cad835473caac5ef14107e3a7fae01120a96558785f48319f66daabc862872b2c53f5ac11fa335c0165e202b4c011334c7bc8f4c4e570cf255190f4e3e2cbc9137ca57cb687947bc”)]

Testing multiple interface implementations with same tests - JUnit4

I want to run the same JUnit tests for different interface implementations. I found a nice solution with the #Parameter option:
public class InterfaceTest{
MyInterface interface;
public InterfaceTest(MyInterface interface) {
this.interface = interface;
}
#Parameters
public static Collection<Object[]> getParameters()
{
return Arrays.asList(new Object[][] {
{ new GoodInterfaceImpl() },
{ new AnotherInterfaceImpl() }
});
}
}
This test would be run twice, first with the GoodInterfaceImpl then with the AnotherInterfaceImpl class. But the problem is I need for most of the testcases a new object. A simplified example:
#Test
public void isEmptyTest(){
assertTrue(interface.isEmpty());
}
#Test
public void insertTest(){
interface.insert(new Object());
assertFalse(interface.isEmpty());
}
If the isEmptyTest is run after the insertTest it fails.
Is there an option to run automatically each testcase with a new instance of an implementation?
BTW: Implementing a clear() or reset()-method for the interface is not really an options since I would not need it in productive code.
Here is another approach with the Template Method pattern:
The interface-oriented tests go into the base class:
public abstract class MyInterfaceTest {
private MyInterface myInterface;
protected abstract MyInterface makeContractSubject();
#Before
public void setUp() {
myInterface = makeContractSubject();
}
#Test
public void isEmptyTest(){
assertTrue(myInterface.isEmpty());
}
#Test
public void insertTest(){
myInterface.insert(new Object());
assertFalse(myInterface.isEmpty());
}
}
For each concrete class, define a concrete test class:
public class GoodInterfaceImplTest extends MyInterfaceTest {
#Override
protected MyInterface makeContractSubject() {
// initialize new GoodInterfaceImpl
// insert proper stubs
return ...;
}
#Test
public void additionalImplementationSpecificStuff() {
...
}
}
A slight advantage over #Parameter is that you get the name of the concrete test class reported when a test fails, so you know right away which implementation failed.
Btw, in order for this approach to work at all, the interface must be designed in a way which allows testing by the interface methods only. This implies state-based testing -- you cannot verify mocks in the base test class. If you need to verify mocks in implementation-specific tests, these tests must go into the concrete test classes.
Create a factory interface and implementations, possibly only in your test hierarchy if you don't need such a thing in production, and make getParameters() return a list of factories.
Then you can invoke the factory in a #Before annotated method to get a new instance of your actual class under test for each test method run.
Just in case somebody reaches here(like I did), looking for testing multiple implementations of the same interface in .net you could see one of the approaches that I was using in one of the projects here
Below is what we are following in short
The same test project dll is run twice using vstest.console, by setting an environment variable. Inside the test, (either in the assembly initialize or test initialize) register the appropriate implementations into a IoC container, based on the environment variable value.
In Junit 5 you could do:
#ParameterizedTest
#MethodSource("myInterfaceProvider")
void test(MyInterface myInterface) {}
static Stream<MyInterface> myInterfaceProvider() {
return Stream.of(new ImplA(), new ImplB());
}
interface MyInterface {}
static class ImplA implements MyInterface {}
static class ImplB implements MyInterface {}

Run Current Junit Test in GWTTestCase

I have a JUnit test that I run on one class, but I recently wrote an emulated version for GWT. Since the specification is the same, I would like to use the same test case, but I want it to run in the GWT environment, which would typically be accomplished by extending GWTTestCase.
I really want to avoid any copy/paste nonsense, because there are likely to be added tests in the future, which I should not be burdened with copying later.
How can I import/inherit my standard unit test to be run as either a regular test case or a GWT test case?
I have found the solution to this problem.
If you extend the original test with GWTTestCase, you can override getModuleName to return null. This tells GWTTestCase to run as a normal pure java test (no translation at all).
You can then extend this test case with one that overrides getModuleName to return a module name, and the same tests will be run with translation.
Basically:
public class RegularTest extends GWTTestCase {
#Override
public String getModuleName() { return null; }
public void testIt() {...}
}
...and the GWT version...
public class GwtTest extends RegularTest {
#Override
public String getModuleName() { return "some.module"; }
}
The downside to this is that it forces you to use JUnit3 style tests, which I find a little annoying, but it beats the alternative.
I think there is no easy way .. But you can extract an interface of your junit test, gwt test case and junit test case implements this interface. You can create a third class for implementation, all test call methods of gwt test case and junit test are delegated to this implementation class.
public interface IRegularTest {
public void testSomething();
public void testSomething2();
}
public class RegularTestImpl implements IRegularTest {
public void testSomething(){
// actual test code
}
public void testSomething2(){
// actual test code
}
}
public class RegularTest extends TestCase implements IRegularTest {
IRegularTest impl = new RegularTestImpl();
public void testSomething(){
impl.testSomething
}
public void testSomething2(){
}
}
public class GwtTest extends TestCase implements IRegularTest {
IRegularTest impl = new RegularTestImpl();
public void testSomething(){
impl.testSomething
}
public void testSomething2(){
}
}

SetUp in derived classes with NUnit?

If I have the following code:
[TestFixture]
public class MyBaseTest
{
protected ISessionManager _sessionManager;
[SetUp]
public void SetUp() { /* some code that initializes _sessionManager */ }
}
[TestFixture]
public class MyDerivedTest : MyBaseTest
{
IBlogRepository _repository;
[SetUp]
public void SetUp() { /* some code that initializes _repository */ }
[Test]
public void BlogRepository_TestGoesHere() { /* some tests */ }
}
...NUnit doesn't call the base SetUp routine. This is expected, and I don't have a problem with it in itself. I can get the derived SetUp to call the base SetUp first, like this:
[TestFixture]
public class MyDerivedTest : MyBaseTest
{
IBlogRepository _repository;
[SetUp]
public new void SetUp()
{
base.SetUp();
/* some code that initializes _repository */
}
This is ugly. If it was a constructor, I wouldn't have to.
I could use the "template method" pattern, and have the following:
public void MyBaseTest
{
abstract void SetUp();
[SetUp]
public void BaseSetUp()
{
/* base initialization */
SetUp(); // virtual call
}
}
I'm not particularly fond of this, either.
What do you do when their test classes need SetUp, and they're derived from another class that also needs SetUp?
You have to call the method directly.
[SetUp]
public void DerivedSetUp()
{
base.BaseSetUp();
// Do something else
}
Edit: I haven't tried it, but perhaps a partial method might work too. I'd prefer to do the above though.
Edit2: I've just tried using partial methods. It didn't work. Even if it did, I think it's still going to be easier to call the base class.
You have the base class explicitly. Given that NUnit uses the [Setup] attribute to mark up test setup, I tink this is "the right thing" to do for NUnit, because it follows the usual language rules.
Sure, NUnit could search the base classes, and call their Setup functions automagically, but I think this would be rather surprising for most people.
There is however at least one unit testing framework that uses constructors for setup: xUnit.Net. Here, the base class setup is called automatically, because this is how constructors in C# behave.
(Note, though, that xUnit.Net recommends again using test setup.)
It looks like you want the setup to be run once before any testing starts, not once before each test is run. The annotation [SetUp] makes the method run once before each test in your fixture is run. [SetUp] is not inherited.
The annotation you want to use is [TestFixtureSetUp] which is run only once, before any of the tests in a fixture are run. This is inherited in the way that you would expect. :)
See the TextFixtureSetUp docs
An approach that I use that I learned in the TDD FireStarter in Tampa was to have the setup method in the base class and then to have a virtual method in the base class called observe. This method is then called in the base class at the end of the setup method.
Then what you do is in the new class that derives from the base class you will override the observe method. The trick in this scenario is you want to execute the Setup method of the base class and the child class does not have a Setup method. The reason for this is the code that you have in the observe method are only those additional things you need for the child test class.
This approach works well for me, but one gotcha is that the test runner will want to execute the base class tests, so what I do to get around that is to move the Tests from the base class into a new class that derives from the base if I have any.
The following works in MbUnit. It may work in NUnit as well.
[TestFixture]
public abstract class Base {
[SetUp]
public virtual void SetUp() {
//Some stuff.
}
}
public class Derived : Base {
public override void SetUp() {
base.SetUp();
//Some more stuff.
}
[Test]
public virtual void Object_WhenInACertainState_WhenAMethodIsCalled_Throws() {
//Create and set state on the object.
//Call the method.
//Assert the method threw.
}
}