Reputation: 3
I am not able to mock Dao method in spring boot. Please let me know what I am doing wrong in below code. I tried using SpringJUnit4ClassRunner and mock the Dao method. But still, it's going into the Dao method instead of returning the mock value. I also tried with MockitoJUnitRunner but that time not able to call the service method as its getting null value.
@RestController
public class HomeController {
@Autowired
HomeSeriveInterface service;
@Autowired
HomeDaoImpl homeDao;
@GetMapping(value="/getData")
public String Data() {
System.out.println("Inside Controller");
List < Map < String, Object >> rows = service.getData();
return "Hi Yogita" + rows;
}
}
@Service
public class HomeService implements HomeSeriveInterface{
@Autowired
HomeDao dao;
@Override
public List<Map<String, Object>> getData() {
System.out.println("Inside Service");
return dao.getData();
}
}
@Repository
public class HomeDaoImpl implements HomeDao{
@Autowired
@Qualifier("jdbcTemplate1")
private JdbcTemplate jdbcTemplate;
@Override
public List < Map < String, Object >> getData() {
System.out.println("Inside Dao");
List < Map < String, Object >> rows = jdbcTemplate.queryForList("SELECT * FROM COURCES");
return rows;
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class CcdWebApplicationTests {
@InjectMocks
@Autowired
HomeController homeController;
@Mock
HomeDao homeDao;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
@Test
public void getDataTest() {
System.out.println("testing *******");
List < Map < String, Object >> data = null;
Mockito.when(homeDao.getData())
.thenReturn(data);
System.out.println("2nd *");
String data2 = homeController.Data();
System.out.println(data2);
}
}
Upvotes: 0
Views: 2342
Reputation: 26522
You don't need @InjectMocks
and use @MockBean
instead of @Mock
:
@Autowired
HomeController homeController;
@MockBean
HomeDao homeDao;
You also do not need this part:
@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
Upvotes: 1