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.
Related
Wanting to know if there's a way to mock a virtual method on a concrete class using AutoFixture and NSubstitute. I've been able to do this easily with Moq, as can be seen here:
public class SomeConcreteClass
{
public string MethodA()
{
return MethodB();
}
public virtual string MethodB()
{
return "AAA";
}
}
[TestFixture]
public class SomeConcreteClassTests
{
private IFixture _fixture;
private SomeConcreteClass _someConcreteClass;
[SetUp]
protected void Setup()
{
_fixture = new Fixture()
.Customize(new AutoMoqCustomization());
var someConcreteClassMock = _fixture.Create<Mock<SomeConcreteClass>>();
_someConcreteClass = someConcreteClassMock.Object;
someConcreteClassMock.CallBase = true;
}
[Test]
public void SomeScenario()
{
Mock.Get(_someConcreteClass).Setup(m => m.MethodB()).Returns("BBB");
var actual = _someConcreteClass.MethodA();
actual.ShouldBe("BBB");
}
}
This is best achieved if you use AutoFixture's support for Parametrised Tests, here illustrated using xUnit.net (but, IIRC, there's similar support for NUnit):
[Theory, AutoNSubstituteData]
public void ImplicitSubtituteViaAttribute([Substitute]SomeConcreteClass scc)
{
scc.MethodB().Returns("BBB");
var actual = scc.MethodB();
Assert.Equal("BBB", actual);
}
Using the [Substitute] attribute enables you to explicitly tell AutoFixture that, although you asked for a concrete class, it should create it via NSubstitute so that you can override any virtual members it might have.
AutoNSubstituteData is defined like this:
public class AutoNSubstituteDataAttribute : AutoDataAttribute
{
public AutoNSubstituteDataAttribute() :
base(() => new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}
AutoDataAttribute comes from AutoFixture.Xunit2, but if you prefer NUnit over xUnit.net, you should be able to use AutoFixture.NUnit3 instead.
Otherwise, I'm not sure you can achieve exactly the same result as with AutoFixture.AutoMoq. In this degenerate example, you can do this:
[Fact]
public void ImperativeWorkaround()
{
var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
fixture.Register(() => Substitute.For<SomeConcreteClass>());
var scc = fixture.Create<SomeConcreteClass>();
scc.MethodB().Returns("BBB");
var actual = scc.MethodB();
Assert.Equal("BBB", actual);
}
This is, however, fairly pointless, as you could just as well have written this:
[Fact]
public void Reduction()
{
var scc = Substitute.For<SomeConcreteClass>();
scc.MethodB().Returns("BBB");
var actual = scc.MethodB();
Assert.Equal("BBB", actual);
}
In other words, AutoFixture doesn't actually do anything in that workaround.
I could imagine that the real issue is that in real usage, the concrete class in question has other members or constructor data that you wish to fill with data. The problem is that due to the way NSubstitute is designed, I'm not aware of any way you can declaratively ask for a 'substitute'; you'll have to use the Substitute.For method, which then completely short-circuits AutoFixture's ability to hook into the process and add its own behaviour.
With Moq, this is possible because in the OP, you're not asking AutoFixture for a SomeConcreteClass object, but rather for a Mock<SomeConcreteClass>, and that enables AutoFixture to distinguish.
In other words, Moq follows the Zen of Python that explicit is better than implicit, and that makes it extensible to a degree not easily achieved with NSubstitute. For that reason, I've always considered Moq to have the better API.
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 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.
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.
I would like to inject a fake nHibernate session into my repository using FakeItEasy, then return a list of objects that are predefined within my test. Does anyone have experience doing this?
Here is the example test:
[TestFixture]
public class ProductionRepositoryTester
{
private ProductionRepository _productionRepository;
[SetUp]
public void SetupFixture()
{
const string propertyNumber = "123";
Tank tank = new Tank { PropertyNumber = propertyNumber };
var session = A.Fake<ISession>();
var sessionFactory = A.Fake<ISessionFactory>();
A.CallTo(session).WithReturnType<IList<Tank>>().Returns(new List<Tank> { tank });
_productionRepository = new ProductionRepository(session, sessionFactory);
}
[Test]
public void ProductionRepositoryCanGetTanks()
{
var tanks = _productionRepository.GetTanks();
Assert.AreNotEqual(0, tanks.Count(), "Tanks should have been returned.");
}
}
And here is the call within the actual ProductionRepository class:
public IEnumerable<Tank> GetTanks()
{
var tanks = Session.CreateCriteria(typeof(Tank)).List<Tank>();
return tanks;
}
Thanks in advance for any advice!
First of all I would advice against faking the NHibernate interfaces at all, this is (in my opinion) too low a level to unit test. It's probably better to have some integration tests for these scenarios. In other words, unit test all interaction with an abstraction for ProductionRepository (IProductionRepository) but stop there. Now, however, that's just my opinion and if you really want to do this I think you would have to change your fake-setup:
The session returns a criteria, not ever a IList directly. Therefore you'd have to have a fake criteria too:
var fakeCriteria = A.Fake<ICriteria>();
A.CallTo(fakeCriteria).WithReturnType<IList<Tank>>().Returns(new List<Tank> { tank });
A.CallTo(session).WithReturnType<ICriteria>().Returns(fakeCriteria);
(I hope I remember the criteria type correctly, I think it's ICriteria but I'm not a hundred percent sure.)