Gra*_*ace 2 c# tdd moq autofixture
我是AutoFixture的新手,我正试图在我的测试环境中为团队中较少TDD的开发者创建一个友好的扩展.这是代码:
public class HomeController : Controller
{
private readonly ISomeService _someService;
public HomeController(ISomeService someService)
{
_someService = someService;
}
public ActionResult Index()
{
_someService.SomeMethod();
return View("Index");
}
}
public class ControllerContext<T> where T : Controller
{
protected static T ControllerUnderTest;
private static IFixture _fixture;
public ControllerContext()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
_fixture.Customize<ControllerContext>(c => c.Without(x => x.DisplayMode));
ControllerUnderTest = _fixture.Create<T>();
}
protected static Mock<TDouble> For<TDouble>() where TDouble : class
{
//var mock = _fixture.Create<TDouble>();
var mock = _fixture.Create<Mock<TDouble>>();
return mock;
}
}
Run Code Online (Sandbox Code Playgroud)
所以扩展是For方法 - 当我检查ControllerUnderTest哪个有一个注入'ISomeService'它有一个实例注入就好了,它肯定会调用我声明的方法.当我检查在'For'方法中创建的模拟时,它看起来与注入控制器的模型相同,但它不会Verif!
public class EXAMPLE_When_going_to_home_page : ControllerContext<HomeController>
{
Because of = () =>
{
ControllerUnderTest.Index();
};
It should_do_something = () =>
{
//This throws a 'Invocation was not performed'
For<ISomeService>().Verify(x => x.SomeMethod());
};
Establish context = () =>
{
};
}
Run Code Online (Sandbox Code Playgroud)
我正在努力寻找有人做类似事情的任何例子,我知道我肯定在做一些愚蠢的事情,但在我脑海中这个测试应该通过?
Create每次创建一个新的匿名实例,除非你冻结(通过.Freeze<T>()或AutoFixture.Xunit [Frozen])一个实例.这意味着注入的值HomeController与返回的值不同For.
有几种可能的解决方案,所有这些解决方案最终都将涉及冻结价值或注入要使用的价值.
一个例子看起来像这样:
public class ControllerContext<T> where T : Controller
{
private static Lazy<T> _controllerFactory;
private static IFixture _fixture;
public ControllerContext()
{
_fixture = new Fixture().Customize(new AutoMoqCustomization());
_fixture.Customize<ControllerContext>(c => c.Without(x => x.DisplayMode));
_controllerFactory = new Lazy<T>(() => _fixture.Create<T>());
}
protected static Mock<TDouble> For<TDouble>() where TDouble : class
{
var mock = _fixture.Freeze<Mock<TDouble>>();
return mock;
}
protected static T ControllerUnderTest
{
get { return _controllerFactory.Value; }
}
}
public class EXAMPLE_When_going_to_home_page : ControllerContext<HomeController>
{
static Mock<ISomeService> SomeService;
Because of = () =>
{
SomeService = For<ISomeService>();
ControllerUnderTest.Index();
};
It should_do_something = () =>
{
//This throws a 'Invocation was not performed'
SomeService.Verify(x => x.SomeMethod());
};
Establish context = () =>
{
};
}
Run Code Online (Sandbox Code Playgroud)
这个改变版本的重点是首先Freeze在服务模拟上调用,然后才创建控制器的匿名实例.由于For现在使用该方法的方式,您可能应该将其重命名为GetService.
| 归档时间: |
|
| 查看次数: |
553 次 |
| 最近记录: |