Spock unit test MockBean is not working on Micronaut 3 RequestScope bean

52 views Asked by At

My project runs on micronaut 3, and I am trying to run test cases with Spock framework. Here is the dependencies and plugins I have added for test cases:

plugins {
    id("groovy")
    // ....
}

dependencies {
    /* other dependencies */
    testImplementation "io.micronaut.test:micronaut-test-spock"
    testImplementation("org.spockframework:spock-core") {
        exclude group: "org.codehaus.groovy", module: "groovy-all"
    }
    testAnnotationProcessor "io.micronaut:micronaut-inject-java"
    testImplementation "io.micronaut:micronaut-inject-groovy"
    testImplementation "io.micronaut:micronaut-inject-java"
}

The class for which I am trying to create the MockBean is given as following:

@Getter
@Setter
@ToString
@RequestScope
public class RequestAttributes {
    private String requestPath;
    private boolean setAsDefault;
    private String customerNo;
    private ChannelType channelType;
    private Double apiVersion;

    public RequestAttributes() {
    }
}

I am creating the bean like this:

import jakarta.inject.Inject

@MicronautTest(propertySources = "application.yml")
class TestCase extends  Specification {
    @Inject
    ClassToBeTested classToBeTested;

    @Inject
    RequestAttributes requestAttributes

    .... Test cases

    @MockBean(RequestAttributes)
    RequestAttributes mockRequestAttributes() {
        Mock(RequestAttributes)
    }
}

Now when the control goes inside of ClassToBeTested, the bean is found null. The declaration of the bean is as follows:

import jakarta.inject.Inject

class ClassToBeTested {
   @Inject
   RequestAttributes requestAttributes;
}

I am not sure why it is happening, I also wanted to add when I was running spock test cases with micronaut 1.3 it worked and I was using javax.inject package for injecting beans. Can anybody help me if it is an issue with jakarta.inject package.

0

There are 0 answers