使用VS2010进行单元测试

时间:2011-12-10 13:19:54

标签: c# asp.net visual-studio-2010 unit-testing mstest

我正在测试方法,如ABC(),如

myclass target = new myclass();
target.ABC();

这个ABC()方法又从另一个类anotherclass.XYZ()调用另一个方法XYZ(),这个XYZ()方法的输入参数依赖于文本框中的值。

因为在测试运行时没有传递textbox的值,所以在运行测试时我得到一个null引用异常(我的意思是测试失败,异常)。

类似情况(另一种​​):方法从查询字符串中提取id值,如

HttpContext context
id = context.request.querystring["id"]

因为,在测试运行时,这个id值为null,我得到一个null引用异常(我的意思是测试失败,异常)。

根据我的理解,逻辑上这是正确的,因为这是测试运行而不是实际运行但仍想确认一次......

我做错了吗?

OR

我的测试运作正常吗?

请建议。感谢您的帮助。

感谢。

2 个答案:

答案 0 :(得分:1)

您需要使用anotherclass的“非实际”实例,但需要使用假XYZ实现Mocked实例。

我将以Moq框架为例。

Mock<IAnotherclass> anotherClassMock= new Mock<IAnotherclass>();//create mock instanse
anotherClassMock.Setup(x=>x.XYZ);//add .Returns(something) if method XYZ returns some value
myclass target = new myclass(anotherClassMock.Object);//create instance of object under test with fake instance of anotherClassMock
target.ABC();
anotherClassMock.Verify(x=>x.XYZ);//verify that method XYZ is actualy been called

首先,您需要提取类anotherclass的接口以创建Mock。在我的示例中,我使用了接口IAnotherclass

为什么我们这样做?我们没有强调类anotherclass的逻辑。我们认为它是正确的。所以我们从中抽象出来并只测试myclass的逻辑。而且我们只是非常非常地调用了XYZ方法。

答案 1 :(得分:1)

我不知道您的代码是什么样的,但可能需要进行一些重构才能进行单元测试。

例如,如果你有这样的代码:

MyClass{

  private AnotherClass _another = new AnotherClass();

  public string ABC(){
    return _another.XYZ();
  }
}

public AnotherClass{
  //Context comes from somewhere...
  public string XYZ(){
    return context.request.querystring["id"]
  }
}

您可能希望将其更改为以下内容:

interface IAnotherClass{
  string XYZ();
}

MyClass{  
  private IAnotherClass _another = new AnotherClass();

  public MyClass(IAnotherClass anotherClass){
    _another = anotherClass;
  }

  public string ABC(){
    return _another.XYZ();
  }
}

public AnotherClass: IAnotherClass{
  //Context comes from somewhere...
  public string XYZ(){
    return context.request.querystring["id"]
  }
}

然后,您可以使用模拟框架来模拟IceN已经显示的IAnotherClass。至于HttpContext - 变得有点复杂,但是如果它只被AnotherClass使用,你就不需要模拟它,因为模拟对象只会返回你喜欢的任何东西。显然,当你来测试AnotehrClass时,它就成了一个问题。如果你发现你确实需要模拟它,那么有很多例子可以做 - 例如this一个。