我正在尝试测试使用dao的类。在我的测试类中,我已经模拟了DAO并将模拟注入到我测试的类的实例中。我正在尝试制作DAO类的假对象。
@RunWith(MockitoJUnitRunner.class)
public class UserManagerTest {
@Mock
private UserManagerDao umDao;
@InjectMocks
private UserManager um = new UserManager();
@Before
public void initializeMockito() {
MockitoAnnotations.initMocks(this);
}
public void testGetUserId() {
}
这是UserManager.class和Dao类
中的方法userManager.class
public long getUserId(String email) throws Exception {
String[] partsOfMail = email.split("@");
return umDao.getUserId(partsOfMail[0], partsOfMail[1]);
}
Dao class
public long getUserId(String userName, String domain) throws Exception {
String sql = msa.getMessage("sql.select.user_id");
Object[] params = new Object[] { userName, domain };
List<Long> result = getJdbcTemplate().queryForList(sql, params, Long.class);
if (result.size() > 0) {
return result.get(0);
}
return 0;
}
答案 0 :(得分:1)
见评论:
@RunWith(MockitoJUnitRunner.class)
public class UserManagerTest {
@Mock
private UserManagerDao umDao; // a mock object should present here
/* @InjectMocks should be able to create an instance
with mocks injected for you - you don't need to create it
yourself */
@InjectMocks
private UserManager um; // = new UserManager();
/* Not required as you're using the MockitoJUnitRunner
@Before
public void initializeMockito() {
MockitoAnnotations.initMocks(this);
} */
// Add test annotation (assuming JUnit4 as you're not extending TestCase)
@Test
public void testGetUserId() {
// Both these fields should not be null
Assert.assertNotNull(umDao);
Assert.assertNotNull(um);
}
有关详细信息,请查看MockitoJUnitRunner
和InjectMocks
文档。
Mockito的文档,其中包含许多示例,可以找到here。
答案 1 :(得分:0)
你的问题是什么?如果你问如何在DAO中模拟一些方法,这是一个简单的例子。
@Test
public void testGetUserId() {
when(umDao.getUserId(<PARS>)).thenReturn(1L);
assertThat(um.getUserId(<PAR>)).isEqualTo(1L);
}