代码之家  ›  专栏  ›  技术社区  ›  Almas Abdrazak

Spring boot,测试积垢存储库

  •  0
  • Almas Abdrazak  · 技术社区  · 8 年前

    我已经阅读了官方文档,如何在spring boot中编写集成测试。 例如,我有一个Rest控制器类

    @RestController
    @RequestMapping(value = "users")
    public class SvcUser {
    
        @RequestMapping(value = "user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
        @ResponseBody
        public ResponseEntity<String> registrateUser(@RequestBody Registration registrate) throws TimeoutException, SocketTimeoutException  {
    
            final String result = userService.registrateUser(registrate.getPhoneCode(), registrate.getPhoneNumber(), registrate.getOsType());
            return ResponseEntity.ok(result);
        }
    

    在userServiceClass中,我这样做了smth

      registrateUser(String args ...){
             Users user = new User();
             user.setSmth(smth);
             userRepository.save(user)
    
       }
    

    我的集成测试

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT,classes = GmoikaApiApplication.class)
    
        public class GmoikaApiApplicationTests {
    
            private MockMvc mockMvc;
            @Autowired
            private WebApplicationContext wac;
            @Before
            public void setUp(){
                this.mockMvc = webAppContextSetup(wac).build();
            }
    
            @Test
            public void firstTest() throws Exception {
                mockMvc.perform(post("/users/user")
                        .content("my new user"))
                        .andExpect(status().isOk())
                        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                        .andExpect(jsonPath("$.error",is(0)))
                        .andDo(print())
                        .andReturn();        
            }
    

    2 回复  |  直到 8 年前
        1
  •  0
  •   Radu Dumbrăveanu    8 年前

    我假设您的项目是Maven项目,那么:

    1. <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>test</scope> </dependency>

    2. 添加到 src/test/resources/config 应用程序.属性

      spring.datasource.url=jdbc:h2:mem:mytestdb spring.datasource.driver-class-name=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect spring.jpa.database=H2 spring.jpa.open-in-view=false spring.jpa.show-sql=false spring.jpa.hibernate.ddl-auto=create-drop

        2
  •  0
  •   Bhushan Uniyal    8 年前

    您需要在spring framework中创建概要文件,第一个用于您的标准应用程序和数据库配置,另一个用于您的测试应用程序,为了进行测试,您应该使用h2database。H2数据库是内存数据库,所以安装时不需要任何H2数据库,只需在项目中添加h2database的依赖项即可

    h2 1.4.194

    也在您的测试配置文件中

    jdbc.driverClassName=org.h2.Driver
    jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
    
    hibernate.dialect=org.hibernate.dialect.H2Dialect
    hibernate.hbm2ddl.auto=create