[英]How to write Unit test case for this method?
public String createUser() {
Session session = HibernateUtility.getSession();
Transaction tx = session.beginTransaction();
session.save(this);
tx.commit();
session.close();
return "accountCreated";
}
How to write Unit test case for this method? 如何为这种方法编写单元测试用例?
It is difficult to unit test code which contains calls to static methods, like HibernateUtility.getSession()
. 很难对包含对静态方法(例如HibernateUtility.getSession()
调用的代码进行单元测试。
You might consider injecting the Session instance (perhaps by adding a parameter to the createUser()
method, or by giving the object that contains this method a Session Factory
object which it can use to obtain Session
instances). 您可能考虑注入Session实例(也许通过向createUser()
方法中添加一个参数,或者通过给包含该方法的对象一个Session Factory
对象,它可以用来获取Session
实例)。 You could then use Mockito or a similar framework to provide a mock Session
object to the method, and verify that the expected calls where being made to it. 然后,您可以使用Mockito或类似的框架为该方法提供一个模拟Session
对象,并验证对它的预期调用。
public String createUser(Session session) {
Transaction tx = session.beginTransaction();
session.save(this);
tx.commit();
session.close();
return "accountCreated";
}
Using Mockito, a unit test might look like this: 使用Mockito,单元测试可能如下所示:
public testCreateUser(){
Session session = mock(Session.class);
Transaction trans = mock(Transaction.class);
when(session.beginTransaction()).thenReturn(trans);
obj.createUser(session);
verify(session).save(obj);
verify(session).close();
verify(trans).commit();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.