Your class has a logger field marked as final, which prevents it from being modified during testing (You'll have the same thing when you use @Slf4j). In this case, you can solve the problem in a different way, such as using unit tests and System.out to capture logs.
class TestAppender extends AppenderBase<ILoggingEvent> {
List<ILoggingEvent> events = []
@Override
protected void append(ILoggingEvent eventObject) {
events.add(eventObject)
}
}
Some explanation about things what I did:
- TestAppender: Implementation of your own Appender that stores logs in the events list.
- setup and cleanup: Adding and removing our TestAppender to/from the logger before and after each test.
- testAppender.events.any { ... }: Verify that appropriate login messages have been logged.
These tests verify that the appropriate log messages are invoked when class methods are executed.
import ch.qos.logback.classic.Logger
import org.slf4j.LoggerFactory
import spock.lang.Specification
import spock.lang.Subject
import spock.lang.Unroll
class YourClassSpec extends Specification {
@Subject
YourClass yourClass = new YourClass()
Logger log = (Logger) LoggerFactory.getLogger(YourClass)
TestAppender testAppender = new TestAppender()
def setup() {
testAppender.start()
log.addAppender(testAppender)
}
def cleanup() {
log.detachAppender(testAppender)
}
@Unroll
def "Test values with userEmail: #userEmail and groupName: #groupName"() {
given:
String userEmail = "[email protected]"
String groupName = "testgroup"
when:
yourClass.testMethod(userEmail, groupName)
then:
testAppender.events.any { it.message == "Here you can compare values and logs: {} {}" && it.argumentArray[0] == userEmail && it.argumentArray[1] == groupName }
}
}
groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: LOG
. In your example you have access to car.logger - but how to this if the class is not within the Spock Testclass? – Educatory