什么是单元测试范围?
我相信单元测试的有用性,但我真的不明白这些规则。
如果我有一个类与另一个类链接,则
public class MyClass
{
private SecondClass MySecondClass;
public MyClass()
{
this.MySecondClass = new SecondClass ();
}
}
该字段是私有的,并且 Myclass 有一个这样的方法:
public ThirdClass Get()
{
return this.MySecondClass.Get();
}
我如何测试这个?我假设我必须测试 MyClass.get()
方法是否可以很好地调用 MySecondClass.Get()
!但我无法模拟 SecondClass
并将其分配给第一个,因为它是一个私有字段..所以我真的想知道如何测试它..
谢谢
I am persuaded of usefulness of unit tests but I really don't understand rules for these ones..
If I have a class linked with another
public class MyClass
{
private SecondClass MySecondClass;
public MyClass()
{
this.MySecondClass = new SecondClass ();
}
}
the field is private, and the Myclass have a method like this:
public ThirdClass Get()
{
return this.MySecondClass.Get();
}
How can I test this?? I assume I have to test if the MyClass.get()
method is well calling MySecondClass.Get()
! But I can't make a mock of SecondClass
and assign it to the first one because it is a Private field.. So I really wonder how is possible to test this..
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法轻松对其进行单元测试,因为实例化是硬编码的。您可以在可以模拟它的地方使用构造函数注入:
现在在单元测试中您可以提供您喜欢的此类的任何实例。这就是控制反转的原理。类不再负责实例化其依赖项,而是传递依赖项的那些类的使用者。
You cannot easily unit test this because the instantiation is hardcoded. You could use constructor injection where you could mock it:
Now in your unit test you could supply any instance of this class you like. That's the principle of Inversion of Control. Classes are no longer responsible for instantiating its dependencies, its the the consumer of those classes that passes the dependencies.