0

I have a test сlass with a method where I add some data to the database and then retrieve it and check if the data is the same:

public class QueryImplTest {
    @Autowired
    Jdbc jdbcTemplate;
    
    QueryImpl queryImpl = new QueryImpl(jdbcTemplate);
    
    @Test
    public void someTest() {
    SomeObject someExpectedObject = new SomeObject(//object 
    queryImpl.saveSomeObject(someExpectedObject)
    SomeObject someRealObject = jdbcTemplate.queryForObject(SELECT_OBJECT_QUERY, SomeObject.Class)
    //all of the Assertions

}

And I get a Cannot invoke JdbcTemplate.update()(from saveSomeObject method) because this.jdbcTemplate is null

The QueryImpl class:

@Repository
public class QueryImpl {
    
    private JdbcTemplate jdbcTemplate;
    @Autowired
    public QueryImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    //methods and query strings

}
  • For `QueryImpl` try to autowire `JdbcTemplate jdbcTemplate` as constructor parameter instead of field on. Than in `QueryImplTest ` you can init queryImpl by providing `jdbcTemplate` as parameter: `QueryImpl queryImpl = new QueryImpl(jdbcTemplate);` – artiomi Oct 10 '22 at 16:54
  • @artiomi, I tried that now, didn't work, got the same mistake – razzledazzle88 Oct 10 '22 at 16:57
  • Your unit test doesn't seem to be managed by Spring, so `@AutoWired` **does nothing**, in addition, even if it were managed, it would be set **after** `new QueryImpl(jdbcTemplate)` was already executed. – Mark Rotteveel Oct 11 '22 at 09:34
  • You're right, I had no @Runner annotation – razzledazzle88 Oct 11 '22 at 13:08

1 Answers1

0

I can see you are Autowiring Jdbc class in the test case. That is incorrect. Please use JdbcTemplate class. Here is the fixed version of your test case.

@JdbcTest
public class QueryImplTest {
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    QueryImpl queryImpl = new QueryImpl();
    
    @Test
    public void someTest() {
    SomeObject someExpectedObject = new SomeObject(//object 
    queryImpl.saveSomeObject(someExpectedObject)
    SomeObject someRealObject = jdbcTemplate.queryForObject(SELECT_OBJECT_QUERY, SomeObject.Class)
    //all of the Assertions

}

If you need more details please read this article. https://www.baeldung.com/spring-jdbctemplate-testing

Rohit Agarwal
  • 763
  • 2
  • 5
  • 10