我写这篇文章是因为我自己尝试了一段时间,但没有运气。无论出于何种原因,我能找到的每个示例似乎都表明这是开箱即用的,但每当我尝试做同样的事情时,我总是会出错。基本上,我有一个控制器,它有两个通过注入的属性。DI,比方说
public class SomeController
{
private ISomeInterface _i;
private MyConfig _c;
public SomeController(ISomeInterface i, MyConfigContext cxt) // Where cxt is Type of DbContext
{
_i = i;
_c = cxt.Configs.FirstOrDefault();
}
public OkResult PostModel(SomeModel c)
{
// Do things
return Ok();
}
}
在我使用 xUnit、Moq 和 AutoFixture 的测试中,我试图避免手动实例化依赖项B
和C
:
public class SomeControllerTests
{
private MyDbContext _cxt;
private Fixture _fixture;
public SomeControllerTests()
{
_cxt = GetCxt() // GetCxt() just returns a context instance, nothing special
_fixture = new Fixture();
_fixture.Customize(new AutoMoqCustomization { ConfigureMembers = true });
_fixture.Customizations.Add(
new TypeRelay(
typeof(ISomeInterface),
typeof(SomeConcreteClass)
)
);
}
[Fact, AutoData]
public void PostStatus_ReturnsOk_GivenValidRequest()
{
SomeController c = _fixture.Create<SomeController>();
SomeModel m = _fixture.Create<SomeModel>();
var result = c.PostModel(m);
Asset.IsType<OkResult>(result);
}
}
有了上面的内容,我在NotImplementedException
运行测试时得到了一个结果,它不会告诉我到底什么没有被实现,所以我无法知道问题是什么。我一定在文档中遗漏了一些东西。我想使用 AutoFixture 使我的测试更持久,但到目前为止,尝试使用它一直很痛苦。我真的不想为了运行测试而手动模拟/存根我的整个应用程序。理想情况下,我希望使用 AutoFixture 文档中显示的语法,您将测试相关的实例放在测试的参数中,它们是为您创建的,但我没有任何运气,比如......
[Theory, AutoData]
SomeTestMethod(SomeController c, SomeModel m)
{
var result = c.PostModel(m);
Assert.IsType<OkResult>(result);
}
谢谢阅读 (: