AutoFixture 3.18.0 引入了一个名为Idioms.FsCheck的新粘合库,它使用FsCheck来实现一个名为ReturnValueMustNotBeNullAssertion
.
这个新的断言验证(或至少,有可能)返回值(查询)的方法不返回 null。
安装
Idioms.FsCheck 在 NuGet 上可用:
PM> Install-Package AutoFixture.Idioms.FsCheck
场景
使用注入的UserService
an 实例IRemotingFacade
并公开两个[1]查询:
- 用户[] 获取用户()
- 用户[] 获取用户(整数)
场景 #1:注入的 an 实例IRemotingFacade
返回 null:
[Theory, UnitTestConventions]
public void Scenario1(
ISpecimenBuilder builder,
[Frozen]Mock<IRemotingFacade> stub)
{
stub.Setup(x => x.GetUsers()).Returns((User[])null);
var sut = from x in new Methods<UserService>() select x.GetUsers();
var assertion = new ReturnValueMustNotBeNullAssertion(builder);
Assert.Throws<ReturnValueMustNotBeNullException>(() =>
assertion.Verify(sut));
}
场景 #2:注入的 an 实例IRemotingFacade
不返回 null:
[Theory, UnitTestConventions]
public void Scenario2(
ISpecimenBuilder builder,
[Frozen]Mock<IRemotingFacade> stub,
User[] users)
{
stub.Setup(x => x.GetUsers()).Returns(users);
var sut = from x in new Methods<UserService>() select x.GetUsers();
var assertion = new ReturnValueMustNotBeNullAssertion(builder);
Assert.DoesNotThrow(() => assertion.Verify(sut));
}
场景 3:如果i
is -1 GetUsers(int)
返回 null:
[Theory, UnitTestConventions]
public void Scenario3(
ISpecimenBuilder builder,
[Frozen]Mock<IRemotingFacade> stub,
User[] users)
{
stub.Setup(x => x.GetUsers()).Returns(users);
var sut = from x in new Methods<UserService>()
select x.GetUsers(default(int));
var assertion = new ReturnValueMustNotBeNullAssertion(builder);
Assert.Throws<ReturnValueMustNotBeNullException>(
() => assertion.Verify(sut));
}
评论
如果您只安装了 F# 3.1,您还可以在app.config文件中添加程序集绑定重定向:
<dependentAssembly>
<assemblyIdentity name="FSharp.Core"
publicKeyToken="b03f5f7f11d50a3a"
culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.3.1.0"
newVersion="4.3.1.0" />
</dependentAssembly>
UnitTestConventionsAttribute
定义为:
internal class UnitTestConventionsAttribute : AutoDataAttribute
{
internal UnitTestConventionsAttribute()
: base(new Fixture().Customize(new AutoMoqCustomization()))
{
}
}
反射查询使用Albedo执行。
[1]对于演示,我将原始代码简化如下:
public class User
{
}
public interface IRemotingFacade
{
User[] GetUsers();
}
public class UserService
{
private readonly IRemotingFacade remotingFacade;
public UserService(IRemotingFacade remotingFacade)
{
if (remotingFacade == null)
throw new ArgumentNullException("remotingFacade");
this.remotingFacade = remotingFacade;
}
public User[] GetUsers()
{
return this.remotingFacade.GetUsers();
}
public User[] GetUsers(int i)
{
if (i == -1)
return null;
return this.remotingFacade.GetUsers();
}
}