Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent DebugLog logs messages when running code under JUnit. #30

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package com.fernandocejas.frodo.internal;

import android.util.Log;
import java.util.Arrays;
import java.util.List;

/**
* Wrapper around {@link android.util.Log}
*/
class DebugLog {
private Boolean runningJUnit;

DebugLog() {
}
Expand All @@ -18,6 +21,28 @@ class DebugLog {
* @param message The message you would like logged.
*/
public void log(String tag, String message) {
Log.d(tag, message);
if (!runningJUnit())

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe it would be better to just catch all Exceptions as it won't slow down execution of unit tests as much as checking the stack trace. Moreover, this implementation is tied to JUnit. What if we are just running our code on desktop?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to catch the exception but I think this kind of exception is not possible to catch.

Copy link

@dmitry-zaitsev dmitry-zaitsev Jul 8, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should just work:

try {
    Log.d(tag, message);
} catch (Exception e) {
    // Ignore
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It didn't work when I tried it. It was my first approach, actually. But you can try it and let me know, maybe I missed something I don't know ;)

Log.d(tag, message);
}

/**
* Find out if code is running under JUnit.
*/
private boolean runningJUnit() {
if (runningJUnit != null) return runningJUnit;

StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
List<StackTraceElement> list = Arrays.asList(stackTrace);

for (StackTraceElement element : list) {
if (element.getClassName().startsWith("org.junit.")) {
runningJUnit = true;
return runningJUnit;
}
}

runningJUnit = false;
return runningJUnit;
}

}