Al *_*den 1 c# testing nhibernate delegates rhino-mocks
我正在使用Rhino模拟来改变NHibernate DAL的行为,这样当代码调用commit事务时,模拟框架会改变行为,从而回滚事务.我这样做的原因是对于集成测试,但我不想向数据库添加任何数据.
这是我测试的方法/类:
public class NHibernateDALSave<T> : IBaseDALSave<T> where T : class
{
protected ISession _session;
protected ISessionFactory _sessionFactory;
public NHibernateDALSave()
{
_sessionFactory = new Configuration().Configure().BuildSessionFactory();
}
public NHibernateDALSave(ISessionFactory sessionFactory)
{
_sessionFactory = sessionFactory;
}
public void OpenSession()
{
if (_sessionFactory == null)
{
_sessionFactory = new Configuration().Configure().BuildSessionFactory();
}
_session = _sessionFactory.OpenSession();
}
public virtual int Save(T objectToSave)
{
this.OpenSession();
using (_session)
{
using (ITransaction tx = _session.BeginTransaction())
{
try
{
Int32 NewId = Convert.ToInt32(_session.Save(objectToSave));
_session.Flush();
tx.Commit();
return NewId;
}
catch (Exception)
{
tx.Rollback();
throw;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是测试代码:
public void SaveEmployee_Blank_Success()
{
//setup employee object to save
EmployeeDataContext employee = new EmployeeDataContext();
employee.Person = new PersonDataContext();
employee.PayRollNo = "12345";
employee.Person.Surname = "TEST";
//stub classes
ISessionFactory SessionFactoryStub = MockRepository.GenerateMock<ISessionFactory>();
ISession SessionStub = MockRepository.GenerateMock<ISession>();
ITransaction TranStub = MockRepository.GenerateMock<ITransaction>();
//Actual classes
ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();
ISession Session = sessionFactory.OpenSession();
ITransaction Tran = Session.BeginTransaction();
try
{
//Configure to prevent commits to the database
SessionStub.Stub(ss => ss.BeginTransaction()).Return(TranStub);
SessionStub.Stub(ss => ss.Save(Arg<EmployeeDataContext>.Is.Anything)).Do((Action)delegate { Session.Save(employee); });
SessionStub.Stub(ss => ss.Flush()).Do((Action)delegate { Session.Flush(); });
TranStub.Stub(ts => ts.Commit()).Do((Action)delegate { Tran.Rollback(); });
TranStub.Stub(ts => ts.Rollback()).Do((Action)delegate { Tran.Rollback(); });
SessionFactoryStub.Stub(sf => sf.OpenSession()).Return(SessionStub);
NHibernateDALSave<EmployeeDataContext> target = new NHibernateDALSave<EmployeeDataContext>(SessionFactoryStub);
target.Save(employee);
}
catch
{
Tran.Rollback();
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是"回调参数与方法参数委托"不匹配,这发生在try,catch块开始后的第二行.
任何人都可以帮我解决此错误消息的含义以及我可以做些什么来解决这个问题?或者有没有人建议如何与Nhibernate进行集成测试?
人
我没有使用RhinoMocks,但我使用过其他模拟框架.我认为问题是你的Save方法只接受一个参数,但你提供给回调Do方法的委托不接受参数.
该行应该是这样的:
SessionStub.Stub(ss => ss.Save(Arg<EmployeeDataContext>.Is.Anything)).Do(arg => Session.Save(employee))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3219 次 |
| 最近记录: |