在用于单元测试的.NET Core中,我正在使用Xunit,Moq和Autofixture。但是即使有了它们,我仍然看到我的单元测试变得复杂并且需要时间。
也许有人可以告诉我是否有任何方法可以使此测试更小?
[Fact]
public async Task Verify_NotAuthorised_NoServiceSendInvoked()
{
// Arrange
var fixture = new Fixture()
.Customize(new AutoMoqCustomization());
var sut = fixture.Create<VerificationService>();
var mockApiBuilder = fixture.Freeze<Mock<IApiEntityBuilder>>();
//init mocked mockSendServiceOne, so later I could check if it was invoked or not
var mockSendServiceOne = fixture.Freeze<Mock<ISendServiceOne>>();
mockApiBuilder.Setup(x => x.Verification(It.IsAny<string>(), It.IsAny<string>()))
.Returns(fixture.Create<VerificationEntity>());
var call = fixture.Freeze<Mock<ISendServiceTwo>>();
call.Setup(x => x.IsSuccessful()).Returns(false);
// Act
await sut.Verify(fixture.Create<string>(), fixture.Create<string>());
// Assert
mockSendServiceOne .Verify(x => x.Call(It.IsAny<SendServiceOneEntity>()), Times.Never);
}
测试方法本身
public async Task<CreatedEntity> Verify(string dataOne, string dataTwo)
{
await _someCaller.Call(_apiEntityBuilder.Verification(dataOne, dataTwo));
_someCaller.CreatePayment();
if (!_someCaller.IsSuccessful()) return _someCaller.CreatedEntity;
await mockSendServiceOne.Call(_apiEntityBuilder.Call(_someCaller.CreatedEntity.SpecificData));
return _someCaller.CreatedEntity;
}
在这里,我正在测试isSuccessful()是否返回fasle,然后不应该调用mockSendServiceOne.Call。
有人可以给我一些有关如何编写更好的单元测试的反馈。因为仅对于代码的这一小检查,我不得不编写大量代码对其进行测试。
您可以使用AutoData Theories。 (链接到Mark Seeman的精彩文章,介绍了这种确切情况)。>
总之,AutoFixture具有一个称为AutoData
的内置属性,您可以从中继承该属性,然后使用AutoMoqCustomization自定义灯具。
您使用此属性装饰测试方法([Theory]),现在自动固定将自动生成您为测试方法指定的任何参数。
[当使用Freeze()
方法生成项目时,请将[Frozen]
属性放在参数前面。
这里是如何做的例子:
public class TheTests
{
[Theory]
[AutoDomainData]
public void Verify_WhatWeWannaTest_CallsTheMethodOnTheDependency([Frozen] Mock<ITheDependency> dependency, WhatWeWannaTest sut)
{
// Act
sut.CallTheDependency();
// Assert
dependency.Verify(x => x.TheMethod());
}
}
// Create a AutoData attribute customized with Moq
public class AutoDomainDataAttribute : AutoDataAttribute
{
public static IFixture FixtureFactory()
{
var f = new Fixture();
// I like members of interfaces to be configured, so i set it her
f.Customize(new AutoMoqCustomization { ConfigureMembers = true });
return f;
}
public AutoDomainDataAttribute() : base(FixtureFactory) { }
}
// Simple class we can test
public class WhatWeWannaTest
{
private readonly ITheDependency _theDependency;
public WhatWeWannaTest(ITheDependency theDependency) { _theDependency = theDependency; }
public void CallTheDependency()
{
_theDependency.TheMethod();
}
}
// Simple dependency for WhatWeWannaTest
public interface ITheDependency
{
int TheMethod();
}