2017-06-15 33 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中的逻辑会更有意义? –

相关问题