测试StructureMap约定

时间:2012-09-18 07:34:57

标签: c# unit-testing structuremap

我有一个StructureMap的约定,如下所示:

public class FakeRepositoriesConvention : IRegistrationConvention
{
    public void Process(Type type, global::StructureMap.Configuration.DSL.Registry registry)
   {
        if (type.Name.StartsWith("Fake") && type.Name.EndsWith("Repository"))
        {
            string interfaceName = "I" + type.Name.Replace("Fake", String.Empty);
            registry.AddType(type.GetInterface(interfaceName), type);
        }
    }
}

我想为此实现单元测试,但我不知道该怎么做。

我的第一个想法是发送一个模拟的注册表,并测试使用正确的参数调用AddType()。我不能让它工作,可能是因为AddType()不是虚拟的。 Registry实现了IRegistry,但这对我没有帮助,因为Process方法不接受接口。

所以我的问题是 - 我该如何测试?

(我正在使用nUnit和RhinoMocks)

1 个答案:

答案 0 :(得分:3)

您可以完全跳过模拟并使用预定义虚拟类型的注册表和组件的简化版本:

// Dummy types for test usage only
public interface ICorrectRepository { }
public class FakeCorrectRepository : ICorrectRepository { }

[Test]
Process_RegistersFakeRepositoryType_ThroughInterfaceTypeName()
{
    var registry = new Registry();
    var convention = new FakeRepositoriesConvention();

    // exercise test
    convention.Process(typeof(FakeCorrectRepository), registry);

    // assert it worked
    var container = new Container(c => c.AddRegistry(registry));
    var instance = container.GetInstance<ICorrectRepository>();
    Assert.That(instance, Is.Not.Null);
}

如果您的约定按照您的假设工作,则上面的测试应该通过。