如何在Android中对Log.e进行单元测试? [英] How to unit test Log.e in android?
问题描述
我需要执行单元测试,当我的应用程序中发生某种情况时,我需要检查是否记录了错误消息.
I need to perform an unit test where I need to check if an error message is logged when a certain condition occurs in my app.
try {
//do something
} catch (ClassCastException | IndexOutOfBoundsException e) {
Log.e(INFOTAG, "Exception "+e.getMessage());
}
我该如何测试?单元测试时出现以下错误.
How can I test this? I am getting the below error while unit testing.
Caused by: java.lang.RuntimeException: Method e in android.util.Log not mocked.
推荐答案
有两种方法可以做到这一点:
There are two ways to do this:
- 您转向Powermock或Powermokito;因为那些模拟框架将允许您模拟/检查对Log.e()的静态调用.
- 您可以考虑替换静态调用.
示例:
interface LogWrapper {
public void e( whatever Log.e needs);
}
class LogImpl implements LogWrapper {
@Override
e ( whatever ) {
Log.e (whatever) ;
}
然后,您必须使用依赖注入在要记录的类中提供一个LogWrapper
对象.对于正常的生产"用法,该对象只是LogImpl
的一个实例.为了进行测试,您可以使用自写的impl(跟踪发送给它的日志);或者您可以使用任何非强大的模拟框架(例如EasyMock或Mokito)对其进行模拟.然后,您可以使用模拟框架的检查/验证方面来检查使用预期参数调用了日志".
And then, you have to use dependency injection to make a LogWrapper
object available within the classes you want to log. For normal "production" usage, that object is simply an instance of LogImpl
; for testing, you can either use a self-written impl (that keeps track of the logs send to it); or you can use any of the non-power mocking frameworks (like EasyMock or Mokito) to mock it. And then you use the checking/verification aspect of the mocking framework to check "log was called with the expected parametes".
请注意:根据您的设置,选项2可能会过大.但就我个人而言,我避免使用Powermock.仅仅是因为我浪费了太多时间来寻找Powermock的怪异问题.而且我喜欢进行覆盖率测量;有时Powermock也会在那给您带来麻烦.
Please note: depending on your setup, option 2 might be overkill. But me, personally, I avoid any usage of Powermock; simply because I have wasted too many hours of my life hunting down bizarre problems with Powermock. And I like to do coverage measurements; and sometimes Powermock gives you problems there, too.
但是,当您询问有关Powermock的信息时,您基本上希望查看此处(powermockito)或此处(powermock).作为记录:下次尝试使用您喜欢的搜索引擎.真的不像您是第一个问这个的人.
But as you are asking about Powermock, you basically want to look here (powermockito) or here (powermock). And for the record: try using your favorite search engine the next time. It is really not like you are the first person asking this.
这篇关于如何在Android中对Log.e进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!