使用MockBean的SpringBootTest没有返回我期望的结果

使用MockBean的SpringBootTest没有返回我期望的结果,spring,spring-boot,mockito,spring-test,spring-boot-test,Spring,Spring Boot,Mockito,Spring Test,Spring Boot Test,版本: Java: 1.8 Spring Boot: 1.5.4.RELEASE 主应用程序: @SpringBootApplication public class SpringbootMockitoApplication implements CommandLineRunner { @Autowired MyCoolService myCoolService; public static void main(String[] args) { Spr

版本:

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");

    }

}
预期输出:我比epic更出色 实际输出:空

我只是想用一个mock来替换上下文中的bean实例,该mock将返回I am before epic。我在这里配置错误了吗?

任何CommandLineRunner的run方法都是作为正在运行的SpringApplication的一部分调用的。当测试框架为测试引导应用程序上下文时,就会发生这种情况。关键的是,这是在您的测试方法对MyColService模拟设置任何期望之前。因此,调用talkToMe时,mock返回null

在将问题简化为一个简单的示例时,可能丢失了一些东西,但我不认为在这里使用集成测试。相反,我将使用模拟服务对CommandLineRunner进行单元测试。为此,我建议转到构造函数注入,这样您就可以将模拟直接传递到服务的构造函数中。

任何CommandLineRunner的run方法都是作为正在运行的SpringApplication的一部分调用的。当测试框架为测试引导应用程序上下文时,就会发生这种情况。关键的是,这是在您的测试方法对MyColService模拟设置任何期望之前。因此,调用talkToMe时,mock返回null


在将问题简化为一个简单的示例时,可能丢失了一些东西,但我不认为在这里使用集成测试。相反,我将使用模拟服务对CommandLineRunner进行单元测试。因此,,我建议转到构造函数注入,这样您就可以将模拟直接传递到服务的构造函数中。

此应用程序结构适用于在启动时运行的批处理过程,以便进行测试。以某种方式禁用commandLineRunner并复制运行器中的逻辑是否更有意义?此应用程序结构是对于一个在启动时运行的批处理过程进行测试,以某种方式禁用commandLineRunner并复制运行程序中的逻辑是否更有意义?我使用上面提到的相同类和相同的Spring Boot版本运行了测试,它运行得很好,没有问题。在pom.xml中,您是否同时添加了spring boot starter测试和spring boot测试依赖项?我使用上面提到的相同类和相同的spring boot版本运行了测试,它工作正常,没有问题。在pom.xml中,您是否同时添加了spring boot starter测试和spring boot测试依赖项?