MVCContrib TestHelper problem with session.clear, session.abandon and Rhino Mock - asp.net-mvc-2

Hi I'm trying to unit test my logout action on my controller but I have hard times to test or stub my Session in the HttpContext. I'm using MVC Contrib TestHelper to make it easier but now I need a little help.
Here's my test :
[TestFixture]
public class SessionControllerTest
{
private ISession _session;
private IConfigHelper _configHelper;
private IAuthenticationService _authService;
//private IMailHelper _mailHelper;
private ICryptographer _crypto;
private SessionController _controller;
private TestControllerBuilder _builder;
private MockRepository _mock;
[SetUp]
public void Setup()
{
_mock = new MockRepository();
_session = _mock.DynamicMock<ISession>();
_configHelper = _mock.DynamicMock<IConfigHelper>();
_authService = _mock.DynamicMock<IAuthenticationService>();
//_mailHelper = _mock.DynamicMock<IMailHelper>();
_crypto = _mock.DynamicMock<ICryptographer>();
_controller = new SessionController(_authService, _session, _crypto, _configHelper);
_builder = new TestControllerBuilder();
_builder.InitializeController(_controller);
}
[Test]
public void Logout_ReturnRedirectToAction()
{
_builder.InitializeController(_controller);
_authService.SignOut();
LastCall.Repeat.Once();
_builder.Session["memberNumber"] = string.Empty;
LastCall.Repeat.Once();
_controller.Session.Clear();
LastCall.Repeat.Any();
_controller.Session.Abandon();
LastCall.Repeat.Any();
//_builder.Session.Stub(s => s.Clear());
//_builder.Session.Stub(s => s.Abandon());
//_builder.Session.Clear();
//LastCall.Repeat.Once();
//_builder.Session.Abandon();
//LastCall.Repeat.Once();
_mock.ReplayAll();
var result = _controller.Logout();
_mock.VerifyAll();
result.AssertActionRedirect().ToAction<SessionController>(c => c.Login());
}
You can see my differents attemps. I get an error telling me that Session.Abandon() is not implemented, witch is right when you take a look at MVCContrib's TestHelper. But how can I mock or Stub the Session that's already mocked by the TestHelper?
The Exception in NUnit :
System.NotImplementedException : The
method or operation is not
implemented. at
MvcContrib.TestHelper.MockSession.Abandon()
Thank you for the help!
EDIT : Here's the new working test
[Test]
public void Logout_ReturnRedirectToAction()
{
_builder.InitializeController(_controller);
var mockSession = _mock.Stub<HttpSessionStateBase>();
_controller.HttpContext.BackToRecord();
_controller.HttpContext.Stub(c => c.Session).Return(mockSession);
_controller.HttpContext.Replay();
_authService.SignOut();
LastCall.Repeat.Once();
_builder.Session["memberNumber"] = string.Empty;
_controller.Session.Clear();
LastCall.Repeat.Once();
_controller.Session.Abandon();
LastCall.Repeat.Once();
_mock.ReplayAll();
var result = _controller.Logout();
_mock.VerifyAll();
result.AssertActionRedirect().ToAction<SessionController>(c => c.Login());
}

It's been a while since I used MvcContrib, so I pulled down the latest code and made a quick test project. It's very odd. Looking at the MvcContrib code (specifically, TestControllerBuilder), it creates mocks for most of the objects (request, response, server, etc...), but not for Session. I'm not sure why this is -- probably have to ask the creators.
However, there is a way to mock it yourself. You can create your own mock session and tell the controller to use yours instead of the one from MvcContrib.TestHelpers. Here's what I did in my test:
var mockSession = MockRepository.GenerateStub<HttpSessionStateBase>();
controller.HttpContext.BackToRecord();
controller.HttpContext.Stub(c => c.Session).Return(mockSession);
controller.HttpContext.Replay();
Now I run my controller method and then use Rhino.Mocks' AAA syntax for making sure the Abandon method was called:
controller.Session.AssertWasCalled(s => s.Abandon());
If you want to use record/replay semantics, you could set your expectations before calling controller.HttpContext.Replay().

Related

How to mock Entity Framework in a N-Layer Architecture

I have a N-Layer application with Entity Framework (Code-First approach). Now I want to automatize some tests. I am using Moq framework. I am finding some problem about writing the tests. Perhaps my architecture is wrong? With wrong, I mean that I wrote components that are not well isolated and so they are not testable. I do not really like this... Or perhaps, I simply cannot use correctly moq framework.
I let you see my architecture:
At every level I inject my context in the constructor of the class.
The Facade:
public class PublicAreaFacade : IPublicAreaFacade, IDisposable
{
private UnitOfWork _unitOfWork;
public PublicAreaFacade(IDataContext context)
{
_unitOfWork = new UnitOfWork(context);
}
}
The BLL:
public abstract class BaseManager
{
protected IDataContext Context;
public BaseManager(IDataContext context)
{
this.Context = context;
}
}
The Repository:
public class Repository<TEntity>
where TEntity : class
{
internal PublicAreaContext _context;
internal DbSet<TEntity> _dbSet;
public Repository(IDataContext context)
{
this._context = context as PublicAreaContext;
}
}
IDataContext is an interface that is implemented by my DbContext:
public partial class PublicAreaContext : DbContext, IDataContext
Now, how I mock EF and how I write the tests:
[TestInitialize]
public void Init()
{
this._mockContext = ContextHelper.CreateCompleteContext();
}
Where ContextHelper.CreateCompleteContext() is:
public static PublicAreaContext CreateCompleteContext()
{
//Here I mock my context
var mockContext = new Mock<PublicAreaContext>();
//Here I mock my entities
List<Customer> customers = new List<Customer>()
{
new Customer() { Code = "123455" }, //Customer with no invoice
new Customer() { Code = "123456" }
};
var mockSetCustomer = ContextHelper.SetList(customers);
mockContext.Setup(m => m.Set<Customer>()).Returns(mockSetCustomer);
...
return mockContext.Object;
}
And here how I write my test:
[TestMethod]
public void Success()
{
#region Arrange
PrepareEasyPayPaymentRequest request = new PrepareEasyPayPaymentRequest();
request.CodiceEasyPay = "128855248542874445877";
request.Servizio = "MyService";
#endregion
#region Act
PublicAreaFacade facade = new PublicAreaFacade(this._mockContext);
PrepareEasyPayPaymentResponse response = facade.PrepareEasyPayPayment(request);
#endregion
#region Assert
Assert.IsTrue(response.Result == it.MC.WebApi.Models.ResponseDTO.ResponseResult.Success);
#endregion
}
Here It seems It works everything correctly!!! And It looks like my architecture is correct. But what if I want to insert/update an Entity? Nothing work anymore! I explain why:
As you can see I pass a *Request object (it is the DTO) to the facade, then in my TOA I generate my entity from the propertiess of the DTO:
private PaymentAttemptTrace CreatePaymentAttemptTraceEntity(string customerCode, int idInvoice, DateTime paymentDate)
{
PaymentAttemptTrace trace = new PaymentAttemptTrace();
trace.customerCode = customerCode;
trace.InvoiceId = idInvoice;
trace.PaymentDate = paymentDate;
return trace;
}
PaymentAttemptTrace is the Entity I will inserto to Entity Framework.. It is not mocked and I cannot inject it. So even if I pass my mocked context (IDataContext), when I try to insert an Entity that is not mocked my test fails!
Here that doubt about I have a wrong architecture has raised!
So, what's wrong? The architecture or the way I use moq?
Thank you for help
UPDATE
Here how I test my code.. For example, I want to test the trace of a payment..
Here the test:
[TestMethod]
public void NoPaymentDate()
{
TracePaymentAttemptRequest request = new TracePaymentAttemptRequest();
request.AliasTerminale = "MyTerminal";
//...
//I create my request object
//You can see how I create _mockContext above
PublicAreaFacade facade = new PublicAreaFacade(this._mockContext);
TracePaymentAttemptResponse response = facade.TracePaymentAttempt(request);
//My asserts
}
Here the facade:
public TracePaymentAttemptResponse TracePaymentAttempt(TracePaymentAttemptRequest request)
{
TracePaymentAttemptResponse response = new TracePaymentAttemptResponse();
try
{
...
_unitOfWork.PaymentsManager.SavePaymentAttemptResult(
easyPay.CustomerCode,
request.CodiceTransazione,
request.EsitoPagamento + " - " + request.DescrizioneEsitoPagamento,
request.Email,
request.AliasTerminale,
request.NumeroContratto,
easyPay.IdInvoice,
request.TotalePagamento,
paymentDate);
_unitOfWork.Commit();
response.Result = ResponseResult.Success;
}
catch (Exception ex)
{
response.Result = ResponseResult.Fail;
response.ResultMessage = ex.Message;
}
return response;
}
Here how I developed the PaymentsManager:
public PaymentAttemptTrace SavePaymentAttemptResult(string customerCode, string transactionCode, ...)
{
//here the problem... PaymentAttemptTrace is the entity of entity framework.. Here i do the NEW of the object.. It should be injected, but I think it would be a wrong solution
PaymentAttemptTrace trace = new PaymentAttemptTrace();
trace.customerCode = customerCode;
trace.InvoiceId = idInvoice;
trace.PaymentDate = paymentDate;
trace.Result = result;
trace.Email = email;
trace.Terminal = terminal;
trace.EasypayCode = transactionCode;
trace.Amount = amount;
trace.creditCardId = idCreditCard;
trace.PaymentMethod = paymentMethod;
Repository<PaymentAttemptTrace> repository = new Repository<PaymentAttemptTrace>(base.Context);
repository.Insert(trace);
return trace;
}
In the end how I wrote the repository:
public class Repository<TEntity>
where TEntity : class
{
internal PublicAreaContext _context;
internal DbSet<TEntity> _dbSet;
public Repository(IDataContext context)
{
//the context is mocked.. Its type is {Castle.Proxies.PublicAreaContextProxy}
this._context = context as PublicAreaContext;
//the entity is not mocked. Its type is {PaymentAttemptTrace} but should be {Castle.Proxies.PaymentAttemptTraceProxy}... so _dbSet result NULL
this._dbSet = this._context.Set<TEntity>();
}
public virtual void Insert(TEntity entity)
{
//_dbSet is NULL so "Object reference not set to an instance of an object" exception is raised
this._dbSet.Add(entity);
}
}
Your architecture looks good, but the implementation is flawed. It is leaking abstraction.
In your diagram the Façade layer depends only on the BLL but when you look at the PublicAreaFacade's constructor you will see that in reality it has a direct dependency to an interface from the Repository layer:
public PublicAreaFacade(IDataContext context)
{
_unitOfWork = new UnitOfWork(context);
}
This should not be. It should only take its direct dependency as input -- the PaymentsManager or -- even better -- an interface of it:
public PublicAreaFacade(IPaymentsManager paymentsManager)
{
...
}
The concequence is that your code becomes way more testable. When you look at your tests now you see that you have to mock the most inner layer of your system (i.e. the IDataContext and even its entity accessors Set<TEntity>) altough you are testing one of the most outer layers of your system (the PublicAreaFacade class).
This is how a unit test for the TracePaymentAttempt method would look like if the PublicAreaFacade only depended on IPaymentsManager:
[TestMethod]
public void CallsPaymentManagerWithRequestDataWhenTracingPaymentAttempts()
{
// Arrange
var pm = new Mock<IPaymentsManager>();
var pa = new PulicAreaFacade(pm.Object);
var payment = new TracePaymentAttemptRequest
{
...
}
// Act
pa.TracePaymentAttempt(payment);
// Assert that we call the correct method of the PaymentsManager with the data from
// the request.
pm.Verify(pm => pm.SavePaymentAttemptResult(
It.IsAny<string>(),
payment.CodiceTransazione,
payment.EsitoPagamento + " - " + payment.DescrizioneEsitoPagamento,
payment.Email,
payment.AliasTerminale,
payment.NumeroContratto,
It.IsAny<int>(),
payment.TotalePagamento,
It.IsAny<DateTime>()))
}
Pass IUnitOfWork into the Facade or BLL layer constructor, whichever one makes calls on the unit of work directly. Then you can setup what the Mock<IUnitOfWork> is returning in your tests. You should not need to pass IDataContext to everything except maybe the repo constructors and the unit of work.
For example, if the Facade has a method PrepareEasyPayPayment that makes a repo call through a UnitOfWork call, setup the mock like this:
// Arrange
var unitOfWork = new Mock<IUnitOfWork>();
unitOfWork.Setup(x => x.PrepareEasyPayPaymentRepoCall(request)).Returns(true);
var paymentFacade = new PaymentFacade(unitOfWork.Object);
// Act
var result = paymentFacade.PrepareEasyPayPayment(request);
Then you've mocked out the data call and can more easily test your code in the Facade.
For the insert testing, you should have a Facade method like CreatePayment which takes a PrepareEasyPayPaymentRequest. Inside that CreatePayment method, it should reference the repo, probably through the unit of work, like
var result = _unitOfWork.CreatePaymentRepoCall(request);
if (result == true)
{
// yes!
}
else
{
// oh no!
}
What you want to mock for unit testing is that this create/insert repo call returns true or false so you can test the code branches after the repo call has completed.
You can also test that the insert call was made as expected, but that's usually not as valuable unless the parameters for that call have a lot of logic involved in building them.
it sounds like you need to change the code a little bit. Newing things introduces hardcoded dependencies and makes them untestable, so try to abstract them away. Maybe you can hide everything to do with EF behind another layer, then all you have to do is mock that particular layer layer and never touch EF.
You can use this open source framework for unit testing which is good to mock entity framework dbcontext
https://effort.codeplex.com/
Try this will help you to mock your data efficiently.

Testing code in a custom NancyFx Bootstrapper

I have a custom Nancy Bootstrapper which uses StructureMapNancyBootstrapper but the issue is the same regardless of container.
public class CustomNancyBootstrapper : StructureMapNancyBootstrapper
{
protected override void RequestStartup(IContainer container, IPipelines pipelines, NancyContext context)
{
var auth = container.GetInstance<ICustomAuth>();
auth.Authenticate(context);
}
}
I want to write a test to assert that Authenticate is called with the context... something like this...
[Test]
public void RequestStartup_Calls_CustomAuth_Authenticate_WithContext()
{
// set up
var mockAuthentication = new Mock<ICustomAuth>();
var mockContainer = new Mock<IContainer>();
var mockPipelines = new Mock<IPipelines>();
var context = new NancyContext();
mockContainer.Setup(x => x.GetInstance<ICustomAuth>()).Returns(mockAuthentication.Object);
// exercise
_bootstrapper.RequestStartup(_mockContainer.Object, _mockPipelines.Object, context);
// verify
mockAuthentication.Verify(x => x.Authenticate(context), Times.Once);
}
The problem is that I can't call RequestStartup because it's protected as defined in NancyBootstrapperBase.
protected virtual void RequestStartup(TContainer container, IPipelines pipelines, NancyContext context);
Is there a "proper"/"offical" Nancy way to do this without creating another derived class and exposing the methods as that just seems like a hack?
Thanks
I guess you can "fake" the request by using Browser from Nancy.Testing:
var browser = new Browser(new CustomNancyBootstrapper());
var response = browser.Get("/whatever");
There is a good set of articles about testing NancyFx application:
http://www.marcusoft.net/2013/01/NancyTesting1.html
Turns out Nancy offers a IRequetStartup interface so you can take the code out of the custom bootstrapper and do something like this...
public class MyRequestStart : IRequestStartup
{
private readonly ICustomAuth _customAuthentication;
public MyRequestStart(ICustomAuth customAuthentication)
{
if (customAuthentication == null)
{
throw new ArgumentNullException(nameof(customAuthentication));
}
_customAuthentication = customAuthentication;
}
public void Initialize(IPipelines pipelines, NancyContext context)
{
_customAuthentication.Authenticate(context);
}
}
and the test is easy and concise
[Test]
public void When_Initialize_Calls_CustomAuth_Authenticate_WithContext()
{
// set up
var mockAuth = new Mock<ICustomAuth>();
var requestStartup = new MyRequestStart(mockAuth.Object);
var mockPipeline = new Mock<IPipelines>();
var context = new NancyContext();
// exercise
requestStartup.Initialize(mockPipeline.Object, context);
// verify
mockAuth.Verify(x => x.Authenticate(context), Times.Once);
}
https://github.com/NancyFx/Nancy/wiki/The-Application-Before%2C-After-and-OnError-pipelines#implementing-interfaces

Autofac.Extras.Quartz with ConcurrentExecutionDisallowed not working

In my Windows service I am using Quartz.net together with Autofac. To assist me here I am using the Nuget Autofac.Extras.Quartz.
So far so good, but when I try to apply the DisallowConcurrencyExecution attribute it is ignored and multiple jobs are spawned.
I am using as follows:
REGISTRATION
builder.RegisterModule(new QuartzAutofacFactoryModule());
builder.RegisterType<CompanyDatabaseProcessor>().As<IJob>().InstancePerLifetimeScope();
SETUP
var fact = container.Resolve<IJobFactory>();
_scheduler = StdSchedulerFactory.GetDefaultScheduler();
_scheduler.JobFactory = fact;
_scheduler.Start();
var job = JobBuilder.Create<IJob>()
.WithIdentity("QProcJob", "A3Group")
.Build();
var trigger = TriggerBuilder.Create()
.WithIdentity("QProcTrigger", "A3Group")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(executeEvery)
.RepeatForever())
.Build();
_scheduler.ScheduleJob(job, trigger);
and when in my IJob, I check the context.JobDetail.ConcurrentExecutionDisallowed it is always set to false.
I see this question is old, but I encountered the same problem and I going to post my solution, so it could be useful to someone.
The problem is that when you use JobFactory, the type of your job is unknown to quartz, so he assigns an internal type (NoOpJob) that is not decorated with DisallowConcurrentExecution attribute, causing that JobDetailImpl(the class that is used by quartz.net for IJobDetail) return false in ConcurrentExecutionDisallowed property.
What I did was a simple class that inherits from JobDetailImpl and add an extensions method Build to the JobBuilder class to maintain the same fluent code in the job creation. Here is the code:
public class SingleJobDetail : JobDetailImpl
{
public SingleJobDetail() : base()
{
}
public override bool ConcurrentExecutionDisallowed => true;
}
public static class JobHelper
{
public static IJobDetail Build(this JobBuilder builder, bool disallowConcurrent)
{
var job = builder.Build();
if (!disallowConcurrent)
return job;
var singleJob = new SingleJobDetail();
singleJob.JobType = job.JobType;
singleJob.Description = job.Description;
singleJob.Key = job.Key;
singleJob.Durable = job.Durable;
singleJob.RequestsRecovery = job.RequestsRecovery;
if (!singleJob.JobDataMap.IsEmpty)
singleJob.JobDataMap = job.JobDataMap;
return singleJob;
}
}
And in the job creation:
var job = JobBuilder.Create().WithIdentity(id).Build(true);

