[英]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
或@MockBeans
或TestConfig
类来模拟实际的 bean,并使用模拟的 bean @MockBean
@MockBeans
Optional
@Autowired
private Optional<B> OptionalB;
@MockBean
private B b;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.