StreamBridge Final Cannot Be Mocked

Viewed 2316

I am not able to mock StreamBridge in my Unit Tests.

@MockBean
private StreamBridge bridge;

I get an IllegalStateException due to:

Caused by: org.mockito.exceptions.base.MockitoException: Cannot mock/spy class org.springframework.cloud.stream.function.StreamBridge Mockito cannot mock/spy because :

  • final class at org.springframework.boot.test.mock.mockito.MockDefinition.createMock(MockDefinition.java:154)
2 Answers

I reached out to Oleg who authored the StreamBridge class and he basically said that:

We should not be making StreamBridge open to simply accommodate some testing framework. If anything it should be the other way around.

Also, Oleg mentioned that

Also, we provide a test binder which was specifically designed for these type of cases where you can actually validate the real binder interaction with StreamBridge (and other components) not the mocked assumption that may actually be wrong. Please look at https://github.com/spring-cloud/spring-cloud-stream/blob/master/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/function/StreamBridgeTests.java for more on testing with StreamBridge.

Considering Oleg's response above and since I need to isolate the Spring Cloud Stream code (StreamBridge and anything else) to test my code, I will be looking into the test binder from Spring Cloud Stream.

BTW, I am using the latest Spring Boot (2.4.5) / Spring Cloud Train Release (2020.0.2).

Thanks,

Rubens

StreamBridge is a final class, With Mockito2 we can mock the final class, but by default this feature is disabled and that need to enable with below steps:

  1. Create a directory ‘mockito-extensions’ in src/test/resources/ folder.

  2. Create a file ‘org.mockito.plugins.MockMaker’ in ‘src/test/resources/mockito-extensions/’ directory.

  3. Write the content 'mock-maker-inline' in org.mockito.plugins.MockMaker file.

  4. At test class level use ‘@ExtendWith(MockitoExtension.class)’

Then StreamBridge will be mocked successfully.

Related