Grensesnitt没有无参数构造函数的类?

时间:2010-12-15 13:47:34

标签: c# .net nunit

我想是否有人尝试使用Grensesnitt作为unit-testing of classes that all follow the same interface。我有一个没有无参数构造函数的类的问题。我知道有GrensesnittObjectLocator,但我无法弄清楚,如何使用它。

请指教,如何使用grensesnitt测试这些没有无参数构造函数的类。

1 个答案:

答案 0 :(得分:0)

我无法让这个开箱即用。我不得不稍微调整一下。所以在GrensesnittObjectLocator.GetHandler方法中而不是:

public static Func<object> GetHandler(Type T)
{
    Func<object> handler;
    if (handleAll != null) return () => { return handleAll(T); };
    if (map.TryGetValue(T, out handler))
    {
        return (Func<object>)handler;
    }
    return () => { return TryReflections(T); };
}   

我将其修改为:

public static Func<object> GetHandler(Type T)
{
    return () =>
    {
        Func<object> handler;
        if (handleAll != null) return handleAll(T);
        if (map.TryGetValue(T, out handler))
        {
            return handler();
        }
        return TryReflections(T);
    };
}       

通过这个修改,我编写了以下例子:

public interface IFoo
{
    int Add(int a, int b);
}

public class Foo : IFoo
{
    private readonly string _foo;
    public Foo(string foo)
    {
        _foo = foo;
    }

    public int Add(int a, int b)
    {
        return a + b;
    }
}

您可以看到Foo类没有默认构造函数。所以现在我们可以进行这个测试:

[InterfaceSpecification]
public class IFooTests : AppliesToAll<IFoo>
{
    [Test]
    public void can_add_two_numbers()
    {
        Assert.AreEqual(5, subject.Add(2, 3));
    }
}

为了向grensesnitt指示如何实例化Foo,只需将以下类添加到测试程序集(包含先前单元测试的同一程序集):

[SetUpFixture]
public class Config
{
    [SetUp]
    public void SetUp()
    {
        // indicate to Grensesnitt that the Foo class
        // doesn't have a default constructor and that 
        // it is up to you to provide an instance
        GrensesnittObjectLocator.Register<Foo>(() =>
        {
            return new Foo("abc");
        });
    }
}
相关问题