简体   繁体   中英

How to mock Optional bean in spring boot?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM