【问题标题】:SpringBootTest with MockBean is not returning what I expect带有 MockBean 的 SpringBootTest 没有返回我所期望的
【发布时间】:2017-06-15 19:58:43
【问题描述】:

版本:

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

    }

}

预期输出:我比史诗更伟大 实际输出:null

我只是想用一个将返回“我比史诗更伟大”的模拟替换上下文中的 bean 实例。我在这里配置错误了吗?

【问题讨论】:

  • 我使用上述相同的类和相同的 Spring Boot 版本进行了测试,它运行良好,没有任何问题。在您的pom.xml 中,您是否同时添加了spring-boot-starter-testspring-boot-test 依赖项?

标签: spring spring-boot mockito spring-test spring-boot-test


【解决方案1】:

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

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

【讨论】:

  • 此应用程序结构用于在启动时运行以进行测试的批处理过程,以某种方式禁用 commandLineRunner 并复制运行器中的逻辑是否更有意义?
猜你喜欢
  • 2021-05-30
  • 1970-01-01
  • 2021-12-11
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-24
相关资源
最近更新 更多