如何使用 XUnit、Moq 和 AutoFixture 对控制器进行单元测试?
How to unit test a controller with XUnit, Moq and AutoFixture?
我有一个具有以下签名的控制器:
public CustomerTypeController(
IHttpContextAccessor accessor,
IPrincipalProvider provider,
IMapper mapper,
ILogger<CustomerTypeController> logger,
ICustomerTypeService customerTypeService)
{ }
我还设置了一个AutoDataAttribute
:
public class AutoMoqDataAttribute : AutoDataAttribute
{
public AutoMoqDataAttribute()
: base(() =>
{
var fixture = new Fixture().Customize(new CompositeCustomization(
new AutoMoqCustomization(),
new SupportMutableValueTypesCustomization()));
fixture.Behaviors.OfType<ThrowingRecursionBehavior>()
.ToList()
.ForEach(x => fixture.Behaviors.Remove(x));
fixture.Behaviors.Add(new OmitOnRecursionBehavior());
return fixture;
})
{ }
}
现在我的 Theory
看起来像这样:
[Theory, AutoMoqData]
public void GetWhenHasCustomerTypesShouldReturnOneCustomerType(
IFixture fixture,
[Frozen] Mock<ICustomerTypeService> service,
CustomerTypeController sut)
{
//Arrange
var items = fixture.CreateMany<Model.CustomerType>(3).ToList();
//Act
var result = sut.Get(1);
//Assert
Assert.IsType<OkResult>(result);
}
在从控制器获取项目之前,我需要使用项目设置服务吗?如果是,服务是如何设置的?
在测试方法中使用[NoAutoProperties]
属性修饰controller参数
详见
我有一个具有以下签名的控制器:
public CustomerTypeController(
IHttpContextAccessor accessor,
IPrincipalProvider provider,
IMapper mapper,
ILogger<CustomerTypeController> logger,
ICustomerTypeService customerTypeService)
{ }
我还设置了一个AutoDataAttribute
:
public class AutoMoqDataAttribute : AutoDataAttribute
{
public AutoMoqDataAttribute()
: base(() =>
{
var fixture = new Fixture().Customize(new CompositeCustomization(
new AutoMoqCustomization(),
new SupportMutableValueTypesCustomization()));
fixture.Behaviors.OfType<ThrowingRecursionBehavior>()
.ToList()
.ForEach(x => fixture.Behaviors.Remove(x));
fixture.Behaviors.Add(new OmitOnRecursionBehavior());
return fixture;
})
{ }
}
现在我的 Theory
看起来像这样:
[Theory, AutoMoqData]
public void GetWhenHasCustomerTypesShouldReturnOneCustomerType(
IFixture fixture,
[Frozen] Mock<ICustomerTypeService> service,
CustomerTypeController sut)
{
//Arrange
var items = fixture.CreateMany<Model.CustomerType>(3).ToList();
//Act
var result = sut.Get(1);
//Assert
Assert.IsType<OkResult>(result);
}
在从控制器获取项目之前,我需要使用项目设置服务吗?如果是,服务是如何设置的?
在测试方法中使用[NoAutoProperties]
属性修饰controller参数
详见