我刚开始在我的单元测试中使用AutoFixture.AutoMoq,我发现它对于创建我不关心特定值的对象非常有帮助.毕竟,匿名对象创建就是它的全部.
我正在努力的是当我关心一个或多个构造函数参数时.采取ExampleComponent下面:
public class ExampleComponent
{
public ExampleComponent(IService service, string someValue)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我想写一个测试,我提供了一个特定的值,someValue但是IService由AutoFixture.AutoMoq自动创建.
我知道如何使用Freeze我IFixture来保持一个已注入组件的已知值,但我不太明白如何提供我自己的已知值.
这是我理想的做法:
[TestMethod]
public void Create_ExampleComponent_With_Known_SomeValue()
{
// create a fixture that supports automocking
IFixture fixture = new Fixture().Customize(new AutoMoqCustomization());
// supply a known value for someValue (this method doesn't exist)
string knownValue = fixture.Freeze<string>("My known value");
// create an ExampleComponent with my known value injected
// but without …Run Code Online (Sandbox Code Playgroud) 让我们考虑同一个非常简单的实体的两个版本(一个带有只读属性):
public class Client
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
与
public class Client
{
public Client(Guid id, string name)
{
this.Id = id;
this.Name = name;
}
public Guid Id { get; }
public string Name { get; }
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用Autofixture时,它们将正常工作,并且可以同时使用它们。当我尝试使用预先定义参数之一时,问题就开始了。with()方法:
var obj = this.fixture.Build<Client>().With(c => c.Name, "TEST").Build();
Run Code Online (Sandbox Code Playgroud)
这将引发错误
System.ArgumentException:属性“名称”是只读的。
但是似乎Autofixture知道如何使用构造函数!而且看来实际Build<>()方法不是创建对象的实例Create()!如果构建仅准备具有设置属性的构建器,然后创建将实例化对象,则它将与只读属性一起正常工作。
那么为什么在这里使用这种(误导)策略呢?我在这里找到了一个答案,指出它是通过测试来放大反馈,但是我看不出使用的用处,FromFactory()尤其是当参数列表很广时。在Build()方法之间移动对象实例化Create()会更直观吗?
如何使用autofixture设置嵌套属性(它是readonly)?像这样的东西:
var result =
fixture.Build<X>()
.With(x => x.First.Second.Third, "value")
.Create();
Run Code Online (Sandbox Code Playgroud) 我希望通过使用AutoFixture和NSubstitue,我可以使用每个人提供的最好的东西.我自己使用NSubstitute取得了一些成功,但我对如何将它与AutoFixture结合使用感到困惑.
我的下面的代码显示了我想要完成的一系列事情,但我的主要目标是完成以下场景:测试方法的功能.
Data.Execute并确认结果我想要尝试的测试是:"should_run_GetCommand_with_provided_property_value"
任何有关如何使用NSubstitue和AutFixture的文章的帮助或参考都会很棒.
示例代码:
using FluentAssertions;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Xunit;
namespace RemotePlus.Test
{
public class SimpleTest
{
[Fact]
public void should_set_property_to_sepecified_value()
{
var sut = Substitute.For<ISimple>();
sut.Data.Returns("1,2");
sut.Data.Should().Be("1,2");
}
[Fact]
public void should_run_GetCommand_with_provided_property_value()
{
/* TODO:
* How do I create a constructor with AutoFixture and/or NSubstitute such that:
* 1. With completely random values.
* 2. With one or more values specified.
* 3. …Run Code Online (Sandbox Code Playgroud)