Hayi
Hayi

Reputation: 6246

@MockBean injected correctly but with null value on test class

I am using tests with Cucumber and Spring Boot

@CucumberContextConfiguration
@ActiveProfiles(profiles = { "cucumber" })
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ExtendWith(SpringExtension.class)
public class FooTest {

    @Autowired
    BatchService batchService;

    @MockBean
    S3ClientService s3ClientService;

    @MockBean
    HttpClientService httpClientService;

    @SpyBean
    UndueService undueService;


    @Given("^foo cucumber test$")
    public void foo_cucumber_test() {
        System.out.println("Foo Test");
    }
}

When I run/debug my test with a break point on @Given method

enter image description here

I got this weird behavior, the @Mockbean/@SpyBean are correctly injected but in the test class its values are null !! and I can't run Mockito functions verify or when

But when I run a test without cucumber

@Test
void fooTest() {
    System.out.println("Foo Test");
}

It works fine !! the values are not null

Upvotes: 2

Views: 6040

Answers (2)

ObviousChild
ObviousChild

Reputation: 129

I landed here because I had the same problem. I found following solution, and seems better than the accepted solution which needs multiple annotations (which actually did not work for me). Adding here for anyone that may find it useful.

Annotate the test class to use MockitExtension as shown below

@ExtendWith(value={SpringExtension.class, MockitoExtension.class})

Upvotes: 0

Semyon Kirekov
Semyon Kirekov

Reputation: 1442

So, mock beans are created but not injected to the test suite. I guess you should put both @Autowired and @MockBean annotations.

Here is a similar question: Spring @MockBean not injected with Cucumber

Upvotes: 7

Related Questions