我想測試連接到使用junit和嘲諷的休眠數據庫的方法。
這裏是我的代碼模擬測試不返回任何值Java Junit
UserDAO.java
public interface UserDAO {
public void addUser(String username, String password);
public List<String> getUsers();
}
UserDAOImpl.java
public class UserDAOImpl implements UserDAO {
public static final Logger LOG = LoggerFactory.getLogger(UserDAOImpl.class);
private static Session session;
public UserDAOImpl() {
}
public UserDAOImpl(Session session) {
this.session = session;
}
private static void beginSession() {
session = DbUtils.getSessionFactory().openSession();
session.beginTransaction();
}
@Override
public void addUser(String username, String password) {
String encryptedPassword = Utils.encrypt(password);
User user = new User(username, encryptedPassword);
beginSession();
try {
session.save(user);
System.out.println(user.getPassword());
session.getTransaction().commit();
} catch (SQLGrammarException e) {
session.getTransaction().rollback();
LOG.error("Cannot save user", e);
} finally {
session.close();
}
}
@Override
public List<String> getUsers() {
beginSession();
List<String> results = new ArrayList<String>();
String hql = "select username from User";
Query query = null;
try {
query = session.createQuery(hql);
results = query.list();
} catch (HibernateException e) {
LOG.error("Cannot execute query", e);
}
return results;
}
}
TestUserDAOImpl
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class TestUserDAOImpl {
@Mock
SessionFactory sessionFactory;
@Mock
Session session;
@Before
public void setup() {
when(sessionFactory.getCurrentSession()).thenReturn(session);
}
@Test
public void testCreate() {
// userDAOImpl = new UserDAOImpl(session);
UserDAOImpl userDAOImpl = Mockito.mock(UserDAOImpl.class);
String username = "username";
String password = "password";
userDAOImpl.addUser(username, password);
System.out.println(userDAOImpl.getUsers());
}
}
測試案例增加了一套用戶名和密碼的數據庫,但是當我嘗試使用getUsers()
返回結果它返回一個空列表。
任何人都可以請幫我解決這個問題嗎?
從您的'addUser'方法開始,您的真實對象永遠不會被調用,因爲您使用的是Mockito版本。 –
我該如何解決這個問題?即使在真實對象中調用addUser方法,也不應損壞主數據庫。 – Newbie