問題:運行單元測試時,類中Application.Current爲null。使用AppDomain爲單元測試提供應用程序調度程序
解決方法:創建一個將運行我的測試類的應用程序域。應用程序域將爲我的測試類提供調度程序。
代碼例如:
MyClassInTheAssembly myClass;
string path = @"C:\\pathToTheDll\\MyAssembly.dll";
path = path.Replace(@"\\", @"\");
AppDomainSetup setup = new AppDomainSetup { PrivateBinPath = path };
AppDomain domain = AppDomain.CreateDomain("MyDomain", null, setup);
myClass = (MyClassInTheAssembly)domain.CreateInstanceFromAndUnwrap(path, typeof(MyClassInTheAssembly).FullName);
的myClass的對象可被用於單元測試使用Application.Current.Dispatcher任何公共方法。
我上myClass的執行單元測試時收到以下錯誤:上式
構造'MyAssembly.MyClassInTheAssembly找不到。
調用domain.CreateInstanceFromAndUnwrap()方法創建我的測試類的實例時會生成此錯誤。
MyClassInTheAssembly構造函數有兩個必需的參數。是否有可能創建一個具有參數的類的AppDomain實例?
UPDATE 感謝user779967指着我在正確的方向。上面我的問題的答案是使用AppDomain.CreateInstanceFromAndUnwrap()的方法重寫。 我嘗試使用方法重寫創建我的測試類使用的AppDomain的實例:
object[] parameters = new object[2]; // object array to pass my required parameters.
parameters[0] = container; // Required constructor param for myClass.
parameters[1] = eventAggregator; // Required constructor param for myClass.
myClass = (MyClassInTheAssembly)domain.CreateInstanceFromAndUnwrap(path, typeof(MyClassInTheAssembly).FullName, true, BindingFlags.Default, null, parameters, null, null);
當時的想法是使用此方法重寫通過我所需要的參數,以我的測試類的實例。然後我可以使用派生自AppDomain的測試類,它爲我的所有單元測試提供一個調度程序線程。
執行此代碼時,我收到以下SerializationException:類型未解析用於成員'Castle.DynamicProxy.Serialization.ProxyObjectReference,NSubstitute,Version = 1.6.1.0,Culture = neutral,PublicKeyToken = 92dd2e9066daa5ca'。這是因爲我需要使用NSubstitute來測試我的容器和eventaggregator類。 AppDomain方法正在爲我的構造函數參數類型尋找IUnityContainer和IEventAggregator的精確參數類型匹配,而不是NSubstitute。
我放棄了我嘗試使用AppDomain實例化我的測試類進行單元測試。我決定把我的測試類方法中處理Application.Current如下:
var dispatcher = Application.Current != null ? Application.Current.Dispatcher : Dispatcher.CurrentDispatcher;
if (dispatcher.CheckAccess())
{
do something....
}
else dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => CallMethodAgain()));
當運行我的生產代碼,Application.Current不應該爲空。在運行我的代碼進行單元測試時,我使用Dispatcher.CurrentDispatcher從執行線程創建調度程序。
如果有人使用AppDomain實例化單元測試的類,我很樂意看到它!
非常感謝。這個提示指向了我正確的方向。在我的原始問題中查看我的更新。 – EnLaCucha