使用受保护对象 C# 编写单元测试的好方法是什么(使用 NMock 和 NUnit 框架)
最佳方法是什么
当为包含其他对象的单个类编写单元测试时,使用模拟对象以避免依赖于其他类的测试的
。 示例 1:
public class MyClass
{
protected MyObject _obj;
public MyClass()
{
_obj = new MyObject();
}
public object DoSomething()
{
//some work
_obj.MethodCall();
//more work;
return result;
}
}
我不想公开受保护的值来为代码创建单元测试。 包装类可以
用于测试,但是有更好的方法吗?
示例 2:
public class MyClass
{
public object DoSomething()
{
//some work
MyObject obj = new obj(parameters);
_obj.MethodCall(Method1);
//more work;
return result;
}
public int Method1()
{ ... }
}
与上面的示例类似,但对象是在我调用的方法中创建的。
示例3:
public class MyClass
{
public object DoSomething()
{
//some work
obj.MethodCall(Method1);
//more work;
return result;
}
public int MethodA()
{ ... }
}
当MethodA仅用作委托时,有没有办法测试它?
When writeing unit tests for a single class that contains other objects what's the best way to use
mock objects to avoid tests dependant on other classes.
Example 1:
public class MyClass
{
protected MyObject _obj;
public MyClass()
{
_obj = new MyObject();
}
public object DoSomething()
{
//some work
_obj.MethodCall();
//more work;
return result;
}
}
I'd rather not expose the protected value to create a unit test for the code. A wrapper class would
work for testing but is there a better way?
Example 2:
public class MyClass
{
public object DoSomething()
{
//some work
MyObject obj = new obj(parameters);
_obj.MethodCall(Method1);
//more work;
return result;
}
public int Method1()
{ ... }
}
Similar to the above example but the ojbect is created in the method I am calling.
Example 3:
public class MyClass
{
public object DoSomething()
{
//some work
obj.MethodCall(Method1);
//more work;
return result;
}
public int MethodA()
{ ... }
}
Is there a way to test MethodA when it is only used as a delegate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议您看一下依赖注入。 一件事是使用模拟对象,但除非您使用像 TypeMock 这样的东西,它基本上可以让您动态修改代码,否则您希望有一种方法来注入您的类所依赖的实例(如果您想摆脱依赖关系。 因此,在示例 1 中,我建议您可以让调用者提供该实例,而不是在构造函数中新建 MyObject 实例。 在这种情况下,您可以轻松地将其替换为模拟甚至存根。
I recommend that you take a look at dependency injection. One thing is using mock objects, but unless you're using something like TypeMock, which basically lets you modify you code on the fly, you want to have a way to inject the instances your class depends on if you want to get rid of the dependencies. So in examples 1, I would suggest that instead of newing an instance of MyObject in the constructor, you could have the caller supply that instance. In that case you would easily by able to replace it with a mock or even a stub.
您是否尝试过从 MyClass 派生 UTMyClass ?
Have you tried deriving a UTMyClass from MyClass?