2017-08-02 49 views
0

我從不爲我的休息控制器和服務編寫測試。 我已閱讀官方文檔,如何在春季啓動時編寫集成測試。 因此,例如我有一個休息Controller類春季啓動,測試垃圾信息庫

@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我做了水木清華這樣

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("https://stackoverflow.com/users/user") 
        .content("my new user")) 
        .andExpect(status().isOk()) 
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) 
        .andExpect(jsonPath("$.error",is(0))) 
        .andDo(print()) 
        .andReturn();   
     } 

這是正常工作,但我在我的數據庫中有新用戶。我不想在生產中僅由於測試而創建假用戶。我的問題是如何避免在集成測試中的數據庫中創建新用戶?

+0

使用測試db表示'hsqldb'是彈簧測試的默認值。你可以使用它。 – sunkuet02

+0

您可以使用'@ Transactional'和'@ Rollback'來創建用戶,然後將其滾回到數據庫中。 – Brad

回答

0

我認爲你的項目是一個Maven項目,則:

  1. 添加以下依賴於的pom.xml

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

  2. 添加到的src /測試/資源/配置文件application.properties含有類似的東西:

    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

+0

我也有我的postgresql數據源的application.properties文件,我應該複製這個文件嗎? –

+0

你** application.properties **位於** src/main/resources **或** src/test/resources **? –

+0

謝謝,我還沒有看到它 –

0

您需要在Spring框架中創建配置文件,第一次爲您的標準應用程序配置數據庫配置,另一個配置爲測試應用程序,爲了測試您應該使用h2database。 H2數據庫內存數據庫,這樣你就不需要在安裝任何的H2數據庫,只需添加項目h2database的依賴

com.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