2017-06-15 34 views
0

版本:SpringBootTest與MockBean沒有返回我的期望

Java: 1.8 
Spring Boot: 1.5.4.RELEASE 

應用程序主:

@SpringBootApplication 
public class SpringbootMockitoApplication implements CommandLineRunner { 
    @Autowired 
    MyCoolService myCoolService; 

    public static void main(String[] args) { 
     SpringApplication.run(SpringbootMockitoApplication.class, args); 
    } 

    @Override 
    public void run(String... strings) throws Exception { 
     System.out.println(myCoolService.talkToMe()); 
    } 
} 

我的服務接口:

public interface MyCoolService { 
    public String talkToMe(); 
} 

我的服務實現:

@Service 
public class MyCoolServiceImpl implements MyCoolService { 

    @Override 
    public String talkToMe() { 
    return "Epic Win"; 
    } 
} 

我的測試類:

@RunWith(SpringRunner.class) 
@SpringBootTest 
public class SpringbootMockitoApplicationTests { 

    @MockBean 
    private MyCoolService myCoolService; 

    @Test 
    public void test() { 
     when(myCoolService.talkToMe()).thenReturn("I am greater than epic"); 

    } 

} 

預期輸出:我比史詩 實際輸出更大:空

我只是想取代與模擬的背景下,將返回「我的bean實例我比史詩更偉大「。我在這裏配置錯了嗎?

+0

我跑了與上面提到的相同的類和相同的春季啓動版本的測試,並沒有問題,它工作正常。在你的'pom.xml'中,你是否添加了'spring-boot-starter-test'和'spring-boot-test'依賴項? –

回答

3

任何CommandLineRunnerrun方法被稱爲SpringApplication正在運行的一部分。當測試框架爲您的測試引導應用程序上下文時,會發生這種情況。至關重要的是,這是在您的測試方法對您的模擬設置任何期望之前。因此,調用talkToMe()時,模擬返回null

在將問題簡化爲一個簡單示例時可能會失去一些東西,但我不認爲我會在這裏使用集成測試。相反,我會用模擬服務單元測試你的CommandLineRunner。爲此,我建議轉移到構造函數注入,以便您可以將模擬直接傳遞到該服務的構造函數。

+0

這個應用程序結構是爲了在測試啓動時運行的批處理過程而開發的,如果以某種方式禁用commandLineRunner並複製runner中的邏輯會更有意義? –

相關問題