0

[Scala] I have a class someClass with a function A in which I use log4j2 for logging.

class someClass {

def A ={
//smt
logger.warn("oups")
}

}

In my unit tests someClassTest, I want to collect what A logs and assert the message content.

class someClassTest {

it("should log warning") {
//trigger A()
//collect logs
val logs //contain logs
assert(logs(0).contains("oups"))

}

}

Theatrically, I should create a custom Appender (extending the AbstractAppender) and collect the logs in a list for example, but I cannot do that, or more like idk how to do that. Is there other ways to assert the logs ? or how to create that custom Appender?

Thank yall

Rida
  • 89
  • 1
  • 5
  • 1
    What is the need to unit test your logs? You don't have test it as it is an external component to your application. At least if you write a wrapper class for you log, you can test your wrapper class. – Harry Coder Sep 10 '22 at 20:46
  • in my case the log message is generated depending on conditions and not a simple string, so i want to check if the message is as it should be – Rida Sep 10 '22 at 20:52
  • You can mock your logger method and call `verify` to check wether your log method is called or not? – Harry Coder Sep 10 '22 at 21:01
  • i spy it instead but i get ```Wanted but not invoked``` even though it normally is – Rida Sep 10 '22 at 21:26
  • Does this answer your question? [Logger.getRootLogger().addAppender(appender) removed in Test cases](https://stackoverflow.com/questions/72556197/logger-getrootlogger-addappenderappender-removed-in-test-cases) – Piotr P. Karwasz Sep 11 '22 at 07:39

0 Answers0