I\'m trying to print some data with System.out
in my unit tests (@Test
mehotds), but it is not showing anything. However, it works properly in
Ran into this as well. I'm using gradle to manage my tasks and I put this in at the end of by build.gradle
file :
test {
testLogging.showStandardStreams = true
}
Now I see System.out.println(whateves)
.
The -Dtest=*
command line option of Maven appears to trigger the show of stdout in unit tests.
By convention, the stdout shows in target/surefire-reports/*-output.txt
. Apparently, the Surefire plugin developers could not reuse stdout for communication of many things between the tests and the framework.
I made i little trick in separate non-test class. It is not that smooth as logger, but if you are looking for quick solution in Spring Boot you can use this.
PrintForTest.java
import org.springframework.stereotype.Controller;
@Controller
public class PrintForTest {
public static void print(String input){
System.out.println(input);
}
}
MainTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.junit.Assert;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class MainTest {
...
@Test
public void testingSomething(){
PrintForTest.print("My new System.out.print()");
Assert.assertEquals(...);
}
}
edited: using static method, no need to use @Autowired.
To get the output of your written Tests via System.out.println you need to configure maven-surefire-plugin to redirect this output into a file which can be achieved by using the following:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
</configuration>
</plugin>
The option redirectTestOutputToFile will redirect the output of System.out.println etc. into a file which is separately created:
Excerpt from the docs:
Set this to "true" to redirect the unit test standard output to a file (found in reportsDirectory/testName-output.txt).
Apart from that a System.out.println does not make sense in a unit test in general.
The problem is the name of your test class. To be recognized in the test phase within the build (by the Maven surefire plugin), it must be named "*Test":
Inclusions and Exclusions of Tests
I am using gradle
. I had this problem with both System.out
and java.util.logging.Logger
. I edited the following part of my build.gradle
file:
test {
testLogging {
exceptionFormat = 'full'
events = ["passed", "failed", "skipped"]
}
}
and added showStandardStreams = true
under testLogging
. The result was as follows:
test {
testLogging {
exceptionFormat = 'full'
events = ["passed", "failed", "skipped"]
showStandardStreams = true
}
}
It fixed both of them.