【问题标题】:Spring boot controller test - mock repository but test actual serviceSpring Boot 控制器测试 - 模拟存储库但测试实际服务
【发布时间】:2018-12-22 19:49:24
【问题描述】:

我正在尝试在 Spring boot 2 中编写一个测试类,其中:

  • 我想测试一个控制器
  • 我想模拟一个存储库
  • 我想按原样注入服务(即模拟它)

这个类看起来像:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
public class MyControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private MyRepositoryInterface myRepository;
    @Autowired
    private MyService myService;
    // tests follow ...
}

MyService 的(唯一)实现使用@Service 进行注释,并允许通过其@Autowired 构造函数注入存储库:

@Service
public class MyActualService implements MyService {
    private MyRepository repo;
    @Autowired
    public MyActualService(MyRepository repo) {
        this.repo = repo;
    }
    // ...
} 

我在运行测试时收到NoSuchBeanDefinitionException,大致说明“没有MyService 可用”。

我怀疑我可能需要特定的测试配置才能获得服务,但我对可用的在线文献感到完全困惑。

任何指针?

【问题讨论】:

  • 根据the docs,自动配置明确“不是@Component@Service@Repository beans”
  • @jonrsharpe aHA。谢谢,正在调查。
  • @jonrsharpe 在实际阅读文档后解决了我的问题(咳咳)。您认为回答这个问题(使用一些子代码)可能有任何价值,还是您认为我应该删除?
  • 我想你可以写出答案。
  • @jonrsharpe 欢呼,很快就会完成。

标签: spring spring-boot integration-testing


【解决方案1】:

在咨询了docs(我一开始没有正确阅读)之后,正如jonsharpe 所指出的,我设法找到了一个可行的解决方案:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTest {
    @Autowired
    private MockMvc mvc;
    @MockBean
    private MyRepositoryInterface myRepository;

    // no need to reference the service explicitly

    // ... tests follow
}

上面在加载完整的应用程序配置时检索服务,并且只按照指示模拟存储库。

我可能会编写一个临时配置来更好地满足要求,但这已经“开箱即用”了。

【讨论】:

  • 另一种可能的解决方案是将@Import 与您的服务一起使用。但你是对的,最好只使用springboottest)
  • 如何使用这种配置方式包含spring security?
  • 我在这里迷路了,看起来这个问答最近得到了支持(并且没有发布其他答案),所以我将自我接受这是最不坏的解决方案 - 总是可以稍后接受更好的答案。
猜你喜欢
  • 2016-06-02
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
相关资源
最近更新 更多