筆者在寫自測的時候遇到的問題:
我想模擬一個Bean,並在之后使用Mockito打樁,於是使用了 @MockBean 注解(spring集成mockito的產物),但代碼編寫好了后啟動測試卻報NullPointerException
好家伙,bean沒有Mock上。
交代一下我的代碼背景:
框架:SpringBoot、SpringBoot Test、TestNG、Mockito
@SpringBootTest
@TestPropertySource("classpath:application.properties")
public class XXXServiceTest extends AbstractTestNGSpringContextTests {
@MockBean
XXXComponent xxxComponent; // null ???
}
解決辦法
// 在測試類上加
@SpringBootTest
@TestPropertySource("classpath:application.properties")
@TestExecutionListeners(MockitoTestExecutionListener.class)
public class XXXServiceTest extends AbstractTestNGSpringContextTests {
@MockBean
XXXComponent xxxComponent; // 有了有了
}
原因
因為Spring集成TestNG的抽象類: AbstractTestNGSpringContextTests
上並沒加關於Mockito相關的測試監聽器,所以就沒有運用上MockBean的注解功能,看源碼
@TestExecutionListeners({ServletTestExecutionListener.class, DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class})
public abstract class AbstractTestNGSpringContextTests implements IHookable, ApplicationContextAware {
PS:官方也有討論過這個issue,但官方並不打算集成進來,所以叫大家自己加個Listener則是,我認為也是該這樣,因為Mockito這樣的產品會有很多種。