asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了asp.net-mvc – 我如何moq aingleingleResult?我是不是该?还是有更好的方法?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的控制器中有一个这样的动作方法
public ActionResult Index()
{
    using (NorthwindDataContext db = new NorthwindDatacontext())
    {
        var results = db.GetRecordSets(arg1,....).ToList();
        // use results as list
    }

    return View();
}

我想开始为它做测试(是的,在它构建之后,而不是之前……但代码是在我开始使用TDD之前编写的……)

我发现在控制器中添加这样的属性

public delegate NorthwindDatacontext ContextBuilderDelegate();

public ContextBuilderDelegate ContextBuilder { get; set; }

我可以在构造函数中添加这样的东西……

ContextBuilder = () => new NorthwindDatacontext();

然后我可以测试ActionMethod设置ContextBuilder属性与模拟NorthwindDatacontext

var controller              = new MyController();
var mockDataContext         = new mock<NorthwindDatacontext>();
controller.ContextBuilder   = () => mockDataContext.object;

但是……我发现无法使用它,因为NorthwindDatacontext的所有方法都使用ISingleResult作为returnType,我无法找到使用该接口创建对象的方法.
我试过这个

var theResult                  = new List<GetRecordSetsResult>();
// fill the data structure here with the provided result...

mockDataContext.Setup(c => c. GetRecordSets()).Returns(theResult as
                                            ISingleResult<GetRecordSetsResult>);

但它不起作用,因为转换为ISingleResult时,theResult为null.

有没有办法创建一个ISingleResult对象来测试这种方式,或者我正在做错误的方式在这里做事情?

提前致谢

解决方法

我创建了一个实现ISingleResult的类,只是在其中放入一个List.我对这种类型的编码还是比较陌生的,所以然这对我有用,但使用风险自负(如果你看到评论后漏洞).
class SingleResult<T>:ISingleResult<T>
{
    readonly List<T> _list = new List<T>();

    public void Add(T item)
    {
        _list.Add(item);
    }

    #region Interface Items

    public IEnumerator<T> GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public object ReturnValue { get { return _list; } }

    public void Dispose() { }

    #endregion
}

然后可以使用它来返回模拟的一部分.这就是我最终将它与Rhino mocks一起使用的方法:

[TestMethod]
public void TestSomething()
{
    //Arrange
    // Make a data context and DAL
    var _ctx = mockRepository.Generatemock<IDataClassesDataContext>();
    var someDALClass = new SomeDALClass(_ctX);

    User testuser = UserObjectHelper.Testuser();
    SingleResult<User> userList = new SingleResult<User> { testuser };

    // InDicate that we expect a call the to sproc GetUserByUserID
    _ctx.Expect(x => x.GetUserByUserID(testuser.UserID)).Return(userList);

    //Act
    someDALClass.updateUser(testuser);

    //Assert
    Assert.IsTrue(SomeTESTCondition());
}

大佬总结

以上是大佬教程为你收集整理的asp.net-mvc – 我如何moq aingleingleResult?我是不是该?还是有更好的方法?全部内容,希望文章能够帮你解决asp.net-mvc – 我如何moq aingleingleResult?我是不是该?还是有更好的方法?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。