【发布时间】: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-test和spring-boot-test依赖项?
标签: spring spring-boot mockito spring-test spring-boot-test