How to mock Optional bean in spring boot?

shankulk :

In my SpringBootApplication, I have a bean which injects another optional bean (like shown below)

@Service
public class A {

    //B is another @Component from one of the dependencies
    private Optional<B> b;
    ...
    ...
}

I am writing an integration test for class A where I need to @MockBean Optional<B> b. However since Optional is a final class, spring mockito raises following error

Cannot mock/spy class java.util.Optional - final class

Is there a way around this? Any help is much appreciated.

Lino :

You can use Optional.of(b).

If you use mockito with annotations, then you can't use @InjectMocks because your optional will not be known for mockito. You have to create your service A yourself. Something like this:

@RunWith(MockitoJUnitRunner.class)
public class ATest {
    @Mock
    private B b;

    private A a;

    @Before
    public void setup() {
        a = new A(Optional.of(b));
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=8143&siteId=1