Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio 2010 - UnitTest - Exception while using generics and AssemblyInitialize

I have a problem with unit tests in Visual Studio 2010. I've pasted the simplified code below.

[TestClass]
public class TestClassA<T>
{
    [AssemblyInitialize()]
    public static void Initialize(TestContext testContext) {}
}

[TestClass]
public class TestClassB : TestClassA<String>
{
    [TestMethod]
    public void TestMethod()
    {
       Assert.IsTrue(true);
    }
}

When I run TestMethod(), I get the following exception:

Assembly Initialization method TestProject.TestClassA`1.Initialize threw exception. System.InvalidOperationException: System.InvalidOperationException: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.. Aborting test execution.

at System.Reflection.RuntimeMethodInfo.ThrowNoInvokeException()
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestExecuter.RunAssemblyInitializeMethod()

When I google this bug, I can find advice how to fix code that uses reflection to call the [AssemblyInitialize] method. But that code is not mine, it's:

Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestExecuter.RunAssemblyInitializeMethod()

I can use [ClassInitialize] method instead of [AssemblyInitialize] and it works, but still I would like to use [AssemblyInitialize] method.

Thank you in advance for any suggustions.

like image 478
CubeCoop Avatar asked Nov 02 '12 13:11

CubeCoop


1 Answers

You don't actually need the inheritance. You can put a separate class in your test project/assembly that contains both AssemblyInit and AssemblyCleanUp attributed methods. Like so:

[TestClass]
public static class AssemblyInitializer
{
    [AssemblyInitialize]
    public static void AssemblyInit(TestContext context)
    {

    }

    [AssemblyCleanup]
    public static void AssemblyCleanup()
    {
    }
}
like image 96
jochen.vg Avatar answered Oct 25 '22 22:10

jochen.vg