开发者

Grensesnitt with classes with no parameterless constructors?

I wonder is anyone have tryed using Grensesnitt for unit-testing of classes that all follow the same interface. I have a problem with classes that don't have parameterless constructors. I know ther开发者_如何学运维e is GrensesnittObjectLocator but I can't figure out, how to use it.

Please advice, how to test these classes that don't have parameterless constructors with grensesnitt.


I didn't manage to make this working out of the box. I had to tweak it a little. So inside the GrensesnittObjectLocator.GetHandler method instead of:

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); };
}   

I modified it to:

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);
    };
}       

With this modification in place I wrote the following exmaple:

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;
    }
}

You can see how the Foo class doesn't have a default constructor. So now we can have this test:

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

And in order to indicate to grensesnitt how to instantiate Foo simply add the following class to your test assembly (the same assembly that contains the previous unit test):

[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");
        });
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