【问题标题】:Generate a stub or mocking a method in .NET在 .NET 中生成存根或模拟方法
【发布时间】:2013-02-24 03:03:33
【问题描述】:

我正在编写一个执行如下逻辑的单元测试:

SomeObject obj1 = new SomeObject();
obj1.SomeMethod(args);

内部SomeMethod

public void SomeMethod(*Some Args*){     
    AnotherObject obj2 = new AnotherObject();
    Obj2.OtherMethod();
}

在我的测试中,我并不关心 Obj2.OtherMethod() 的真正作用,我希望测试忽略它。所以我认为生成一个存根会为我解决这个问题,但我不知道该怎么做。

【问题讨论】:

  • 您看过 Moq 或 RhinoMocks 吗?听起来你想模拟 Obj2。

标签: .net unit-testing testing stub


【解决方案1】:

这是一种方法。如果您有一个由 AnotherObject 实现的接口(例如,IAnother,它至少具有 AnotherMethod 作为方法),您的正常执行路径会将 AnotherObject 的实例传递给 SomeMethod。

然后为了进行测试,您可以传递一个实现 IAnother 接口的模拟对象 - 通过使用模拟框架或自己编写一个。

所以你有:

Public void SomeMethod(IAnother anotherObject)
{     
  anotherObbject.OtherMethod();
}

Public class MyMock : IAnother...

用于测试 -

IAnother another = new MyMock();
..SomeMethod(myMock)

但在实际代码中

IAnother = new AnotherObject()...

你明白了。

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 2021-02-09
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 2012-06-11
    • 1970-01-01
    相关资源
    最近更新 更多