包装类的 Junit 测试用例
我有一个 Java 类,它只是扩展一个库类并使用默认参数调用其父类的方法。 我该如何为此编写 Junit 测试? MockObjectTestCase 也很好。 这是我正在谈论的示例:
public class ResourceBundleMessageSource {
public String getMessage(String key, Object[] objects, Locale locale) {
//Spring library method
}
}
public class MessageResource extends ResourceBundleMessageSource {
public String getMessage(String key) {
return (getMessage(key, null, Locale.getDefault());
}
}
我知道包装器方法甚至不是必需的,但可以更轻松地频繁调用它。 请注意,该类运行良好,我只对单元测试的编写方式感兴趣。
I have a Java class that simply extends a library class and calls a method of its parent with a default parameter. How do I write a Junit test for that? A MockObjectTestCase is good too. Here is an example of what I'm talking about:
public class ResourceBundleMessageSource {
public String getMessage(String key, Object[] objects, Locale locale) {
//Spring library method
}
}
public class MessageResource extends ResourceBundleMessageSource {
public String getMessage(String key) {
return (getMessage(key, null, Locale.getDefault());
}
}
I know the wrapper method isn't even necessary, but makes frequent calls to it easier. Note the class works fine, I'm only interested in how the unit test is written.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您愿意稍微重构您的类,我建议将
MessageResource
委托给MessageSource
实例,而不是扩展ResourceBundleMessageSource
。 然后我会在单元测试中使用模拟。 像这样的事情:和单元测试
If you would be willing to refactor your class slightly, I would recommend
MessageResource
delegate to aMessageSource
instance, rather than extendResourceBundleMessageSource
. Then I'd use mocks in my unit test. Something like this:and unit test
对于这个特定的例子,我可能不会费心去测试它。
如果您确实需要测试它,请尝试以下操作:
如果前两行很难写,那么不测试它更有意义。
如果您有多个这样的测试,请将前两行移至设置夹具中。
For this particular example I probalby would not bother to test it.
If you do need to test it, try something like:
If the first two lines are hard to write, then it makes even more sense not to test it.
If you have several tests like this, move the first two lines into a setup fixture.
我认为甚至不值得为此编写单元测试。 如果已经有对 ResourceBundleMessageSource.getMessage() 的测试,那么这应该足够好了。
I don't think it's even worth writing a unit test for that. If there's already a test for ResourceBundleMessageSource.getMessage(), then that should be good enough.