java - Unable to mock JdbcTemplate in testing spring boot service -


in test case service,i unable resolve dependency of dao class , jdbctemplate.

public class testpromotionusingjunit {      @injectmocks     private itemservice itemservice;      @mock     private itemdaoimpl itemdaoimpl;     @mock     private jdbctemplate jdbctemplate;      @before     public void setupmock() {         mockitoannotations.initmocks(this);          itemservice = new itemservice();      }      @test     public void testfindmax() {         product pro1 = new product();         pro1.setplucode("4900692627408");         pro1.setcategoryno("2");         pro1.setcategoryname("women");         pro1.setproductname("t-shirt10163");         pro1.setcolor("cy");         pro1.setsize("32");         bigdecimal b1 = new bigdecimal(94.00);         bigdecimal b2 = new bigdecimal(8);         pro1.setprice(b1);         pro1.settax(b2);         product pro2 = new product();         pro2.setplucode("4900692627408");          assertequals(pro1.getprice(), itemservice.getitem(pro1));      }  } 

here itemservice should return product object returns null. due internally unable solve dependency.

@injectmocks creates mock instance of itemservice, then

itemservice = new itemservice(); 

creates real instance , throws mock away. in setupmock(), after itemservice constructed, try adding equivalent of this:

itemservice.setitemdao(itemdaoimpl); 

so you'll have real itemservice uses mock dao.

then in testfindmax() configure dao return pro1, this:

when(itemdaoimpl.getitem(...)).thenreturn(pro1); 

Comments