Add unit tests with mockito for metric stats (#38)

This commit is contained in:
Stephan Schnabel 2023-05-02 09:30:58 +02:00 committed by GitHub
parent cfce0dee45
commit 99a01e5c02
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 424 additions and 9 deletions

View file

@ -1,5 +1,14 @@
package io.kokuwa.keycloak.metrics.junit;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.ClassOrderer;
import org.junit.jupiter.api.MethodOrderer;
@ -21,9 +30,42 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
@TestMethodOrder(MethodOrderer.DisplayName.class)
public abstract class AbstractMockitoTest {
private static final List<LogRecord> LOGS = new ArrayList<>();
static {
System.setProperty("org.jboss.logging.provider", "jdk");
System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tT %4$-5s %2$s %5$s%6$s%n");
Logger.getLogger("org.junit").setLevel(Level.INFO);
Logger.getLogger("").setLevel(Level.ALL);
Logger.getLogger("").addHandler(new Handler() {
@Override
public void publish(LogRecord log) {
LOGS.add(log);
}
@Override
public void flush() {}
@Override
public void close() {}
});
}
@BeforeEach
void reset() {
Metrics.globalRegistry.clear();
Metrics.addRegistry(new SimpleMeterRegistry());
LOGS.clear();
}
public static void assertLog(Level level, String message) {
assertTrue(LOGS.stream()
.filter(l -> l.getLevel().equals(level))
.filter(l -> l.getMessage().equals(message))
.findAny().isPresent(),
"log with level " + level + " and message " + message + " not found");
}
}