@DataJpaTest autowire dataSource

2.5k Views Asked by At

I'm using dbsetup framework to set up my database. I'm trying to test repository level (I'm using Spring data) using annotation @DataJpaTest. To set up a database using "dbsetup" I need to autowire the datasource, but I can't autowire because @DataJpaTest creates its own datasource and datasource already exists(but I don't know how to use it...). And the question is how can I autowire the datasource to set up my database using @DataJpaTest?

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource("/application-test.properties")
public class ArticleRepositoryTest {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private TagRepository tagRepository;
    @Autowired
    private UserRepository userRepository;
    //here is the error, because datasource already exists...
    @Autowired
    private DataSource dataSource;

    @Before
    public void cleanData() throws SQLException {
        Operation operation = sequenceOf(CommonOperations.DELETE_ALL);
        DbSetup dbSetup = new DbSetup(new DataSourceDestination(dataSource), operation);
        dbSetup.launch();

        DBUtil.resetAutoIncrementColumns(applicationContext, "article", "tag", "user");
    }
1

There are 1 best solutions below

3
On BEST ANSWER

Remove @DataJpaTest if you dont need autoconfigured database, @AutoConfigureTestDatabase creates a datasource based on the database you have configured in application-test.properties.