Home » Android » android – Can I print an information message in JUnit tests?

android – Can I print an information message in JUnit tests?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am running JUnit tests as part of my Android app tests. In this case it’s just testing the responses of an API we rely on that may be changed frequently (in order to validate later tests)

When these tests pass the output window of Android studio shows no messages. We’d instead like to start each method with a message saying which endpoint it is testing (E.g. “Tests /oranges//segments”) so that the message always shows as the first message for both passing and failing tests.

I tried the android logs Log.println(Log.ASSERT, "...", "...") but that did not show in the android studio output.

Is there a way to do this? The output window I refer to is the one displayed below

enter image description here

(When a test is marked as ignored, you can supply a message to display. I’d just like the same behaviour for my other tests)

How to&Answers:

The old fashioned Java styled System.out.println(); will work.

Answer:

JUnit tests are not executed on a Android device (or emulator) but on Java Virtual Machine on PC’s environment. You have two solution:

  • Just use some Logger (like log4j, JDK logger, etc) or simply use System.out.
  • Use Roboletric and its capability to define shadow classes to redefine Log class.

I suggest you the second way. Roboletric already have a shadow class for log. To redirect output into console

 @Before
 public void setUp() throws Exception {
      ShadowLog.stream = System.out;
      //you other setup here
 }

Some references:

https://guides.codepath.com/android/Unit-Testing-with-Robolectric
https://github.com/robolectric/robolectric-samples
http://www.vogella.com/tutorials/Robolectric/article.html

I hope it helps.