简体   繁体   English

如何在 Spring Boot 中模拟 Optional bean?

[英]How to mock Optional bean in spring boot?

In my SpringBootApplication , I have a bean which injects another optional bean (like shown below)在我SpringBootApplication ,我有一个bean ,一个注入另一个可选豆(如下图所示)

@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 .我正在为class A编写集成测试,我需要@MockBean Optional<B> b However since Optional is a final class, spring mockito raises following error但是,由于Optional是最后一类,因此 spring mockito 会引发以下错误

Cannot mock/spy class java.util.Optional - final class无法模拟/间谍类 java.util.Optional - 最终类

Is there a way around this?有没有解决的办法? Any help is much appreciated.任何帮助深表感谢。

You can use Optional.of(b) .您可以使用Optional.of(b)

If you use mockito with annotations, then you can't use @InjectMocks because your optional will not be known for mockito.如果您使用带有注释的 mockito,那么您不能使用@InjectMocks因为您的 optional 不会因 mockito 而为人所知。 You have to create your service A yourself.您必须自己创建服务A 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您实际上应该使用@MockBean@MockBeansTestConfig类来模拟实际的 bean,并使用模拟的 bean @MockBean @MockBeans Optional

@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.尽管Lino 的上述答案完美无缺,但我选择不修改生产代码以使测试正常工作。 I've instead modified my code like below:我改为修改我的代码如下:

@Service
public class A {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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