问题
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.
回答1:
There are two ways to do this:
- You turn to Powermock or Powermokito; as those mocking frameworks will allow you to mock/check that static call to Log.e().
- You could consider replacing the static call.
Example:
interface LogWrapper {
public void e( whatever Log.e needs);
}
class LogImpl implements LogWrapper {
@Override
e ( whatever ) {
Log.e (whatever) ;
}
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".
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.
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.
来源:https://stackoverflow.com/questions/38863913/how-to-unit-test-log-e-in-android