[英]C# Reflection: Replace a referenced assembly
我目前正在為 MutationTesting 編寫一個框架。 代碼幾乎是完整的,但有一點(花了半天時間)我無法弄清楚:
通過反射我想執行一個方法“TestMethod”,它位於 class“TestClass”中。 “TestClass”所在的項目引用了一個組件,我們稱之為“Proband.dll”。
“TestMethod”在 Proband.dll 中創建某種類型的 object 並在該 object 上執行方法。
為了澄清一點:TestClass - 是一個包含單元測試的 class。 TestMethod - 是一個單一的單元測試。 Proband.dll - 包含要測試的方法/類。
在執行TestMethod之前,我已經成功地對Proband.dll進行了拆解、變異和重組。 所以現在我有一個新的“Proband.dll”,它將由 TestClass 代替!
問題是 TestClass 已經在執行中。 我在想是否可以創建一個 AppDomain,其中將加載新的 Proband.dll,並在新的 AppDomain 中執行 TestMethod。
我已經創建了這個 AppDomain 並成功地將新的 Proband.dll 加載到其中,但是,我不知道如何在這個新的 AppDomain 中執行 TestMethod。 另外我不知道這是否會“取代”舊的 Proband.dll 用於測試方法。
這是我的測試類:
[TestClass()]
public class TestClass
{
[TestInitialize()]
public void MyTestInitialize()
{
// code to perform the mutation.
// From here, the "TestMethod" should be called with
// the new "Proband.dll".
}
[TestMethod()]
public void TestMethod()
{
// test code calling into Proband.dll
}
}
有誰知道如何實現這一目標? 或者任何線索或關鍵字?
謝謝,克里斯蒂安
這可能是矯枉過正,但看看我的答案:
您需要在已加載 Proband.dll 的 AppDomain 中創建TestClass
,並使用MarshalByRef
將 class 保留在 AppDomain 中(以便稍后卸載它)。
這是關於我所做的更多信息(不准確,因為我正在對其進行更改以匹配您需要的更多內容)。
// Create Domain
_RemoteDomain = AppDomain.CreateDomain(_RemoteDomainName,
AppDomain.CurrentDomain.Evidence,
AppDomain.CurrentDomain.BaseDirectory,
AppDomain.CurrentDomain.BaseDirectory,
true);
// Load an Assembly Loader in the domain (mine was Builder)
// This loads the Builder which is in the current domain into the remote domain
_Builder = (Builder)_RemoteDomain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().FullName, "<namespace>.Builder");
_Builder.Execute(pathToTestDll)
public class Builder : MarshalByRefObject
{
public void Execute(string pathToTestDll)
{
// I used this so the DLL could be deleted while
// the domain was still using the version that
// exists at this moment.
Assembly newAssembly = Assembly.Load(
System.IO.File.ReadAllBytes(pathToTestDll));
Type testClass = newAssembly.GetType("<namespace>.TestClass",
false, true);
if (testClass != null)
{
// Here is where you use reflection and/or an interface
// to execute your method(s).
}
}
}
這應該為您提供所需的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.