ASP.NET MVC3でValueProviderFactoriesを単位テストする方法は?
-
25-09-2019 - |
質問
プロジェクトをASP.NET MVC 2から3にアップグレードしたかったのですが、ほとんどのテストが成功しましたが、失敗したものがあります。 ValueProviderFactories.Factories.GetValueProvider(context)
.
これは、問題を解明する簡単なテストクラスです。
[TestFixture]
public class FailingTest
{
[Test]
public void Test()
{
var type = typeof(string);
// any controller
AuthenticationController c = new AuthenticationController();
var httpContext = new Mock<HttpContextBase>();
var context = c.ControllerContext = new ControllerContext(httpContext.Object, new RouteData(), c);
IModelBinder converter = ModelBinders.Binders.GetBinder(type);
var bc = new ModelBindingContext
{
ModelName = "testparam",
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, type),
ValueProvider = ValueProviderFactories.Factories.GetValueProvider(context)
};
Console.WriteLine(converter.BindModel(context, bc));
}
}
例外「オブジェクト参照はオブジェクトのインスタンスに設定されていません。」いつ投げられます ValueProviderFactories.Factories.GetValueProvider(context)
呼ばれています。 Stacktraceは次のようになります:
Microsoft.Web.Infrastructure.dll!Microsoft.Web.Infrastructure.DynamicValidationHelper.ValidationUtility.CollectionReplacer.GetUnvalidatedCollections(System.Web.HttpContext context) + 0x23 bytes
Microsoft.Web.Infrastructure.dll!Microsoft.Web.Infrastructure.DynamicValidationHelper.ValidationUtility.GetUnvalidatedCollections(System.Web.HttpContext context, out System.Collections.Specialized.NameValueCollection form, out System.Collections.Specialized.NameValueCollection queryString, out System.Collections.Specialized.NameValueCollection headers, out System.Web.HttpCookieCollection cookies) + 0xbe bytes
System.Web.WebPages.dll!System.Web.Helpers.Validation.Unvalidated(System.Web.HttpRequest request) + 0x73 bytes
System.Web.WebPages.dll!System.Web.Helpers.Validation.Unvalidated(System.Web.HttpRequestBase request) + 0x25 bytes
System.Web.Mvc.DLL!System.Web.Mvc.FormValueProviderFactory..ctor.AnonymousMethod__0(System.Web.Mvc.ControllerContext cc) + 0x5a bytes
System.Web.Mvc.DLL!System.Web.Mvc.FormValueProviderFactory.GetValueProvider(System.Web.Mvc.ControllerContext controllerContext) + 0xa0 bytes
System.Web.Mvc.DLL!System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider.AnonymousMethod__7(System.Web.Mvc.ValueProviderFactory factory) + 0x4a bytes
System.Core.dll!System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Web.Mvc.ValueProviderFactory,<>f__AnonymousType2<System.Web.Mvc.ValueProviderFactory,System.Web.Mvc.IValueProvider>>.MoveNext() + 0x24d bytes
System.Core.dll!System.Linq.Enumerable.WhereSelectEnumerableIterator<<>f__AnonymousType2<System.Web.Mvc.ValueProviderFactory,System.Web.Mvc.IValueProvider>,System.Web.Mvc.IValueProvider>.MoveNext() + 0x2ba bytes
mscorlib.dll!System.Collections.Generic.List<System.Web.Mvc.IValueProvider>.List(System.Collections.Generic.IEnumerable<System.Web.Mvc.IValueProvider> collection) + 0x1d8 bytes
System.Core.dll!System.Linq.Enumerable.ToList<System.Web.Mvc.IValueProvider>(System.Collections.Generic.IEnumerable<System.Web.Mvc.IValueProvider> source) + 0xb5 bytes
System.Web.Mvc.DLL!System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(System.Web.Mvc.ControllerContext controllerContext) + 0x24d bytes
test.DLL!FailingTest.Test() Line 31 + 0xf9 bytes C#
私はそれが例外を投げて見た理由を知りたかった:
public static ValidationUtility.UnvalidatedCollections GetUnvalidatedCollections(HttpContext context)
{
return (ValidationUtility.UnvalidatedCollections) context.Items[_unvalidatedCollectionsKey];
}
だから、私たちが頼っていたときに私たちは過去に戻っていますか HttpContext.Current
?それを回避する方法は?
解決
これは、httpcontextにアクセスするprox-ing valueprovidersによって、それを無視するものに簡単に解決できます。
ブログ投稿ですべてを説明しました。 ASP.NET MVC3のValueProviderFactoriesを使用した単体試験アクション.
重要なのはこのコードです:
public static class ValueProviderFactoresExtensions {
public static ValueProviderFactoryCollection ReplaceWith<TOriginal>(this ValueProviderFactoryCollection factories, Func<ControllerContext, NameValueCollection> sourceAccessor) {
var original = factories.FirstOrDefault(x => typeof(TOriginal) == x.GetType());
if (original != null) {
var index = factories.IndexOf(original);
factories[index] = new TestValueProviderFactory(sourceAccessor);
}
return factories;
}
class TestValueProviderFactory : ValueProviderFactory {
private readonly Func<ControllerContext, NameValueCollection> sourceAccessor;
public TestValueProviderFactory(Func<ControllerContext, NameValueCollection> sourceAccessor) {
this.sourceAccessor = sourceAccessor;
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext) {
return new NameValueCollectionValueProvider(sourceAccessor(controllerContext), CultureInfo.CurrentCulture);
}
}
}
したがって、次のように使用できます。
ValueProviderFactories.Factories
.ReplaceWith<FormValueProviderFactory>(ctx => ctx.HttpContext.Request.Form)
.ReplaceWith<QueryStringValueProviderFactory>(ctx => ctx.HttpContext.Request.QueryString);
実際にはとても簡単でした:)
アップデート: :コメントで述べたように、あなたは覚えておくべきです:
- 設定
ctx.HttpContext.Request.ContentType
nullの価値がないプロパティ、それ以外の場合は、jsonvalueproviderFactoryが例外をスローします。モックを作成し、そこにデフォルト値を設定することを好みます。 - を交換します
HttpFileCollectionValueProviderFactory
結合中に使用できるため。 - プロジェクトにある他の依存関係に注意してください。
他のヒント
valueProviderFactories.Factories、ModelBinders.Binders、または単体テスト内からその他の静的アクセターを呼び出すべきではありません。それがまさにModelBindingContext.ValueProviderが存在する理由です。そのため、静的デフォルトに依存するのではなく、独自の作成のモックされたiValueProviderを提供できるようにします(MVCパイプラインが実行されていると仮定)。