尝试在特定错误条件下为我的应用程序的条目编写测试 - 条目看起来也类似:
IFoo.cs
public interface IFoo
{
void DoStuff();
}
Foo.cs
public class Foo : IFoo
{
void DoStuff()
{
// Do some things
}
}
AThing.cs
public class AThing
{
private readonly IFoo _iFoo;
public AThing(IFoo iFoo)
{
_iFoo = iFoo;
}
public void Whatever()
{
_iFoo.DoStuff();
}
}
AutoFacConfig.cs
public class AutofacConfig
{
private static IContainer _container;
public static IContainer Container
{
get { return _container; }
}
public static void IoCConfiguration()
{
var builder = new ContainerBuilder();
// Registrations...
builder.RegisterType<AThing>();
builder.RegisterType<Foo>().AsImplementedInterfaces();
_container = builder.Build();
}
}
Program.cs的
public class Program
{
public static int Main(string[] args)
{
try
{
AutofacConfig.IoCConfiguration();
using (var scope = AutofacConfig.Container.BeginLifetimeScope())
{
var aThing = scope.Resolve<AThing>();
var result = aThing.Whatever());
}
}
catch (Exception ex)
{
return 0;
}
return 1;
}
}
test.cs中
[TestFixture]
public class Test
{
[Test]
public void ShouldReturn0WhenExceptionEncountered()
{
// How to override say, Foo.DoStuff to throw an exception?
var result = Program.Main();
Assert(0, result);
}
}
以上是一个过于简单的示例,但是通过我通过AutoFac注册的实际实现可能很难实际导致异常。为了测试入口点的异常捕获,如果我可以在Foo
中注入我的某个依赖项的模拟或伪造,会更容易。
我该怎么做?
答案 0 :(得分:0)
与this answer类似,我进行了以下更改以测试我的方案:
重构AutoFacConfig.cs
public class AutofacConfig
{
private static IContainer _container;
public static Action<ContainerBuilder> OverridenRegistrations;
public static IContainer Container
{
get { return _container; }
}
public static void IoCConfiguration()
{
var builder = new ContainerBuilder();
// Registrations...
builder.RegisterType<AThing>();
builder.RegisterType<Foo>().AsImplementedInterfaces();
OverridenRegistrations(builder);
_container = builder.Build();
}
}
Refactored Test.cs
[TestFixture]
public class Test
{
public class ExceptionFoo : IFoo
{
public void DoStuff()
{
throw new Exception();
}
}
[Test]
public void ShouldReturn0WhenExceptionEncountered()
{
AutofacConfig.OverridenRegistrations = builder =>
{
builder.RegisterType<ExceptionFoo>().AsImplementedInterfaces();
};
var result = Program.Main();
Assert(0, result);
}
}
由于封装级别,链接问题/答案中的AutoFac配置似乎不同,所以这对我有用。