Why are my WCF Async with Rx unit tests unstable?

I am using Rx and RxUI in a MVVM project and have a view model that queries its data from a WCF service asynchronously. In the unit tests I create a mock object that returns a Task with the expected value.
Here's a general idea of what my view model looks like
public class ViewModel : ReactiveObject
{
private IContext _context;
public ViewModel(IContext context)
{
_context = context;
Observable.FromAsync(() => _context.WcfServiceCall())
.Subscribe(result => {
Children.AddRange(results.Select(r => new ChildViewModel(r).ToList()));
});
}
public ObservableCollection<ChildViewModel> { get; private set;}
}
My unit test looks like this
[TestFixture]
public class ViewModelTest : AssertionHelper
{
[Test]
public void ShouldSetChildren()
{
var c = new Mock<IContext>();
c.Setup(q => q.WcfServiceCall())
.Returns(Task.Run(() => new []{ 1,2,3,4,5,6 })):
var vm = new ViewModel(c.Object);
var p = vm.Children.First(); // this call sometimes fails
...
}
}
The issue I'm having is that I have over 400 tests that do this sort of thing and they all work most of the time but I randomly get failed tests, one or two at a time, that report the sequence has no values. This is unpredictable and random. I can run the tests again after a failure and all succeed. I have added the TestScheduler as described here but the problems persist.
Is there a better way to test methods that make asynchronous method calls?
Edit from Paul Bett's input:
I see FromAsync does not take an IScheduler parameter but I do have SubscribeOn and ObserveOn available.
Alternatively, I could call the WCF async method directly and convert the returned Task to an observable. I'm not sure I understand when it is more appropriate to use Observable.FromAsync versus not using it.
Does Observable.FromAsync take an IScheduler parameter? Is it your Test Scheduler?
I realize that my unit tests were incorrect in that they were touching too many moving parts. I have tests that verify that the mocked web service calls are being made when expected and I really shouldn't include that complexity in tests that aren't focused on that test point.
I'm calling the wcf service when navigating to the view model. Here's a better representation of my view model with minor changes regarding specifying an IScheduler:
public class ViewModel : ReactiveObject, IRoutableViewModel
{
private IContext _context;
public ViewModel(IContext context)
{
_context = context;
Weeks = new ReactiveCollection<WeekViewModel>();
this.WhenNavigatedTo(() =>
{
_context.Service.GetWeeksAsync()
.ToObservable()
.ObserveOn(RxApp.DeferredScheduler)
.Subscribe(result =>
{
Weeks.AddRange(result.Select(w => WeekViewModel(w)));
});
});
// ...
}
public ReactiveCollection<WeekViewModel> Weeks { get; private set; }
}
Instead of setting up the context to populate the Weeks collection then using the router to navigate to the ViewModel I am now adding objects to the Weeks collection in the unit tests and skipping navigation and the asynchronous web service calls. This has reduced the tests a bit, eliminated the instability as far as I can tell, and reduced the execution time of test suite.
So my unit tests look something like this
[TestFixture]
public class ViewModelTest : AssertionHelper
{
[Test]
public void ShouldSetChildren()
{
var c = new Mock<IContext>();
var vm = new ViewModel(c.Object);
vm.Children.AddRange((new []{1,2,3,4,5,6}).Select(i => new ChildViewModel(i)));
var p = vm.Children.First(); // this is valid now - no timing issues
...
}
}
The code behaves correctly in the app but was problematic in the test runner so I believe that this solves my immediate issues.

