Wie verwende ich Moq, um eine MEF-Importabhängigkeit für Komponententests zu erfüllen?

Das ist meine Schnittstelle

<code>public interface IWork
{
    string GetIdentifierForItem(Information information);
}
</code>

und meine Klasse

<code>public class A : IWork
{
[ImportMany]
public IEnumerable<Lazy<IWindowType, IWindowTypeInfo>> WindowTypes { get; set; }

public string GetIdentifierForItem(Information information)
{
    string identifier = null;
    string name = information.TargetName;

    // Iterating through the Windowtypes 
    // searching the 'Name' and then return its ID  
    foreach (var windowType in WindowTypes)
    {
        if (name == windowType.Metadata.Name)
        {
            identifier = windowType.Metadata.UniqueID;
            break;
        }
    }
    return identifier;
}
}
</code>

Problem : Ich möchte die Methode in einer Einheit testenGetIdentifierForItem

Folgendes habe ich versucht, um es zu lösen:

(1) Erstellen Sie einen Lazy-Mock, und legen Sie die Werte fest, die für die Rückgabe von property gets erforderlich sind

var windowMock = new Mock<Lazy<IWindowType, IWindowTypeInfo>>(); windowMock.Setup(foo => foo.Metadata.Name).Returns("Data"); windowMock.Setup(foo => foo.Metadata.UniqueID).Returns("someString");

(2) Erstellen Sie eine Fenstertypenliste und das oben genannte verspottete Objekt und setzen Sie es dann auf das erstellte A-Objekt

<code>var WindowTypesList = new List<IWindowType, IWindowTypeInfo>>();
WindowTypesList.Add(windowMock.Object);
A a = new A();
a.WindowTypes = WindowTypesList;
</code>

(3) Erstellen Sie das Informationsmodell

<code>var InfoMock = new Mock<Information>();
InfoMock.Setup(foo => foo.TargetName).Returns("Data");
</code>

Um alle oben genannten Punkte als Einheitentest zusammenzufassen

<code>[TestMethod]
public void GetIDTest()
{
    var windowMock = new Mock<Lazy<IWindowType, IWindowTypeInfo>>();
    windowMock.Setup(foo => foo.Metadata.Name).Returns("Data");
    windowMock.Setup(foo => foo.Metadata.UniqueID).Returns("someString");

    var WindowTypesList = new List<Lazy<IWindowType, IWindowTypeInfo>>();
    WindowTypesList.Add(windowMock.Object);

    A a = new A();
    a.WindowTypes = WindowTypesList;
    var InfoMock = new Mock<Information>();
    InfoMock.Setup(foo => foo.TargetName).Returns("Data");

    string expected = "someString"; // TODO: Initialize to an appropriate value
    string actual;
    actual = a.GetIdentifierForItem(InfoMock.Object);
    Assert.AreEqual(expected, actual);

}
</code>

Dieser Komponententest kann nicht ausgeführt werden und löst die Ausnahme 'TargetInvocationException' aus. Es sieht so aus, als würde ich etwas tun, was ich nicht tun sollte.

Aber ich bin nicht sicher, wie ich es anders machen soll. Ich habe einige der Links in der Kurzanleitung von Moq gelesen. Ich weiß, dass mir etwas fehlt. Können Sie mir helfen, indem Sie Anleitungen zum Testen dieser Einheit geben?

Antworten auf die Frage(2)

Ihre Antwort auf die Frage