如何测试这部分代码
您好,我正在编写 junit 测试,如何测试此方法..这只是此方法的一部分:
public MyClass{
public void myMethod(){
List<myObject> list = readData();
}
}
我将如何对此进行测试? ReadData 是 MyClass 中的私有方法吗?
Hello I'm writting junit test how can I test this method .. this is only part of this method :
public MyClass{
public void myMethod(){
List<myObject> list = readData();
}
}
How will I make the test for this? ReadData is a private method inside MyClass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如所写,测试
myMethod()
没有意义,除非readData()
按照 Frank Grimm 提到的方式更改实例状态。要做的一件事是更改myMethod()
,以便将list
放入List
实例变量中。然后您可能会这样做:您仍然需要编写
MyClass.getList()
来返回List
实例变量。为了保持健壮性,您可以使
MyClass
构造函数接受一个实现IMyReadInterface
等接口的对象。readData()
将使用该对象。然后在测试中,您可以实例化一个也实现IMyReadInterface
的模拟,配置该模拟以提供所需的数据,以便readData()
正常工作,并构造inst
与该模拟。As written, it doesn't make sense to test
myMethod()
unlessreadData()
changes the instance state the way Frank Grimm mentioned. One thing to do would be to changemyMethod()
so that it putslist
into aList
instance variable. Then you might do something like this:You'd still have to write
MyClass.getList()
to return theList
instance variable.To be robust, you could make the
MyClass
constructor accept an object that implements an interface likeIMyReadInterface
.readData()
would use that object. Then in your test, you could instantiate a mock that also implementsIMyReadInterface
, configure the mock to provide the data needed so thatreadData()
works correctly, and constructinst
with that mock.除非我们更多地了解该方法,否则您真正需要测试的是 readData 返回的格式是否适合您的通用列表。否则,如果不了解您的私有方法中发生的情况,就很难推荐任何东西。
Unless we know more about the method, all you really need to test is that the return from readData is in a format that fits into your generic list. Otherwise, its hard to recommend anything without knowing more about whats going on in your private method.
您始终可以测试 List 对象以查看它是否包含 readData() 应该插入到列表中的所有元素。创建一个返回列表的公共方法,您可以将该列表中的长度和元素与您期望的长度和元素进行比较。
You can always test the List object to see if it contains all of the elements that readData() is supposed to insert into the list. Make a public method that returns the list and you can compare the length and elements in that list to what you are expecting to be in there.