C# Rhino模拟存根错误
我是模拟测试的新手,我已经使用RhinoMock创建了一个单元测试。 第一个存根正常运行,但第二个存根抛出空异常,代码如下C# Rhino模拟存根错误,c#,mstest,rhino-mocks,C#,Mstest,Rhino Mocks,我是模拟测试的新手,我已经使用RhinoMock创建了一个单元测试。 第一个存根正常运行,但第二个存根抛出空异常,代码如下 [TestMethod] public void TestMethod1() { SetUp(); //bind List ftsController and ftsEreceiptNumberPrefix MockRepository mocks = new MockRepository(); var fts
[TestMethod]
public void TestMethod1()
{
SetUp(); //bind List ftsController and ftsEreceiptNumberPrefix
MockRepository mocks = new MockRepository();
var ftsUnitOfWork = mocks.StrictMock<IFtsUnitOfWork>();
ftsUnitOfWork.Stub(x => x.Repository<FtsController>().Get()).Return(ftsController.AsQueryable());
ftsUnitOfWork.Stub(x =>
{
if (x.Repository<FtsPrefix>() == null)
{
throw new ArgumentNullException("Input cannot be null");
}
x.Repository<FtsPrefix>().Get();
}).Return(ftsPrefix.AsQueryable());
;
BoGeneratePrefix generateEreceiptPrefix = new BoGeneratePrefix (logger,ftsUnitOfWork);
generatePrefix.ProcessJob(null);
}
[TestMethod]
公共void TestMethod1()
{
SetUp();//绑定列表ftsController和ftsEreceiptNumberPrefix
MockRepository mocks=新建MockRepository();
var ftsUnitOfWork=mocks.StrictMock();
Stub(x=>x.Repository().Get()).Return(ftsController.AsQueryable());
ftsUnitOfWork.Stub(x=>
{
如果(x.Repository()==null)
{
抛出新ArgumentNullException(“输入不能为null”);
}
x、 Repository().Get();
}).Return(ftsPrefix.AsQueryable());
;
BoGeneratePrefix GenerateReceiptPrefix=新的BoGeneratePrefix(记录器,ftsUnitOfWork);
generatePrefix.ProcessJob(空);
}
ProcessJob:
public class BoGeneratePrefix : IBoDataPurging
{
#region private Variables
private readonly ILogger _logger;
private readonly IUnitOfWork _ftsUnitOfWork;
private readonly string _defaultTraceCategory;
#endregion
#region BoGeneratePrefix Constructor
/// <summary>
/// Initialized class oject BoGeneratePrefix
/// </summary>
/// <param name="logger"></param>
/// <param name="ftsUoW"></param>
public BoGeneratePrefix(ILogger logger, IFtsUnitOfWork ftsUoW)
{
_defaultTraceCategory = GetType().Name;
_logger = logger;
_ftsUnitOfWork = ftsUoW;
}
public void ProcessJob(Configuration hconfiguration)
{
try
{
var lstController = _ftsUnitOfWork.Repository<FtsController>().Get().Select(x => x. Id).Distinct().AsNoTracking();
foreach (var Id in lstController.ToList())
{
var prefix = _ftsUnitOfWork.Repository<FtsPrefix>()
.Get(x => x. Id == Id
&& x.Status == Constants.NotPrefix).Count();
var ignoreForLowerSafePoint =
_ftsUnitOfWork.Repository<ConfigurationParameter>()
.Get(y => y.ParamType == Constants.IgnoreForLowerSafePoint &&
y.ParamName == Id)
.AsNoTracking()
.Select(t => t.ParamValues).SingleOrDefault();
var currentTime = DateTime.ParseExact(DateTime.Now.ToString(Constants.HHmmssTime),
Constants.HHmmssTime,
System.Globalization.CultureInfo.InvariantCulture).TimeOfDay;
if ( !( hconfiguration.StartTime <= currentTime
&& hconfiguration.EndTime >= currentTime))
{
return;
}
}
}
catch (Exception ex)
{
throw;
}
}
公共类BoGeneratePrefix:ibodataprefix
{
#区域私有变量
专用只读ILogger\u记录器;
私人只读IUnitOfWork ftsUnitOfWork;
私有只读字符串_defaultTraceCategory;
#端区
#区域BoGeneratePrefix构造函数
///
///初始化类oject BOGEREPROFIX
///
///
///
公共BoGeneratePrefix(ILogger记录器,IFtsUnitOfWork ftsUoW)
{
_defaultTraceCategory=GetType().Name;
_记录器=记录器;
_ftsuonofwork=ftsUoW;
}
public void ProcessJob(配置hconfiguration)
{
尝试
{
var lstController=ftsUnitOfWork.Repository().Get().Select(x=>x.Id).Distinct().AsNoTracking();
foreach(lstController.ToList()中的变量Id)
{
var prefix=\u ftsUnitOfWork.Repository()
.Get(x=>x.Id==Id
&&x.Status==Constants.NotPrefix).Count();
var ignoreForLowerSafePoint=
_ftsUnitOfWork.Repository()
.Get(y=>y.ParamType==Constants.IgnoreForLowerSafePoint&&
y、 ParamName==Id)
.AsNoTracking()
.Select(t=>t.ParamValues).SingleOrDefault();
var currentTime=DateTime.ParseExact(DateTime.Now.ToString(Constants.hhmmstime),
常数.hhmmstime,
系统。全球化。文化信息。不变量文化)。时间;
如果(!(hconfiguration.StartTime=currentTime))
{
返回;
}
}
}
捕获(例外情况除外)
{
投掷;
}
}
存储库:
public interface IRepository<TEntity> : IDisposable where TEntity : class
{
/// <summary>
/// Delete the record from the database by accepting the input parameter as id
/// </summary>
/// <param name="id">Parameter id is used to delete record from the database</param>
void Delete(object id);
/// <summary>
/// Delete the enity
/// </summary>
/// <param name="entityToDelete"></param>
void Delete(TEntity entityToDelete);
/// <summary>
/// Get Queryable by passing the Expression
/// </summary>
/// <param name="filter">this is used for filter parameter/Expression of query</param>
/// <param name="orderBy">Passing condition of orderBy for query</param>
/// <param name="includeProperties">Properties to be included in to the query while generating the query on filter/order by</param>
/// <returns>Entity type Queryable i.e. creates query depend upon accepted entity type as input parameter</returns>
#pragma warning disable S2360
IQueryable<TEntity> Get(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "");
#pragma warning restore S2360
/// <summary>
/// Get Queryable by accepting the input parameter as modifiedSinceTimestamp
/// </summary>
/// <param name="modifiedSinceTimestamp"> modifiedSinceTimestamp </param>
/// <returns></returns>
IQueryable<TEntity> GetModifiedSince(long modifiedSinceTimestamp);
/// <summary>
/// Provides information of an entity by accepting the input parameters
/// </summary>
/// <param name="id">it gives the enity on the id condition </param>
/// <returns>Returns Entity </returns>
TEntity GetById(params object[] id);
/// <summary>
/// Inserts all changes made in this context as a Focus business transaction and enlists it for data insertion.
/// </summary>
/// <param name="entity">Entity i.e. object of generic type </param>
void Insert(TEntity entity);
/// <summary>
/// Gives information about which entity to update
/// </summary>
/// <param name="entityToUpdate">information about to update an enity</param>
void Update(TEntity entityToUpdate);
/// <summary>
///
/// </summary>
/// <param name="query"></param>
/// <param name="parameters"></param>
/// <returns></returns>
IEnumerable<TEntity> ExecWithStoreProcedure(string query, params object[] parameters);
/// <summary>
///
/// </summary>
/// <param name="entityToUpdate"></param>
void Detach(TEntity entityToUpdate);
}
公共接口IRepository:IDisposable其中tenty:class
{
///
///通过接受输入参数作为id从数据库中删除记录
///
///参数id用于从数据库中删除记录
作废删除(对象id);
///
///删除不完整性
///
///
无效删除(TEntity entityToDelete);
///
///通过传递表达式获取可查询性
///
///用于查询的筛选参数/表达式
///为查询传递orderBy的条件
///在按筛选/排序生成查询时要包含在查询中的属性
///实体类型可查询,即根据接受的实体类型作为输入参数创建查询
#pragma警告禁用S2360
IQueryable Get(表达式filter=null,Func orderBy=null,字符串includeProperties=“”);
#pragma警告恢复S2360
///
///通过接受输入参数作为modifiedSinceTimestamp获取可查询性
///
///修改的时间戳
///
IQueryable GetModifiedSince(长modifiedSinceTimestamp);
///
///通过接受输入参数提供实体的信息
///
///它给出了id条件下的enity
///返回实体
tenty GetById(params object[]id);
///
///将在此上下文中所做的所有更改作为焦点业务事务插入,并将其登记为数据插入。
///
///实体,即泛型类型的对象
无效插入(TEntity实体);
///
///提供有关要更新的实体的信息
///
///有关更新enity的信息
无效更新(TEntity entityToUpdate);
///
///
///
///
///
///
IEnumerable可执行存储过程(字符串查询,参数对象[]参数);
///
///
///
///
无效分离(TEntity entityToUpdate);
}
工作单元-
public class FtsUnitOfWork : IFtsUnitOfWork
{
#region local variables
private readonly ILogger _logger;
private IFtsDbProvider _ftsDbProvider;
private readonly string _defaultTraceCategory;
private DbContext _context;
private Hashtable _repositories;
#endregion local variables
/// <summary>
/// Constructor for Fts Unit Of Work
/// </summary>
/// <param name="logger"></param>
/// <param name="ftsDbProvider"></param>
public FtsUnitOfWork(ILogger logger, IFtsDbProvider ftsDbProvider)
{
_defaultTraceCategory = GetType().Name;
_logger = logger;
_logger.WriteTrace("FtsUnitOfWork: Initializing", _defaultTraceCategory);
_ftsDbProvider = ftsDbProvider;
_context = new FtsDbContext(_logger, "FtsDbStore", _ftsDbProvider.GetFtsDbCompiledModel());
_logger.WriteTrace("FtsUnitOfWork: Initialized", _defaultTraceCategory);
}
/// <summary>
/// Saves all changes made in this context as a Focus business transaction and enlists it for data consolidation.
/// </summary>
/// <returns></returns>
public virtual int Save()
{
try
{
return _context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
throw new Exception("Optimistic_Concurrency_Check");
}
}
/// <summary>
///
/// </summary>
/// <param name="focusDtTransactionId"></param>
/// <returns></returns>
public int Save(Guid focusDtTransactionId)
{
return _context.SaveChanges();
}
/// <summary>
/// Generic Repository this function creates the Repository by accepting the parameter as Entity type
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public IRepository<T> Repository<T>() where T : class
{
if (_repositories == null)
{
_repositories = new Hashtable();
}
var type = typeof(T).Name;
if (!_repositories.ContainsKey(type))
{
var repositoryType = typeof(Repository<>);
var repositoryInstance =
Activator.CreateInstance(repositoryType
.MakeGenericType(typeof(T)), _context);
_repositories.Add(type, repositoryInstance);
}
return (IRepository<T>)_repositories[type];
}
/// <summary>
///
/// </summary>
/// <typeparam name="T1"></typeparam>
/// <param name="sqlParameters"></param>
/// <param name="spName"></param>
/// <returns></returns>
public List<T1> GetMany<T1>(SqlParameter[] sqlParameters, string spName)
{
return _context.Database.SqlQuery<T1>(spName, sqlParameters).ToList();
}
/// <summary>
///
/// </summary>
/// <param name="isolationLevel"></param>
/// <returns></returns>
public DbContextTransaction GetDbContextTransaction(IsolationLevel isolationLevel)
{
return _context.Database.BeginTransaction(isolationLevel);
}
#region IDisposable Support
private bool _disposedValue; // To detect redundant calls
/// <summary>
///
/// </summary>
/// <param name="disposing"></param>
public virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
_logger.WriteTrace("FtsUnitOfWork: Disposing", _defaultTraceCategory);
_ftsDbProvider = null;
_repositories = null;
this._context.Dispose();
this._context = null;
_logger.WriteTrace("FtsUnitOfWork: Disposed", _defaultTraceCategory);
}
_disposedValue = true;
}
}
/// <summary>
///
/// </summary>
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
公共类FtsUnitOfWork:IFtsUnitOfWork
{
#区域局部变量
专用只读ILogger\u记录器;
私人IFtsDbProvider ftsDbProvider;
私有只读字符串_defaultTraceCategory;
私有DbContext _context;
私有哈希表存储库;
#端域局部变量
///
///Fts工作单元的建造师
///
///
///
公共FtsUnitOfWork(ILogger记录器、IFtsDbProvider FTSDDBProvider)
{
_defaultTraceCategory=GetType().Name;
_记录器=记录器;
_WriteTrace(“FtsUnitOfWork:initialization”,_defaultTraceCategory);
_ftsDbProvider=ftsDbProvider;
_context=new FtsDbContext(_logger,“FtsDbStore”,_ftsDbProvider.getftsdbcomiledmodel());
_WriteTrace(“FtsUnitOfWork:Initialized”,\u defaultTraceCategory);
}
///
///将在此上下文中所做的所有更改保存为焦点业务事务,并将其登记用于数据整合。
///
///
公共虚拟整数保存()
{
尝试
{
返回_context.SaveChanges();
}
捕获(DbUpdateConcurrencyException ex)
{
抛出新异常(“乐观并发检查”);
}
}
///
///
///
///
///
公共i