12

Here https://stackoverflow.com/a/52968130/10894456 is well explained why @DataJpaTest @SpringBootTest shouldn't be mixed in one application.

But barely explained the case when anyway need to test every layer of MVC SpringBoot application (from my point it's natural to test not only one or only another layer but both and even all layers, isn't it?)

So there was suggested a solution to use @AutoConfigureTestDatabase rather than @DataJpaTest but didn't finish the job (((

So my question is: is using @AutoConfigureTestDatabase an appropriate solution? If yes, please explain details. If no, please suggest more appropriate solution, thank you

J.J. Beam
  • 2,612
  • 2
  • 26
  • 55
  • Yes, like already answered, it is an appropriate solution. What details do you need? It's not clear what it is that you're asking. – eis Apr 24 '19 at 20:49
  • Just substitute DataJpaTest <---> AutoConfigureTestDatabase and everything it's ok? – J.J. Beam Apr 24 '19 at 20:51
  • you want to combine SpringBootTest and AutoConfigureTestDatabase. Added as an answer. – eis Apr 25 '19 at 05:05

2 Answers2

15

Assuming you want the full application with the exception of database being in-memory, yes, combining @SpringBootTest with @AutoConfigureTestDatabase is an appropriate solution, as it does just that.

It is also mentioned in the documentation of @DataJpaTest:

If you are looking to load your full application configuration, but use an embedded database, you should consider @SpringBootTest combined with @AutoConfigureTestDatabase rather than this annotation.

eis
  • 51,991
  • 13
  • 150
  • 199
  • And what about you need full application? With database real connection too. Do I need to use @AutoConfigureTestDatabase(replace=Replace.NONE) ? As said here: https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/html/boot-features-testing.html – Douglas Silva Apr 28 '22 at 15:47
1

I trie using the @AutoConfigureTestDatabase thing, but it did not worked, then, I found this Spring H2 Test DB does not reset before each test and adding @Transactional worked!

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
@Transactional
public class ClippingControllerTest {

Related questions:

  1. How to test Spring CrudRepository using @DataJpaTest in Spring boot 2.1.0.M4 using Junit 5
  2. Error while testing: found multiple declaration of @BootstrapWith for test class
  3. Database cleanup after Junit tests

Related articles:

  1. https://brightinventions.pl/blog/clear-database-in-spring-boot-tests/
  2. https://medium.com/@dSebastien/cleaning-up-database-tables-after-each-integration-test-method-with-spring-boot-2-and-kotlin-7279abcdd5cc
  3. https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-testing
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144