C#:如何对依赖于同一类中的另一个方法的方法进行单元测试?

时间:2011-01-07 22:20:59

标签: c# unit-testing visual-studio-2010 mocking

我有一个类似于以下的类:

public class MyProxy : ClientBase<IService>, IService
{
    public MyProxy(String endpointConfiguration) :
        base(endpointConfiguration) { }

    public int DoSomething(int x)
    {
        int result = DoSomethingToX(x); //This passes unit testing

        int result2 = ((IService)this).DoWork(x)

        //do I have to extract this part into a separate method just
        //to test it even though it's only a couple of lines?
        //Do something on result2
        int result3 = result2 ...

        return result3;
    }

    int IService.DoWork(int x)
    {
        return base.Channel.DoWork(x);
    }
}

问题在于,在测试时我不知道如何模拟result2项而不将使用result2获取result3的部分提取到单独的方法中。并且,因为它是单元测试,所以我不想深入测试result2返回的结果...我宁愿以某种方式模拟数据......比如,能够调用函数并替换它一个电话。

5 个答案:

答案 0 :(得分:3)

您是否偏爱模拟框架?

Partial Mock中的Rhino Mocks功能似乎应该可以满足您的需求。

答案 1 :(得分:2)

你真的不能这样做。你有三个选择:

  • 子类MyProxy并覆盖DoWork,这需要一些摆弄来取悦编译器
  • 模拟Channel属性,这将要求它可在基类
  • 中设置
  • 将DoWork移到另一个类中,在构造函数中传递Channel,并在测试中模拟它

答案 2 :(得分:1)

执行以下操作:

设置IService属性,例如:

public IService MyService { get; set; }

然后您可以执行:int result2 = MyService.DoWork(x)只要构造函数中的某个位置或您设置的任何内容MyService = this;

如果您不想公开该属性,可以将其设置为私有或其他任何内容,并使用访问器对其进行测试。

答案 3 :(得分:0)

您可以使用最新的Microsoft Research项目Moles

来完成此操作

运行后,您可以执行以下操作

MMyProxy.DoWork32 = () => put your mock result here.

请记住将moleBehavior设置为未通过方法的直通。

答案 4 :(得分:0)

我相信你有一个设计问题,你的IService.DoWork应该很可能生活在另一个类中,它看起来只是一个其他东西的薄包装。你考虑过重构吗?

然后,如果它存在于另一个类中,则不需要任何特殊处理来进行模拟。