Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Hi I am writing a SpringBoot application, where I am writing unit as well as integration tests, but my integration tests are failing?

Reason 1: It tries to create a table by executing schema.sql twice and hence table already exists exception is thrown and the test fails.

Reason 2: Even if I put create if not exists, it fails on insertions by executing the data.sql as it tries to execute the script 2nd time and a uniqueness constraint violation occurs. I know I can drop tables or delete records at the start to get rid of errors.

But why it's running twice? not thrice or once?

First test

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Atest {

}

Second test

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class Btest {

}

Third test

@SpringBootTest
public class Ctest {

}

Atest and Btest both passes and they try to access a record from test data and they are able to see it. but Ctest fails due to exception

Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table "tbl_test" already exists; SQL statement:

as there are 2 files in test->resourece folder data.sql and schema.sql. it tries to run them twice

My Questions:

  1. Why Scripts are executed twice?
  2. Why not thrice, once for each test?
  3. I can see the only difference among them is @SpringBootTest vs @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) but still they are in one execution cycle or context and hence it should not happen.
  4. Why it does not fail when multiple tests have @SpringBootTest (like if all three has this annotaion).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

M. Deinum answered the question in his comment:

Because the context is different. One runs with a mock environment ht other with no web environment. Due to this difference it will load a new application context.

To expand on this a little: The Spring testing infrastructure caches application contexts used for testing. If you use the same configuration for setting up the ApplicationContext in multiple tests, the ApplicationContext will be reused.

Since ATest and BTest use the same configuration they use the ApplicationContext instance. And since the execution of schema.sql and data.sql happens during construction of the ApplicationContext they get only executed once.

CTest uses a different configuration so the ApplicationContext has to get created freshly and therefore the scripts get executed again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...