I am getting this error when I run my test: System.NotImplementedException : The member 'IQueryable.Provider' has not been implemented on type 'DbSet' ...'
I saw this blog post on creating a fakeDbSet but that was before EF6. Is there a better way to handle this with EF 6?
[Test]
public void Edit_ShouldCall_DbContext_Entry()
{
//arrange
var request = Builder<EditGroupRequest>.CreateNew().Build();
fakeDbSet.Stub(x => x.FirstOrDefault(y => y.ReportGroupNameKey == request.Key)).Return(new MyObject());
//act
_sut.Edit(request);
//assert
_contextFake.AssertWasCalled(x => x.Entry(Arg<MyObject>.Is.Anything).Property(y => y.ReportGroupName).CurrentValue = request.Name);
}
Although DBSet implements IQueryable, IDbSet... the object generated by the mock engine is not implementing them.
A possible solution is using a Mocking framework that supports building mocks that implement many interfaces like the one pointed out in another thread (Substitute):
Mocking DBSet, EF Model First
Here you have an utility function to build a mocked DBSet which data is stored on a generic list:
public static DbSet<T> BuildMockedDbSet<T>(List<T> data) where T : class
{
IQueryable<T> queryable = data.AsQueryable();
DbSet<T> fakeDbSet = Substitute.For<DbSet<T>, IQueryable<T>>();
((IQueryable<T>)fakeDbSet).Provider.Returns(queryable.Provider);
((IQueryable<T>)fakeDbSet).Expression.Returns(queryable.Expression);
((IQueryable<T>)fakeDbSet).ElementType.Returns(queryable.ElementType);
((IQueryable<T>)fakeDbSet).GetEnumerator().Returns(queryable.GetEnumerator());
fakeDbSet.AsNoTracking().Returns(fakeDbSet);
return fakeDbSet;
}
Hope it helps.
Related
I been trying to figure out how i can unit test service and so far have got nowhere.
I am using xUnit and NSubstitute (as advised by friends), below is the simple test that i want to run (which fails currently).
public class UnitTest1
{
private readonly RallyService _rallyService;
public UnitTest1(RallyService rallyService)
{
_rallyService= rallyService;
}
[Fact]
public void Test1()
{
var result = _rallyService.GetAllRallies();
Assert.Equal(2, result.Count());
}
}
My rally service class makes a simple call to the db to get all Rally entites and returns those:
public class RallyService : IRallyService
{
private readonly RallyDbContext _context;
public RallyService(RallyDbContext context)
{
_context = context;
}
public IEnumerable<Rally> GetAllRallies()
{
return _context.Rallies;
}
}
Any guidance would be appreciated.
Since you use .NET Core, I assume you also use Entity Framework Core. While it was possible to mock most of the operations in the previous EF version, however the EF Core suggests to use in-memory database for unit testing. I.e. you don't need to mock RallyDbContext, hence NSubstitute is not needed for this particular test. You would need NSubstitute to mock the service when testing a controller or application using the service.
Below is your Test1 written using in-memory database.
public class UnitTest1
{
private readonly DbContextOptions<RallyDbContext> _options;
public UnitTest1()
{
// Use GUID for in-memory DB names to prevent any possible name conflicts
_options = new DbContextOptionsBuilder<RallyDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
}
[Fact]
public async Task Test1()
{
using (var context = new RallyDbContext(_options))
{
//Given 2 records in database
await context.AddRangeAsync(new Rally { Name = "rally1" }, new Rally { Name = "rally2" });
await context.SaveChangesAsync();
}
using (var context = new RallyDbContext(_options))
{
//When retrieve all rally records from the database
var service = new RallyService(context);
var rallies = service.GetAllRallies();
//Then records count should be 2
Assert.Equal(2, rallies.Count());
}
}
}
A working test application with this unit test is in my GitHub for your reference. I used SQL Express in the actual app.
I don't think it is standard to have a unit test constructor with a parameter. The unit test runner will new up this class, and unless you are using something that will auto-inject that parameter I think the test will fail to run.
Here is a standard fixture layout:
public class SampleFixture {
[Fact]
public void SampleShouldWork() {
// Arrange stuff we need for the test. This may involved configuring
// some dependencies, and also creating the subject we are testing.
var realOrSubstitutedDependency = new FakeDependency();
realOrSubstitutedDependency.WorkingItemCount = 42;
var subject = new Subject(realOrSubstitutedDependency);
// Act: perform the operation we are testing
var result = subject.DoWork();
// Assert: check the subject's operation worked as expected
Assert.Equal(42, result);
}
[Fact]
public void AnotherTest() { /* ... */ }
}
If you need a common setup between tests, you can use a parameterless constructor and do common initialisation there.
In terms of the specific class you are trying to test, you need to make sure your RallyDbContext is in a known state to repeatably and reliably test. You may want to look up answers specific to testing Entity Framework for more information.
I need a jump start in testing the methods on my Business layer. Consider the Materials BLL object, how can I test the AddNewMaterial method for it?
interface IGenericRepository<TEntity>
{
TEntity Add(TEntity m);
}
public interface IMaterialRepository : IGenericRepository<Material>
{
}
public interface IUnitOfWork
{
IMaterialRepository Materials { get; private set;}
void Save();
}
public interface IUnitOfWorkFactory
{
IUnitOfWork GetUnitOfWOrk();
}
public class MaterialsBLL
{
private readonly IUnitOfWorkFactory _uowFactory;
//uowFactory comes from DI
public MaterialsBLL(IUnitOfWorkFactory uowFactory)
{
_uowFactory = uowFactory;
}
//TODO: test this
public Material AddNewMaterial(Material m)
{
using(var uow = _uowFactory.GetUnitOfWOrk())
{
var result = uow.Materials.Add(m);
uow.Save();
return result;
}
}
I am using Moq, and XUnit, but am very green. In general I want to do this:
Mock the repositories Add method.
Mock the UoW Materials property to return my repository mock.
Mock the UoWFactory to return the UoW mock.
Create the MaterialsBLL giving the mocked UoWFactory to the contstructor.
Verify that the AddNewMaterials calls the repository's Add, and the UoW's Save, etc.
It seems to me that, I maybe should be creating a Fake MaterialRepository, rather than mocking it? Any other advice? Here is a first crack:
[Fact]
public void TestGetMaterialById()
{
var materialList = GetMaterials();
var materialRepositoryMock = new Mock<IMaterialRepository>();
materialRepositoryMock.Setup(repo => repo.Get(4)).Returns(materialList.First());
var uowMock = new Mock<IUnitOfWork>();
uowMock.SetupProperty<IMaterialRepository>(uow => uow.Materials, materialRepositoryMock.Object);
var uowFactoryMock = new Mock<IUnitOfWorkFactory>();
uowFactoryMock.Setup(f => f.GetUnitOfWork()).Returns(uowMock.Object);
var materialsBll = new Materials(uowFactoryMock.Object);
var result = materialsBll.Get(4);
Assert.Equal(result.MaterialId, 4);
Assert.Equal(result.Name, "Four");
}
When you feel like you need several levels of nested mock objects, there's generally something wrong with your design.
The Law of Demeter warns us here that you should probably not tinker with uow.Materials in MaterialsBLL.
Besides, a Unit of Work is typically not the place to expose Repositories. The code that needs to access Materials will usually have a direct reference to an IMaterialsRepository, not ask it from the UoW, and then the Repository implementation might reference the UoW internally.
This leads to a flatter design and simplifies your production code as well as your tests.
Hi I'm new to Mocking.
I have a class:
public class Car
{
public virtual void Register() {
...
Warrant();
}
public virtual void Warrant() {
...
}
}
I was wanting to test that Register calls Warrant. Using RhinoMocks I came up with:
[Test]
public void RhinoCarTest() {
var mocks = new Rhino.Mocks.MockRepository();
var car = mocks.PartialMock<Car>();
mocks.ReplayAll();
car.Stub(x => x.Warrant());
car.Register();
car.AssertWasCalled(x => x.Warrant());
}
I'm not even sure if this is correct but it seemed to do the job. I was wanting to do the same thing in Moq. I couldn't seem to find a partial Moq.
What I came up with was:
[Test]
public void MoqCarTest() {
var car = new Mock<Car>();
car.Setup(x => x.Warrant());
car.Object.Register();
car.Verify(x => x.Warrant());
}
This doesn't even work though. Can someone point me in the right direction?
Partial classes in Rhino.Mocks will call the base class methods unless you set up a Mock and/or stub. By default, Moq will only call base class methods if you create the mock to specifically do that. Here's an example that will work for your example:
var car = new Mock<Car> {CallBase = true};
car.Object.Register();
car.Verify(c => c.Warrant(), Times.Once());
However, I would try and avoid this approach (verifying that a specific method was called). Instead, your test should simply ensure that the correct "work" was done after calling the method. How that work gets done is a private implementation of the method.
If you write tests that ensure certain methods are called, your tests can become more brittle over time -- especially as you refactor for performance or other issues.
I'm trying to get my controller in a unit test to return a mock file when Request.Files[0] is called
From other posts on this site I've put together:
[TestMethod]
public void CreateFileInDatabase()
{
var repository = new MocRepository();
var controller = GetController(repository);
HttpContextBase mockHttpContext = MockRepository.GenerateMock<HttpContextBase>();
HttpRequestBase mockRequest = MockRepository.GenerateMock<HttpRequestBase>();
mockHttpContext.Stub(x => x.Request).Return(mockRequest);
mockRequest.Stub(x => x.HttpMethod).Return("GET");
var filesMock = MockRepository.GenerateMock<HttpFileCollectionBase>();
var fileMock = MockRepository.GenerateMock<HttpPostedFileBase>();
filesMock.Stub(x => x.Count).Return(1);
mockRequest.Stub(x => x.Files).Return(filesMock);
var t = mockHttpContext.Request;
var automobile = new Automobile{ automobileNumber = "1234" };
controller.ControllerContext = new ControllerContext(mockHttpContext, new RouteData(), controller);
controller.Create(automobile);
}
When I'm in the controller during a test and call Request.Files I get the filesMock great.
However I want to be able to call Request.Files[0] and get a mock File which I can pass as a parameter to a method.
I haven't done much mocking before so any help would be appreciated!
Your filesMock object is a mock, therefore it have no idea how to resolve Files[0]. You need to tell it what to return, if someone asks for the first file:
filesMock.Stub(x => x[0]).Return(fileMock);
Add the above line after the creation of the fileMock object and the code works :)
The easiest way is to add an abstraction over the Request.Files[0] via an interface and object that actually calls out to Request.Files[0]
Note: I'm not actually sure what the datatype is for Request.Files[0], just using IFile as an example.
public interface IFileRetriever
{
IFile GetFile();
}
public class FileRetriever
{
public IFile GetFile()
{
return Request.Files[0];
}
}
Obviously suit the interface and real implementation to your use case, it will probably not be what is above...
In your class that currently calls out to Request.Files[0] just take in the IFileRetriever as a dependency, which is straightforward to mock out in Rhino Mocks (or any mocking/faking framework)
I want to refactor a DLL to make it MEFable too. Should I unit test whether a class is decorated with [Export] or [Import] and other MEF attributes?
Your tests should focus more on the goal instead of the mechanism. Create tests that verify things like "if I throw types X, Y and Z together in a container, then I can pull an IFoo interface from the container", like this:
[Test]
public void Can_get_IFoo_from_container_with_Foo_Bar_Baz()
{
var catalog = new TypeCatalog(typeof(Foo), typeof(Bar), typeof(Baz));
using (var container = new CompositionContainer(catalog))
{
var test = container.GetExportedValue<IFoo>();
}
}
This is no longer a real "unit" test because it involves multiple classes and an IoC container. We just call them "composition tests".
After thinking some hours and reading some TDD blogs again I should say, YES, I have to test whether my class has MEF attributes or not.
So before refactoring my classes I write unit tests in that way:
[TestClass]
public class When_SampleClass_mefable
{
[TestMethod]
[TestCategory("LFF.Kabu.Win.Login.ViewModel.SampleClass")]
public void Should_SampleClass_be_marked_with_Export_Attibute()
{
//arrange
var info = (typeof (SampleClass));
//act
var attr = info.GetCustomAttributes(true);
var hasExportAttribute =
attr.Where(x => x.GetType() == typeof (ExportAttribute))
.Where(x => ((ExportAttribute)x).ContractType == typeof(SampleClass))
.Count() > 0;
//assert
Assert.IsTrue(hasExportAttribute, "SampleClass is not marked with Export.");
}
}
For other MEF attributes like [ImportingConstructor] or [PartCreationPolicy] I do it the same way.