我想使用AutoFixture(3.50.6)生成一些ApiController(WebAPI 2)的子類。爲什麼使用樣本生成器時,我會得到循環引用DummyApiController - > DummyApiController?
我自定義AF以允許使用this customization生成ApiControllers。
由於進一步定製需求,我想創建一個SpecimenBuilder
,將創建任何類型的ApiController並用一個簡單的
fixture.Create<DummyController>();
我嘗試這個測試應用此配置(NUnit的3):
[TestFixture]
public class ApiControllerSpecimenBuilderTests
{
[Test]
public void ShouldCreateAControllerUsingSpecimenBuilder()
{
var fixture = new Fixture()
.Customize(new AutoMoqCustomization())
.Customize(new ApiControllerCustomization());
fixture.Customizations.Add(new ApiControllerSpecimenBuilder());
var ctl = fixture.Create<DummyController>();
}
}
public class ApiControllerCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Inject(new UriScheme("http"));
fixture.Customize<HttpConfiguration>(c => c
.OmitAutoProperties());
fixture.Customize<HttpRequestMessage>(c => c
.Do(x =>
x.Properties.Add(
HttpPropertyKeys.HttpConfigurationKey,
fixture.Create<HttpConfiguration>())));
fixture.Customize<HttpRequestContext>(c => c
.Without(x => x.ClientCertificate));
}
}
public class ApiControllerSpecimenBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
var t = request as Type;
if (t == null || !typeof(ApiController).IsAssignableFrom(t))
{
return new NoSpecimen();
}
var controller = context.Resolve(t) as ApiController;
// ...
return controller;
}
}
public class DummyController : ApiController
{
}
失敗,出現以下錯誤:
Ploeh.AutoFixture.Object CreationException:AutoFixture無法 創建一個System.RuntimeType類型的實例,因爲遍歷的 對象圖包含循環引用。 [...]
路徑:Foo.Common.Tests.AutoFixture.SpecimenBuilders.DummyController - > Foo.Common.Tests.AutoFixture.SpecimenBuilders.DummyController
爲什麼DummyController有一個參考到它自己的類型?
而且,如果我改變測試與DummyController一個空的定製,它通過:
[Test]
public void ShouldCreateAControllerUsingSpecimenBuilder()
{
var fixture = new Fixture()
.Customize(new AutoMoqCustomization())
.Customize(new ApiControllerCustomization())
.Customize(new DummyControllerCustomization()); // new customization
fixture.Customizations.Add(new ApiControllerSpecimenBuilder());
var ctl = fixture.Create<DummyController>();
}
public class DummyControllerCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<DummyController>(c => c);
}
}
在這種情況下,SpecimenBuilder似乎無法與DummyController類型了打擊。這個空白的定製是否會使測試通過?它是否會覆蓋標本生成器?但是爲什麼它不拋出同樣的例外,因爲我不告訴他省略任何東西(並且無論如何,我不知道該如何省略......)?
我想我可以使用OmitOnRecursionBehavior
,但我想保持默認行爲以避免所有其他情況下的遞歸,另外我寧願瞭解發生了什麼(或者如果我確實做得很傻)。
完美的問題:我有一次嘗試複製。好工作:) –