【发布时间】:2017-10-05 23:22:57
【问题描述】:
我曾经在单元测试中使用 Moq 和 AutoMoqer,但我的团队决定改用 NSubstitute。我们大量使用 DI,所以我希望能够要求一个目标进行测试,并让该目标自动将所有模拟对象提供给它的构造函数,或者换句话说,一个传入模拟的 DI 容器。我还想根据需要修改那些模拟对象。
使用 Moq/AutoMoq/MSTest 的示例
[TestMethod]
public void ReturnSomeMethod_WithDependenciesInjectedAndD1Configured_ReturnsConfiguredValue()
{
const int expected = 3;
var diContainer = new AutoMoq.AutoMoqer();
var mockedObj = diContainer.GetMock<IDependency1>();
mockedObj
.Setup(mock => mock.SomeMethod())
.Returns(expected);
var target = diContainer.Resolve<MyClass>();
int actual = target.ReturnSomeMethod();
Assert.AreEqual(actual, expected);
}
public interface IDependency1
{
int SomeMethod();
}
public interface IDependency2
{
int NotUsedInOurExample();
}
public class MyClass
{
private readonly IDependency1 _d1;
private readonly IDependency2 _d2;
//please imagine this has a bunch of dependencies, not just two
public MyClass(IDependency1 d1, IDependency2 d2)
{
_d1 = d1;
_d2 = d2;
}
public int ReturnSomeMethod()
{
return _d1.SomeMethod();
}
}
由于我的问题措辞不当并且我进行了更多研究,因此我找到了一种使用 NSubstitute/AutofacContrib.NSubstitute/XUnit 的方法:
[Fact]
public void ReturnSomeMethod_WithDependenciesInjectedAndD1Configured_ReturnsConfiguredValue()
{
const int expected = 3;
var autoSubstitute = new AutoSubstitute();
autoSubstitute.Resolve<IDependency1>().SomeMethod().Returns(expected);
var target = autoSubstitute.Resolve<MyClass>();
int actual = target.ReturnSomeMethod();
Assert.Equal(actual, expected);
}
public interface IDependency1
{
int SomeMethod();
}
public interface IDependency2
{
int NotUsedInOurExample();
}
public class MyClass
{
private readonly IDependency1 _d1;
private readonly IDependency2 _d2;
//please imagine this has a bunch of dependencies, not just two
public MyClass(IDependency1 d1, IDependency2 d2)
{
_d1 = d1;
_d2 = d2;
}
public int ReturnSomeMethod()
{
return _d1.SomeMethod();
}
}
我还有我原来的问题。如何使用 AutoFixture.AutoNSubstitute 作为 DI 容器来做到这一点?
【问题讨论】:
-
你有
fixture.Create<IPromise>(),还有Substitute.For<IPromise>()。为什么要以两种不同的方式创建两个相同类型的对象?_target您的系统在测试中吗?IPromise是如何定义的? -
如果您发布 Minimal, Complete, and Verifiable example 会很有帮助 - 例如,您想通过但当前失败的单元测试。另一个想法是,如果您以前有一个使用 AutoFixture.AutoMoq 的有效解决方案,您可以(也)发布它。
-
嗨,马克 - 感谢您查看此代码。我为这个糟糕的例子道歉,我已经用你的建议更新了这个问题。
-
什么是
AutoMoq.AutoMoqer? -
来自 nuget:“自动模拟容器”...“AutoMoqer 是一个“自动模拟”容器,可为您创建对象。只需告诉它要创建什么类,它就会创建它。” github.com/darrencauthon/AutoMoq
标签: c# unit-testing dependency-injection autofixture nsubstitute