How to pass values across test cases in NUnit 2.6.2?

I am having two Methods in Unit Test case where First Insert Records into Database and Second retrieves back data. I want that input parameter for retrieve data should be the id generated into first method.
private int savedrecordid =0;
private object[] SavedRecordId{ get { return new object[] { new object[] { savedrecordid } }; } }
[Test]
public void InsertInfo()
{
Info oInfo = new Info();
oInfo.Desc ="Some Description here !!!";
savedrecordid = InsertInfoToDb(oInfo);
}
[Test]
[TestCaseSource("SavedRecordId")]
public void GetInfo(int savedId)
{
Info oInfo = GetInfoFromDb(savedId);
}
I know each test case executed separately and separate instance we can't share variables across test methods.
Please let me know if there is way to share parameters across the test cases.
The situation you describe is one of unit tests' antipatterns: unit tests should be independent and should not depend on the sequence in which they run. You can find more at the xUnit Patterns web site:
Unit test should be implemented using Fresh Fixture
Anti pattern Shared Fixture
And both your unit tests have no asserts, so they can't prove whether they are passing or not.
Also they are depend on a database, i.e. external resource, and thus they are not unit but integration tests.
So my advice is to rewrite them:
Use mock object to decouple from database
InsertInfo should insert info and verify using the mock that an appropriate insert call with arguments has been performed
GetInfo should operate with a mock that returns a fake record and verify that it works fine
Example
Notes:
* I have to separate B/L from database operations…
* … and make some assumptions about your solution
// Repository incapsulates work with Database
public abstract class Repository<T>
where T : class
{
public abstract void Save(T entity);
public abstract IEnumerable<T> GetAll();
}
// Class under Test
public class SomeRule
{
private readonly Repository<Info> repository;
public SomeRule(Repository<Info> repository)
{
this.repository = repository;
}
public int InsertInfoToDb(Info oInfo)
{
repository.Save(oInfo);
return oInfo.Id;
}
public Info GetInfoFromDb(int id)
{
return repository.GetAll().Single(info => info.Id == id);
}
}
// Actual unittests
[Test]
public void SomeRule_InsertInfo_WasInserted() // ex. InsertInfo
{
// Arrange
Info oInfo = new Info();
oInfo.Desc = "Some Description here !!!";
var repositoryMock = MockRepository.GenerateStrictMock<Repository<Info>>();
repositoryMock.Expect(m => m.Save(Arg<Info>.Is.NotNull));
// Act
var savedrecordid = new SomeRule(repositoryMock).InsertInfoToDb(oInfo);
// Assert
repositoryMock.VerifyAllExpectations();
}
[Test]
public void SomeRule_GetInfo_ReciveCorrectInfo() // ex. GetInfo
{
// Arrange
var expectedId = 1;
var expectedInfo = new Info { Id = expectedId, Desc = "Something" };
var repositoryMock = MockRepository.GenerateStrictMock<Repository<Info>>();
repositoryMock.Expect(m => m.GetAll()).Return(new [] { expectedInfo }.AsEnumerable());
// Act
Info receivedInfo = new SomeRule(repositoryMock).GetInfoFromDb(expectedId);
// Assert
repositoryMock.VerifyAllExpectations();
Assert.That(receivedInfo, Is.Not.Null.And.SameAs(expectedInfo));
}
ps: full example availabel here