2017-07-27 8 views
6

私はSpringブートRestコントローラのテストを書いています。この残りのコントローラは、いくつかの値をdbに書き込みます。メモリ内のDBを使用してRestコントローラのテストを記述する

このテストにSpringが提供するインメモリデータベースを使用したいと思います。さらに下、私は次の例外がスローされた参照エラースタックトレースで

java.lang.IllegalStateException: Failed to load ApplicationContext 

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoconfigureTestDatabase.

このthis docによると、私はこのエラーが発生し@DataJpaTestとテストクラスを、注釈を付ける必要があり私が取り組んでいるテストクラスです:

@RunWith(SpringRunner.class) 
@SpringBootTest 
@AutoConfigureMockMvc 
@DataJpaTest 
public class AuthenticationControllerFTest { 

    @Autowired 
    private MockMvc mockMvc; 

    @MockBean 
    private AuthenticationManager authenticationManager; 

    @Autowired 
    private WebApplicationContext context; 

    @Autowired 
    private Filter springSecurityFilterChain; 

    @Before 
    public void setup() { 
     mockMvc = MockMvcBuilders.webAppContextSetup(context) 
       .addFilters(springSecurityFilterChain).build(); 
    } 

    @Test 
    public void testCreate() throws Exception { 

     String exampleUserInfo = "{\"name\":\"Salam12333\",\"username\":\"[email protected]\",\"password\":\"Salam12345\"}"; 
     RequestBuilder requestBuilder = MockMvcRequestBuilders 
       .post("/signup") 
       .accept(MediaType.APPLICATION_JSON).content(exampleUserInfo) 
       .contentType(MediaType.APPLICATION_JSON); 

     MvcResult result = mockMvc.perform(requestBuilder).andReturn(); 

     MockHttpServletResponse response = result.getResponse(); 
     int status = response.getStatus(); 
     Assert.assertEquals("http response status is wrong", 200, status); 
    } 
} 

このエラーの原因は何ですか?

編集1 これは私のapplication.propertiesの内容です:

spring.datasource.username = hello 
spring.datasource.password = hello 
spring.datasource.driver-class-name= com.mysql.jdbc.Driver 
spring.datasource.url = jdbc:mysql://localhost:3306/myproject?useSSL=false 

spring.jpa.show-sql=true 
spring.jpa.hibernate.ddl-auto=update 
logging.level.org.hibernate.SQL=DEBUG 
logging.level.org.hibernate.type=TRACE 
logging.level.org.springframework.web=DEBUG 

server.port = 8443 
server.ssl.key-store = classpath:tomcat.keystore 
server.ssl.key-store-password = hello 
server.ssl.key-password = hello 
server.ssl.enabled = true 
server.ssl.key-alias=myproject 

編集2

私はpom.xmlに次を追加しました:

<dependency> 
    <groupId>org.hsqldb</groupId> 
    <artifactId>hsqldb</artifactId> 
    <scope>test</scope> 
</dependency> 

私はapplication-test.propertiesを作成ウィ以下の内容番目:

spring.datasource.username= root 
spring.datasource.password= password 
spring.datasource.driver-class-name= org.h2.Driver 
spring.datasource.url= jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 
  1. ユーザ名とpassowrdは何ですか?どこに置いたらいいですか?
  2. 私はこの行を含むエラーを取得し、テストを実行したときに、私はまた、テストクラスに@ActiveProfiles("test")を追加しました:

Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

+0

"組み込みデータベースが必要な場合は、サポートされているクラスパスをクラスパスに追加するか、@AutoconfigureTestDatabaseの置換属性を調整してください。だから、あなたはクラスパスに組み込みのデータベースを入れましたか? –

+0

私の 'application.properties'ファイルの内容を元の投稿に追加します。 –

+0

application.propertiesはクラスパスに影響しません。 pom.xmlにh2またはhsqldbを追加する必要があります。 –

答えて

4

Spring BootH2インメモリ・データベースの依存関係が表示され、それが作成されます(下記参照)の自動設定を可能にし、あなたがクラスパス上H2依存関係を持っている、あなたは@SpringBootApplicationでクラスに注釈を付けると仮定すると、 javax.sql.DataSourceの実装。デフォルトの接続URLはjdbc:h2:mem:testdbで、デフォルトのユーザー名とパスワードはusername:saとpassword:emptyです。

アプリケーション。プロパティは、我々は除いてメモリデータベース構成にするために、追加の任意のものを追加する必要はありません

spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 
    spring.datasource.driverClassName=org.h2.Driver 
    spring.datasource.username=sa 
    spring.datasource.password= 

    spring.datasource.testWhileIdle = true 
    spring.datasource.validationQuery = SELECT 1 

    spring.jpa.show-sql = true 
    spring.h2.console.enabled=true // if you need console 

H2依存関係が

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

    <dependency> // If you need h2 web console 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-web</artifactId> 
    </dependency> 

あなたは春ブーツで管理http://localhost:8080/h2-console

+0

'username'と' password'の値はデフォルトですか?もしそうでなければ、どこに置くべきですか?スコープが 'runtime'で' test'でないのはなぜですか? –

+0

@ArianHosseinzadeh私は自分の答えを更新しました 資格はデフォルトです、あなたはh2コンソールでそれらを変更することができます、私の答えに説明を追加しました。スコープについてはわかりません - ランタイムはうまく動作します。テスト用に変更することができます。 – fg78nc

1

は、両方の注釈@AutoConfigureMockMvcと@DataJpaTestを削除します。完成したアプリケーションをテストしようとしているので、@ SpringBootTestアノテーションが必要です。 @DataJpaTestは、データアプリケーションスライスのみをテストする場合にのみ必要です。これを見てください:https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4

+0

しかし私は実際のデータベースを使用したくありません。私はメモリ内のDBを使いたいです。 –

+0

両方のアノテーションを削除すると、次のエラーが表示されます。 'フィールド' mockMvc 'で表現されている満足度の低い依存関係。ネストされた例外はorg.springframework.beans.factory.NoSuchBeanDefinitionExceptionです: 'org.springframework.test.web.servlet.MockMvc'タイプの適格なBeanはありません:autowire候補と見なされる少なくとも1つのbeanが必要です。依存関係の注釈:{@ org.springframework.beans.factory.annotation.Autowired(必須= true)} ' –

1

おそらくこれは役立ちます。

spring.datasource.url=jdbc:hsqldb:mem:testdb 
spring.datasource.username=sa 
spring.datasource.password= 

spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect 
spring.jpa.show-sql=true 
spring.jpa.hibernate.ddl-auto=create 

も参照してくださいConfigure specific in memory database for testing purpose in Spring

+0

そして、まずはhsqldbを最初に設定する必要があると仮定します。 –

+0

'username'、' password'を設定し、Javaで 'testdb'を作成する方法はありますか? –

+0

データベースがメモリにあります...あなたは 'testdb'をどういう意味ですか? Hibernateは起動時にエンティティからテーブルを作成します。値をあらかじめロードする場合は、SQLスクリプトを使用する必要があります。他の質問がある場合は、SOを検索したり、新しい質問をしてください。 –

2

のためのH2コンソールにアクセスできるファイルクラスパス上のjarファイルとクラスパス上のアプリケーションプロパティファイル(application.properties)(Mavenが使用されている場合はsrc/test/resources)の残りの部分は、スプリングブート(ブートの美しさ)によって注意が払われます。

別のオプションは、特定の性質は、(例えばapplication-test.propertiesための)クラスパスsrc/amin/resources上のファイルのプロファイルを提供することである

ファイルの両方のプロパティファイルの

設定例を以下に示すテスト構成のために有効である(検討クラスパス上のHSQL DBジャー):インメモリDBは、次のものを必要とテストRESTサービスの場合

spring.jpa.hibernate.ddl-auto = create-drop 
spring.jpa.database = HSQL 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect 
spring.datasource.driverClassName = org.hsqldb.jdbcDriver 
spring.datasource.url: jdbc:hsqldb:mem:scratchdb 
spring.datasource.username = sa 
spring.datasource.password = pass 
2


1のpom.xmlにH2依存関係を追加します

<dependency> 
    <groupId>com.h2database</groupId> 
    <artifactId>h2</artifactId> 
    <scope>runtime</scope> 
    <optional>true</optional> 
</dependency> 

2. H2 application.propertiesで設定したり、クラス

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
をテストapplication.yaml

spring.jpa.database = h2 
spring.datasource.url=jdbc:hsqldb:mem:testdb 
spring.datasource.username=sa 
spring.datasource.password= 
spring.jpa.database-platform=org.hibernate.dialect.HSQLDialect 
spring.jpa.show-sql=true 
spring.jpa.hibernate.ddl-auto=create 

3.注釈を定義します。

完全なコードは次のようになります:

@RunWith(SpringRunner.class) 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 
public class AuthenticationControllerFTest { 

    @Autowired 
    private MockMvc mockMvc; 

    @MockBean 
    private AuthenticationManager authenticationManager; 

    @Autowired 
    private WebApplicationContext context; 

    @Autowired 
    private Filter springSecurityFilterChain; 

    @Before 
    public void setup() { 
     mockMvc = MockMvcBuilders.webAppContextSetup(context) 
       .addFilters(springSecurityFilterChain).build(); 
    } 

    @Test 
    public void testCreate() throws Exception { 

     String exampleUserInfo = "{\"name\":\"Salam12333\",\"username\":\"[email protected]\",\"password\":\"Salam12345\"}"; 
     RequestBuilder requestBuilder = MockMvcRequestBuilders 
       .post("/signup") 
       .accept(MediaType.APPLICATION_JSON).content(exampleUserInfo) 
       .contentType(MediaType.APPLICATION_JSON); 

     MvcResult result = mockMvc.perform(requestBuilder).andReturn(); 

     MockHttpServletResponse response = result.getResponse(); 
     int status = response.getStatus(); 
     Assert.assertEquals("http response status is wrong", 200, status); 
    } 
} 
関連する問題