简体   繁体   English

如何在模拟存储库中使用MockMvc?

[英]How to use MockMvc with mocked repository?

Conext Conext

  • I found this question here but my problem is different. 我在这里找到了这个问题但是我的问题有所不同。

  • So we are using Katharsis Controller and Spring Data Rest . 因此,我们正在使用Katharsis ControllerSpring Data Rest

  • We only have 1 controller for entire application and then the request will be sent to Spring Data Rest repositories classes. 我们只有1个用于整个应用程序的控制器,然后该请求将发送到Spring Data Rest存储库类。

  • We want to use Spring Restdoc to generate documentation which requires us to write unit tests with MockMvc . 我们想使用Spring Restdoc生成文档,这需要我们使用MockMvc编写单元测试。

  • But when using Mockmvc , it starts up the container and will require datasources to be set up. 但是,当使用Mockmvc ,它将启动容器并需要设置数据源。

  • If we use standaloneSetup() and pass the mocked repository class, then MockMvc won't load Katharsis Controller and therefore the request won't reach that repository. 如果我们使用standaloneSetup()并传递MockMvc存储库类,则MockMvc将不会加载Katharsis Controller ,因此请求将不会到达该存储库。

  • I understand that we can create an in-memory database but our project is big and the database needs a huge number of tables to be created we want to avoid that since these tests are for documentation purposes. 我知道我们可以创建一个内存数据库,但是我们的项目很大,并且数据库需要创建大量表,我们希望避免这样做,因为这些测试是出于文档目的。

Question

Is there any way to achieve this and only mock the target repository class? 有什么方法可以做到这一点,并且只模拟目标存储库类吗?

Note 注意

By repository I mean CrudRepository interface in Spring DataRest . CrudRepository存储库是指Spring DataRest CrudRepository接口。

  1. As Andy Wilkinson suggested, you may consider creating unit test where you wire beans together by yourself and use MokMvc standalone setup. 正如安迪·威尔金森(Andy Wilkinson)所建议的那样,您可以考虑创建单元测试,在该单元测试中,您可以自己将bean连接在一起并使用MokMvc独立设置。

  2. If you want to create integration test and create Spring Context anyway, there is way to fake Spring bean by using @Primary , @ActiveProfiles and @Profile annotations. 如果您仍然想创建集成测试并创建Spring Context,可以使用@Primary@ActiveProfiles@Profile批注来伪造Spring bean。 I wrote a blog post with GitHub example how to do it . 我用GitHub示例写了一篇博客文章如何做到这一点 You just need to combine this approach with WebApplicationContext based MockMvc setup. 您只需要将此方法与基于WebApplicationContextMockMvc设置相结合。 It works without problems, I wrote such tests in the past. 我以前写过这样的测试,但没有任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM