How to mock Optional bean in spring boot?

Viewed 1755

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.

3 Answers

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));
    }
}

You should actually mock the actual bean using @MockBean or @MockBeans or TestConfig class and Autowire the Optional with mocked bean

@Autowired
private Optional<B> OptionalB;

@MockBean
private B b;

Although Lino's above answer works perfectly, I chose not to modify the production code to make the test work. I've instead modified my code like below:

@Service
public class A {

    @Autowired(required = false)
    private B b;
    ...
    ...
}
Related