Why is a ClassInitialize decorated method making all my tests fail?

為{幸葍}努か 提交于 2019-12-22 04:58:23

问题


I understand, from MSDN, that ClassInitialize is to mark a method that will do setup code for all tests, once, before all tests run. When I include such a method in the abridged fixture below, all tests fail. As soon as I comment it out, they pass again.

[TestClass]
public class AuthenticationTests
{
    [ClassInitialize]
    public void SetupAuth()
    {
        var x = 0;
    }

    [TestMethod]
    public void TestRegisterMemberInit()
    {
        Assert.IsTrue(true);
    }
}

回答1:


The [ClassInitialize] decorated method should be static and take exactly one parameter of type TestContext:

[ClassInitialize]
public static void SetupAuth(TestContext context)
{
    var x = 0;
}

In fact, if I copy-paste your code into a clean VS project, the testrunner explains exactly that in the error message:

Method UnitTestProject1.AuthenticationTests.SetupAuth has wrong signature. The method must be static, public, does not return a value and should take a single parameter of type TestContext.




回答2:


Method marked with [ClassInitialize]:

  1. Apply to only one method of a test class.
  2. The class must be sealed, i.e. not inherited.
  3. The method has to be public static.
  4. The method must pass a TestContext parameter.
  5. The Method does not return a value.



回答3:


In VS2015, the failure to have the TestContext parameter causes this most unhelpful error to be output when you run the test (in case anyone is searching on the exception, like I was):

Exception thrown: 'Microsoft.VisualStudio.TestPlatform.MSTestFramework.TypeInspectionException' in Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll



来源:https://stackoverflow.com/questions/11297646/why-is-a-classinitialize-decorated-method-making-all-my-tests-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!