如何使用structureMap测试已注册类型的范围?
例如,我有一个注册表:
public class DataRegistry : Registry
{
public DataRegistry()
{
ForRequestedType<ISessionManager>().TheDefaultIsConcreteType<SessionManager>().CacheBy(StructureMap.Attributes.InstanceScope.Singleton);
ForRequestedType<ISessionRequest>().TheDefaultIsConcreteType<SessionRequest>().CacheBy(StructureMap.Attributes.InstanceScope.HttpContext);
}
}
我想测试ISessionRequest实例范围是HttpContext。所以我有一个测试:
[Test]
public void Container_AlwaysHas_OneSessionRequestPerHTTPContext()
{
//Setup
//Act
ObjectFactory.Configure(r => r.AddRegistry<DataRegistry>());
//Test
}
但我不知道在注册后会测试该类型的范围吗?
答案 0 :(得分:2)
我相信您希望编写一个测试证明已注册插件的生命周期具有所需的生命周期。
您可以检查容器的型号。这是您希望编写的测试之一。
[TestFixture]
public class container_registration
{
[Test]
public void session_request_should_be_scopped_per_httpcontext()
{
var container = new Container(new DataRegistry());
var plugin = container.Model.PluginTypes.First(p => p.PluginType.UnderlyingSystemType == typeof(ISessionRequest));
plugin.Lifecycle.ShouldBeOfType(typeof(HttpContextLifecycle));
}
}
答案 1 :(得分:0)
[TestFixture]
public class WhenRegisteringItemsInTheIoc
{
[SetUp]
public void Setup()
{
Given_A_Ioc_Container();
When_Registering_Items_In_The_Ioc();
}
private Container _container;
private void Given_A_Ioc_Container()
{
_container = new Container();
}
public void When_Registering_Items_In_The_Ioc()
{
_container.Configure(registry => registry.For<IContext>().HybridHttpOrThreadLocalScoped().Use<Context>());
}
[Test]
public void Then_Should_Have_A_LifeTime_Of_Hybrid_Http_Or_Thread_Local_Scoped()
{
IPluginTypeConfiguration plugin =
_container.Model.PluginTypes.First(p => p.PluginType.UnderlyingSystemType == typeof (IContext));
Assert.That(plugin.Lifecycle, Is.EqualTo("Hybrid"));
}
}
如果将来有人再次访问,以上是我们用来涵盖这种情况的测试。 “plugin.Lifecycle”返回与范围相关的字符串,在本例中为“Hybrid”。如果未定义范围,则返回“Transient”。