Spring 豆茬无效
我有一个配置类,其中几个mockbean替换了测试上下文中的实际beanSpring 豆茬无效,spring,spring-boot,testing,mocking,mockito,Spring,Spring Boot,Testing,Mocking,Mockito,我有一个配置类,其中几个mockbean替换了测试上下文中的实际bean @Configuration public class MyTestConfig { @MockBean private MyService myService; } 我在测试中使用这些模拟: @Import({ MyTestConfig .class }) public class MyTest { @Autowired private MyService myService;
@Configuration
public class MyTestConfig {
@MockBean
private MyService myService;
}
我在测试中使用这些模拟:
@Import({ MyTestConfig .class })
public class MyTest {
@Autowired
private MyService myService;
@Test
public void aTest() {
...
}
}
首先,我的想法是在这个MyTestConfig
配置类中添加存根,以便为所有测试预先制作mock,因此我在@PostConstruct
方法中进行了此操作,它工作得很好-mock-in测试确实返回了预期值:
@PostConstruct
public void init() {
when(myService.foo("say hello")).thenReturn("Hello world");
}
但事实证明,构建一个适用于所有测试的预制模拟可能很棘手,所以我们决定将存根转移到测试中
@Test
public void aTest() {
when(myService.foo("say hello")).thenReturn("Hello world");
}
这不起作用-stubbed方法返回null
。我们希望将MockBean保留在配置类中,但在测试中存根它们,那么关于存根无效的原因有什么建议吗
Spring Boot 2.0.5,Mockito 2.22.0是的,存根应该在各自的测试用例中执行(除非您有一个共享存根场景的测试类,但这一切都取决于首选项) 但是,为了创建
@MockBeans
,您需要使用@springbootest
,以便用mock替换实际的bean。这可以像下面这个例子一样简单:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {
@Autowired
private MyTestClass testClass;
@MockBean
private MyService service;
@Test
public void myTest() {
// testing....
}
}
实际上,我很惊讶,
@MockBean
在配置类中可以正常工作。另外,在测试类上使用@Import
是不应该做的事情。如果您想全局模拟Bean,您需要在@Bean
方法中使用Mockito.mock
自己创建模拟,以进行可靠的模拟。否则,在要使用模拟实例的测试用例中使用一个@Autowired
字段。另外,您应该在@springbootest
或@ContextConfiguration
中将其指定为用于配置的类,而不是@Import
。@M.Deinum@MockBean
的文档说明:可以用作类级注释或@configuration classes,或者使用SpringRunner测试@run类,所以它肯定应该在配置类中工作。如果stubing在测试中起作用,那么在@Bean方法中定义一个普通的mock就可以了,但是它不起作用,所以这也不是一个选项。如果stubing不起作用,那么你一定在做一些奇怪的事情。我们在成百上千的测试用例中使用了这种方法,效果非常好。您是否为要执行的操作定义了正确的存根?@M.Deinum我们的“我的问题”描述不足,因为我跳过了一个非常重要的细节,但您确实帮助我解决了这个问题。我没有说(旨在保持简单)我的测试是一个@WebMvcTest
,带有@WithUserDetails
,我的服务是一个自定义UserDetailsManager
的依赖项。Spring Security在实际测试内容之前调用UserDetailsManager
。这就是为什么存根测试没有效果,这也是为什么在config的@PostConstruct
中存根模拟时,它工作正常的原因。谢谢你的帮助。这个bean实际上被一个mock替换了MockUtil.isMock(myService)
在测试中返回true
。唯一的问题是在测试中执行的存根无效。您是否使用@SpringBootTest
和SpringRunner
来运行测试?我找到了答案,请参阅问题下方的注释。谢谢你的帮助!