mercredi 26 août 2015

How to inject a mock Assembly for use with Moq

There is a method in my controller that returns attribute data from the current executing assembly into a partial view.

In this example, I'm merely pulling the Title, but I need to do more with it.

Controller:

    var title = "";

    var asm = Assembly.GetExecutingAssembly();
    var attrs = asm.GetCustomAttributes(typeof(AssemblyTitleAttribute));
    var titleAttr = (AssemblyTitleAttribute)attributes[0];

    title = titleAttr.Title;

    return PartialView("_Build", version);

When writing the unit test in Moq, I need to find a way to inject the Assembly attributes into a mock so that I can verify that the correct attributes are being generated when I run the controller test, and then do x or y with my asserts.

UnitTest:

    //Arrange
    //The magic I need to happen.

    //Act
    var controller = GetController();
    var result = controller.MyMethod() as PartialViewResult;
    var title = result.Model;

    //Assert
    Assert.AreEqual("Title", title); //currently static, need to verify against a mock

I know this is an extremely simple set of code, but I just need proof of concept at this point.

Is there a good way to create a fake Assembly? Do I need to use System.Reflection.Emit?

Aucun commentaire:

Enregistrer un commentaire