How to mock Optional bean in spring boot?
在我的
1 2 3 4 5 6 7 8 | @Service public class A { //B is another @Component from one of the dependencies private Optional b; ... ... } |
我正在为
Cannot mock/spy class java.util.Optional
- final class
有没有解决的办法?非常感谢您的帮助。
您可以使用
如果将带注释的嘲笑搭配使用,则不能使用
1 2 3 4 5 6 7 8 9 10 11 12 | @RunWith(MockitoJUnitRunner.class) public class ATest { @Mock private B b; private A a; @Before public void setup() { a = new A(Optional.of(b)); } } |
尽管Lino的上述答案非常有效,但我选择不修改生产代码以使测试工作。相反,我修改了我的代码,如下所示:
1 2 3 4 5 6 7 8 | @Service public class A { @Autowired(required = false) private B b; ... ... } |
您实际上应该使用
自动连接
1 2 3 4 5 | @Autowired private Optional OptionalB; @MockBean private B b; |