我正在尝试使用SUT 工厂“模式”来创建我的 SUT。
给定 SUT 结构:
namespace MySut
{
public class Dep1
{
}
public class Dep2
{
}
public class Sut
{
public Sut( Dep1 dep1, Dep2 dep2 )
{
}
}
}
我正在使用AutoFixture,并且想知道折叠以下规范和相关 SUT 工厂方法 [有价值但] 忙碌工作的最佳方法是什么:
namespace MySpecifications
{
using MySut;
public class MySpecification
{
public void TestCore()
{
// Dont care about dependencies, testing core functionality
var sut = CreateSut();
}
public void TestDep1Interaction()
{
// Dont care about Dep2, want to observe stuff on the Dep1 dependent object
var sut = CreateSut( new Mock<Dep1>().Object );
}
public void TestDep2Interaction()
{
// Dont care about Dep1, want to observe stuff on the Dep2 dependent object
var sut = CreateSut( new Mock<Dep2>().Object );
}
private object CreateSut( )
{
return CreateSut( CreateDep1(), CreateDep2() );
}
private object CreateSut( Dep1 dep1 )
{
return CreateSut( dep1, CreateDep2() );
}
private object CreateSut( Dep2 dep2 )
{
return CreateSut( CreateDep1(), dep2 );
}
private Sut CreateSut( Dep1 dep1, Dep2 dep2 )
{
return new Sut( dep1, dep2 );
}
private static Dep1 CreateDep1()
{
return new Fixture().CreateAnonymous<Dep1>();
}
private static Dep2 CreateDep2()
{
return new Fixture().CreateAnonymous<Dep2>();
}
}
}
类似于:
public class MyAutoFixturedSpecification
{
public void TestCore()
{
// Dont care about dependencies, testing core functionality
var sut = CreateSut();
}
public void TestDep1Interaction()
{
// Dont care about Dep2, want to observe stuff on the Dep1 dependent object
var sut = CreateSut( new Mock<Dep1>().Object );
}
public void TestDep2Interaction()
{
// Dont care about Dep1, want to observe stuff on the Dep2 dependent object
var sut = CreateSut( new Mock<Dep2>().Object );
}
private object CreateSut( params object[] injectedNonAnonymouses )
{
return new Fixture( ).Build<Sut>( )./*??????*/;
}
}
或者:
public class MyAnticipatedAutoFixturedSpecification
{
public void TestCore()
{
// Dont care about dependencies, testing core functionality
var sut = new Fixture( ).Build<Sut>().CreateAnonymous( );
}
public void TestDep1Interaction()
{
// Dont care about Dep2, want to observe stuff on the Dep1 dependent object
var sut = new Fixture().Build<Sut>()/*.With( new Mock<Dep1>().Object )*/.CreateAnonymous();
}
public void TestDep2Interaction()
{
// Dont care about Dep1, want to observe stuff on the Dep2 dependent object
var sut = new Fixture().Build<Sut>()/*.With( new Mock<Dep2>().Object )*/.CreateAnonymous();
}
}
即,删除所有工厂垃圾,以便我的规范可以轻松应对过渡到:
namespace MySutWithNewDependency
{
public class Dep1
{
}
public class Dep2
{
}
public class Dep3
{
}
public class Sut
{
public Sut( Dep1 dep1, Dep2 dep2, Dep3 dep3 )
{
}
}
}
虽然与自动模拟容器的概念有重叠,但我仍然不是在寻找金锤 - 只是一种能够一次模拟 0 或 1 个事物并且能够自定义创建依赖对象而无需每当其依赖关系集发生变化时,重新访问对 Sut 构造函数的显式调用。
(也使用 xUnit.net(SubSpec 风格)、Moq、Ninject2(虽然我不想在我的规范中使用 DI))