Logging is a very important aspect of any code and Junit 5 test cases are no exception. Sometimes people use System.out.println
but it's not a good practice.
we can log the Junit 5 test cases in multiple ways.
- java.util.Logger
- Lombok log4j2
Java.util.logging
Java.util.logging
is a basic logging mechanism provided by Java by default. if no external logging framework is used, then Java.util.logging
comes handy.
To use logging first create a static instance of Logger.
static final Logger logger = Logger.getLogger(TestLifecycleLogger.class.getName());
package com.example.junit5.sujan;
public class AppleCalculator {
public int addApple(int apple1, int apple2) {
return apple1 + apple2;
}
}
package org.wesome.junit5;
import org.junit.jupiter.api.Test;
import java.util.logging.Logger;
import static org.junit.jupiter.api.Assertions.assertEquals;
class AppleCalculatorTest {
static final Logger log = Logger.getLogger(AppleCalculatorTest.class.getName());
@Test
void addApple() {
AppleCalculator appleCalculator = new AppleCalculator();
int apple = appleCalculator.addApple(1, 1);
log.info("apple " + apple);
assertEquals(2, apple, " 1 apple + 1 apple is 2 apple ");
}
}
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}
Lombok log4j2
Lombok has become a very useful library to avoid the boiler plate code. it provides a lot of annotation and functionality to increase productivity.
package org.wesome.junit5;
import lombok.extern.log4j.Log4j2;
@Log4j2
public class AppleCalculator {
public int addApple(int apple1, int apple2) {
int apple = apple1 + apple2;
log.info("input is {} and {}, after computation output is {}", apple1, apple2, apple);
return apple;
}
}
package org.wesome.junit5;
import lombok.extern.log4j.Log4j2;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@Log4j2
class AppleCalculatorTest {
@Test
void addApple() {
AppleCalculator appleCalculator = new AppleCalculator();
int apple = appleCalculator.addApple(1, 1);
log.info("total apple is {}", apple);
assertEquals(2, apple, " 1 apple + 1 apple is 2 apple ");
}
}
plugins {
id 'java'
id 'io.freefair.lombok' version '6.0.0-m2'
}
group 'org.wesome'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}