我的控制器中有一个方法,它将属性数据从当前执行的程序集返回到分部视图中。
在这个例子中,我只是拉动标题,但我需要用它做更多的事情。
控制器:
var title = "";
var asm = Assembly.GetExecutingAssembly();
var attrs = asm.GetCustomAttributes(typeof(AssemblyTitleAttribute));
var titleAttr = (AssemblyTitleAttribute)attributes[0];
title = titleAttr.Title;
return PartialView("_Build", title);
在 Moq 中编写单元测试时,我需要找到一种方法将程序集属性注入到模拟中,以便我可以验证在运行控制器测试时是否生成了正确的属性,然后使用我的断言执行 x 或 y 。
单元测试:
//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
我知道这是一组非常简单的代码,但此时我只需要概念证明。
有没有一个好的方法来创建一个假的Assembly?
我需要使用 System.Reflection.Emit 吗?
您可以创建一个虚拟方法,例如GetCustomAttributes
它提供给定类型的属性。然后在你的测试项目中testable类将从控制器类派生并重写此方法。
家庭控制器:
private IDependency _someDependency;
public HomeController(IDependency someDependency)
{
_someDependency = someDependency;
}
public ActionResult MyMethod()
{
var title = "";
var version = "";
IEnumerable<Attribute> attributes = GetCustomAttributes(typeof(AssemblyVersionAttribute)).ToList();
AssemblyVersionAttribute verAttr = attributes.OfType<AssemblyVersionAttribute>().FirstOrDefault();
if (verAttr != null) version = verAttr.Version;
attributes = GetCustomAttributes(typeof(AssemblyTitleAttribute)).ToList();
AssemblyTitleAttribute titleAttr = attributes.OfType<AssemblyTitleAttribute>().FirstOrDefault();
if (titleAttr != null) title = titleAttr.Title;
return PartialView("_Build", title + version);
}
public virtual IEnumerable<Attribute> GetCustomAttributes(Type attributeType)
{
var asm = Assembly.GetExecutingAssembly();
var attrs = asm.GetCustomAttributes(attributeType);
return attrs;
}
Test:
[TestClass]
public class MyMethodTest
{
[TestMethod]
public void MyMethod_WhenCalled_PartialViewIsReturned()
{
// Arrange
// The magic I need to happen.
Mock<IDependency> dependencyStub = new Mock<IDependency>();
// dependencyStub.Setup(...).Returns(...);
var controller = new TestableHomeController(dependencyStub.Object)
{
UseFakeAttributes = true
};
// Act
var result = controller.MyMethod() as PartialViewResult;
// Assert
var model = result.Model;
Assert.AreEqual("MyFakeTitle1.0.0.0", model); // currently static, need to verify against a mock
}
private class TestableHomeController : HomeController
{
public bool UseFakeAttributes { get; set; }
public TestableHomeController(IDependency someDependency)
:base(someDependency)
{ }
public override IEnumerable<Attribute> GetCustomAttributes(Type attributeType)
{
return UseFakeAttributes
? new List<Attribute>
{
new AssemblyTitleAttribute("MyFakeTitle"),
new AssemblyVersionAttribute("1.0.0.0"),
new AssemblyDescriptionAttribute("Assembly fake description")
// next attributes ...
}.Where(a => a.GetType() == attributeType)
: base.GetCustomAttributes(attributeType);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)