簡體   English   中英

我無法在Spring Boot應用程序中使用Mockito模擬Dao方法

[英]I am not able to mock the Dao method using mockito in Spring boot application

我無法在春季啟動時模擬Dao方法。 請讓我知道我在下面的代碼中做錯了什么。 我嘗試使用SpringJUnit4ClassRunner並模擬Dao方法。 但是,它仍將進入Dao方法,而不是返回模擬值。 我也嘗試過使用MockitoJUnitRunner,但是那一次由於它獲取空值而無法調用service方法。

@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);

    }

}

您不需要@InjectMocks並使用@MockBean代替@Mock

@Autowired
HomeController homeController;

@MockBean
HomeDao homeDao;

也不需要這部分:

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM