2016-04-19 129 views
3

我遇到NUnit告诉我的问题:“没有找到合适的构造函数”。这是什么原因?我还得到另一条消息:“异常没有堆栈跟踪”。这两条消息只是一遍又一遍地重复。这里是我的代码Nunit测试结果OneTimeSetUp:找不到合适的构造函数

[TestFixture] 
public class SecurityServiceTests 
{ 
    private IContext stubIContext; 
    private ISecurityService securityService; 
    private IWindsorContainer windsorContainer; 

    public SecurityServiceTests(IContext stubIContext) 
    { 
     this.stubIContext= stubIContext; 
    } 

    [TestFixtureSetUp] 
    public void TestSetup() 
    { 
     //Mocks the database context 
     stubIContext= MockRepository.GenerateStub<IContext>(); 
     var returnedList = new List<string>(); 
     stubIContext.Stub(a => a.GetUserSecurities(null)).IgnoreArguments().Return(returnedList); 

     securityService = new SecurityService(windsorContainer); 

    } 

    [Test] 
    public void ControllerShouldGetUserGroupForCurrentUsers() 
    { 
     //Act 
     var action = securityService.CurrentUserFeatureList; 

     //Assert 
     Assert.IsNotNull(action); 
    } 


} 

回答

3

SecurityServiceTests类需要被用作TextFixture一个默认的构造函数。

docs on TextFixture

有迹象表明,作为一个测试夹具上的类的一些限制。

它必须是公开导出的类型,否则NUnit将不会看到它。

它必须有一个默认的构造函数,否则NUnit将无法构造它。

目前尚不清楚,反正为什么你在该类接受,并设置IContext stubIContext,你接下来要嘲笑在安装该领域的构造函数。

删除public SecurityServiceTests(IContext stubIContext)构造函数,测试将运行。

编辑:这是slightly different in NUnit3,在评论中指出的@克里斯:

如果没有参数设置有TestFixtureAttribute,类必须有一个默认的构造函数。

如果提供参数,它们必须匹配其中一个构造函数。

+0

只需要注意,在NUnit3中,TestFixtures可以被参数化。但是你是对的,这看起来不像这里想要的。 [v3文档](https://github.com/nunit/docs/wiki/TestFixture-Attribute) – Chris

4

您正试图创建一个参数化灯具,因此您有一个构造函数接受一个参数。与上面的评论相反,这在NUnit V2和V3中都是有效的。

但是,为了让NUnit使用该构造函数,必须给它一个参数来应用,而且你还没有这样做。您将通过指定

[TestFixture(someArgument)] 

也许,你正打算通过分配在TestFixtureSetUp一个值stubIContext做这样的事情做到这一点。但是,这不能工作有两个原因:

  1. 它没有被提供给构造函数,这就是你的灯具需要它。

  2. 无论如何,该对象的构造发生在该设置方法被调用之前。

有几种方法可以在灯具实例化之前创建存根,特别是在NUnit v3中。然而,我实际上并没有明白为什么你需要这个设备进行参数化,因为无论如何你都使用了一个存根。

除非您有其他需要参数化的内容,在示例中未显示,否则我只需在设置中创建存根。我的首选是使用SetUp而不是TestFixtureSetUp。创建存根并不昂贵,所以似乎没有理由来节约。但是,如果在摘录中没有看到原因,TestFixtureSetUp也可以工作。

相关问题