鉴于我有一个控制器类:
public class ResourceController : AuthorizedController
{
public virtual string Resource()
{
//do magic
}
public virtual string ResourceParent()
{
var url = Resource();
return url;
}
}
}
使用测试工具:
[Subject(typeof (ResourceController))]
public class When_I_want_the_parent_resource : WithSubject<ResourceController>
{
private static readonly string ParentUrl = "/organizations/1";
private static readonly string ResourceUrl = "/organizations/1/contacts/1";
private static string _result;
private Establish context = () =>
{
The<ResourceController>()
.WhenToldTo(x => x.Resource())
.Return(ResourceUrl);
};
private Because of = () => _result = Subject.ResourceParent();
private It should_match_the_expected_parent_url = () =>
_result.ShouldEqual(ParentUrl);
}
此单元测试将失败,因为 Subject.ResourceParent() 将返回 null,因为 Machine.Fakes 已自动模拟此方法。作为临时解决方法,我刚刚从 ResourceParent 中删除了 virtual 关键字,以便能够测试我的代码。我认为必须有一个真正的解决方案让我告诉 Machine.Fakes 不要覆盖ResourceParent()