gpt4 book ai didi

c# - 在 Justmock 中模拟构造函数调用对于 UrlHelper 失败

转载 作者:太空宇宙 更新时间:2023-11-03 12:38:58 25 4
gpt4 key购买 nike

在 justmock 中,我们可以通过安排构造函数调用来返回模拟实例而不是实际实例

Mock.Arragne(()=>new MyClass(Arg.IsAny<string>())).IgnoreInstance().Returns(Mock.Create<MyClass>());

但是当我尝试对 UrlHelper 类进行同样的操作时,实际类型将被实例化,而不是模拟类型。任何人都可以告诉这是否有任何错误:

网址模型类

    public class UrlModel
{
private UrlHelper url;
public UrlModel()
{
url = new UrlHelper(HttpContext.Current.Request.RequestContext);
}
}

测试方法:

public void UrlTest()
{
Mock.Arrange(() => HttpContext.Current.Request.RequestContext).Returns(Mock.Create<RequestContext>());

var mockedUrl = Mock.Create<UrlHelper>();

Mock.Arrange(() => new UrlHelper(Arg.IsAny<RequestContext>()))
.IgnoreArguments()
.IgnoreInstance()
.Returns(mockedUrl);

//Here url will have actual instance instead of mocked instance
var model = new UrlModel();

//Assert is ommitted for bravity ..
}

最佳答案

您可以使用 Typemock通过伪造 RequestContext 并修改属性行为,在不添加任何新接口(interface)的情况下测试您的代码:

[TestMethod,Isolated]
public void UrlTest()
{
//Arrange
var fakeRequest = Isolate.Fake.Instance<RequestContext>();
Isolate.WhenCalled(() => HttpContext.Current.Request.RequestContext).WillReturn(fakeRequest);

//Act
var res = new UrlModel();
//getting the private field so it can be asserted
var privateField = Isolate.NonPublic.InstanceField(res, "url").Value as UrlHelper;

//Assert
Assert.AreEqual(fakeRequest, privateField.RequestContext);
}

关于c# - 在 Justmock 中模拟构造函数调用对于 UrlHelper 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39787899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com