How to combine PropertyData and AutoNSubstituteData attributes in xunit/autofixture? - unit-testing

I am using the [AutoNSubstituteData] attribute, which was posted here:
AutoFixture, xUnit.net, and Auto Mocking
I would like to combine this with the [PropertyData("")] attribute from xunit extensions.
This is my test:
public static IEnumerable<string[]> InvalidInvariant
{
get
{
yield return new string[] { null };
yield return new [] { string.Empty };
yield return new [] { " " };
}
}
[Theory, AutoNSubstituteData, PropertyData("InvalidInvariant")]
public void TestThatGuardsAreTriggeredWhenConnectionStringArgumentIsInvalid(
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string invalidConnString,
string query)
{
deal.Init.Group.Returns(Group.A);
deal.Aggr.Group.Returns(Group.A);
deal.Product.Commodity.Returns(Product.Commodity.E);
var sut = new Handler(db, sender);
Assert.Throws<ArgumentException>(() =>
sut.HandleDeal(deal, conn, invalidConnString, query));
}
Is there a way to combine these attributes or to get the desired functionality (mock everything, except for invalidConnstring, which should be filled with the property-data)?

There are two ways to do this:
Option 1 - Using AutoFixture.Xunit and the CompositeDataAttribute class:
internal class AutoNSubstituteDataAttribute : AutoDataAttribute
{
internal AutoNSubstituteDataAttribute()
: base(new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}
internal class AutoNSubstitutePropertyDataAttribute : CompositeDataAttribute
{
internal AutoNSubstitutePropertyDataAttribute(string propertyName)
: base(
new DataAttribute[] {
new PropertyDataAttribute(propertyName),
new AutoNSubstituteDataAttribute() })
{
}
}
Define the test cases as below:
public class Scenario
{
public static IEnumerable<object[]> InvalidInvariantCase1
{
get
{
yield return new string[] { null };
}
}
public static IEnumerable<object[]> InvalidInvariantCase2
{
get
{
yield return new string[] { string.Empty };
}
}
public static IEnumerable<object[]> InvalidInvariantCase3
{
get
{
yield return new string[] { " " };
}
}
}
Then declare the parameterized test as:
public class Scenarios
{
[Theory]
[AutoNSubstitutePropertyData("InvalidInvariantCase1")]
[AutoNSubstitutePropertyData("InvalidInvariantCase2")]
[AutoNSubstitutePropertyData("InvalidInvariantCase3")]
public void AParameterizedTest(
string invalidConnString,
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string query)
{
}
}
Please note that the parameterized parameter invalidConnString have to be declared before the other parameters.
Option 2 - Using Exude:
public class Scenario
{
public void AParameterizedTest(
IDeal deal,
IDbConnection conn,
IDb db,
ISender sender,
string invalidConnString,
string query)
{
}
[FirstClassTests]
public static TestCase<Scenario>[] RunAParameterizedTest()
{
var testCases = new []
{
new
{
invalidConnString = (string)null
},
new
{
invalidConnString = string.Empty
},
new
{
invalidConnString = " "
}
};
var fixture = new Fixture()
.Customize(new AutoNSubstituteCustomization());
return testCases
.Select(tc =>
new TestCase<Scenario>(
s => s.AParameterizedTest(
fixture.Create<IDeal>(),
fixture.Create<IDbConnection>(),
fixture.Create<IDb>(),
fixture.Create<ISender>(),
tc.invalidConnString,
fixture.Create<string>())))
.ToArray();
}
}

The [Theory] attribute works by looking for one or more 'data source attributes'; for example
[InlineData]
[PropertyData]
[ClassData]
etc.
The [AutoData] attribute is just another such attribute, as is your derived [AutoNSubstituteData] attribute.
It's possible to add more than one 'data source attribute' to the same [Theory], as witnessed by the idiomatic use of the [InlineData] attribute:
[Theory]
[InlineData("foo")]
[InlineData("bar")]
[InlineData("baz")]
public void MyTest(string text)
This produces three test cases.
It's also possible to combine [PropertyData] and [AutoData], but it probably doesn't do what you want it to do. This:
[Theory]
[AutoNSubstituteData]
[PropertyData("InvalidInvariant")]
public void MyTest(/* parameters go here */)
will result in 1 + n test cases:
1 test case from [AutoNSubstituteData]
n test cases from the InvalidInvariant property
These two attributes know nothing about each other, so you can't combine them in the sense that they're aware of each other.
However, when you're implementing a property, you can write whatever code you'd like, including using a Fixture instance, so why not just do this?
public static IEnumerable<string[]> InvalidInvariant
{
get
{
var fixture = new Fixture().Customize(new MyConventions());
// use fixture to yield values...,
// using the occasional hard-coded test value
}
}
Another option is to use derive from the InlineAutoDataAttribute, which would enable you to write your test cases like this:
[Theory]
[MyInlineAutoData("foo")]
[MyInlineAutoData("bar")]
[MyInlineAutoData("baz")]
public void MyTest(string text, string someOtherText, int number, Guid id)
This would cause the first argument (text) to be populated with the constants from the attributes, while the remaining parameters are populated by AutoFixture.
Theoretically, you may also be able to combine the [AutoData] and [PropertyData] attributes using the CompositeDataAttribute, but it may not work the way you'd like.
Finally, you could consider using Exude for true first-class parameterized tests.

I have implemented an AutoPropertyDataAttribute that combines xUnit's PropertyDataAttribute with AutoFixture's AutoDataAttribute. I posted it as an answer here.
In your case you will need to inherit from the attribute in the same way as you would from an AutoDataAttribute, with the exception that you pass a fixture creation function instead of an instance:
public class AutoNSubPropertyDataAttribute : AutoPropertyDataAttribute
{
public AutoNSubPropertyDataAttribute(string propertyName)
: base(propertyName, () => new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}

Related

Using AutoFixture to set properties on a collection as data for an Xunit theory

I'm new to Xunit and AutoFixture, and writing a theory that looks like:
[Theory, AutoData]
public void Some_Unit_Test(List<MyClass> data)
{
// Test stuff
}
MyClass looks like:
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
This causes AutoFixture to create a list of items with random values for each property. This is great, but I would like the IsActive property to always be true.
I could set it to true at the start of every test but I'm guessing there is a smarter way. I looked at InlineData, ClassData, PropertyData, even Inject() but nothing quite seemed to fit.
How can I improve this?
Here is one way to do this:
public class Test
{
[Theory, TestConventions]
public void ATestMethod(List<MyClass> data)
{
Assert.True(data.All(x => x.IsActive));
}
}
The TestConventionsAttribute is defined as:
internal class TestConventionsAttribute : AutoDataAttribute
{
internal TestConventionsAttribute()
: base(new Fixture().Customize(new TestConventions()))
{
}
private class TestConventions : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<MyClass>(c => c.With(x => x.IsActive, true));
}
}
}
Thank you, Nikos. This is very useful. Just a small update, now after a while and couple of versions after there is a small change with regards to the base constructor which should be called, the one above is now obsolete. It should look something like this:
private static readonly Func<IFixture> fixtureFactory = () =>
{
return new Fixture().Customize(new TestConventions());
};
public TestConventionsAttribute()
: base(fixtureFactory)
{
}
private class TestConventions : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<MyClass>(c => c.With(x => x.IsActive, true));
}
}

Can a particular constructor argument of an injected SUT using Autodata xUnit Theories?

Consider the following test,
[Theory, MyConventions]
public void GetClientExtensionReturnsCorrectValue(BuilderStrategy sut)
{
var expected = ""; // <--??? the value injected into BuilderStrategy
var actual = sut.GetClientExtension();
Assert.Equal(expected, actual);
}
and the custom attribute I'm using:
public class MyConventionsAttribute : AutoDataAttribute {
public MyConventionsAttribute()
: base(new Fixture().Customize(new AutoMoqCustomization())) {}
}
and the SUT:
class BuilderStrategy {
private readonly string _clientID;
private readonly IDependency _dependency;
public void BuilderStrategy(string clientID, IDependency dependency) {
_clientID = clientID;
_dependency = dependency;
}
public string GetClientExtension() {
return _clientID.Substring(_clientID.LastIndexOf("-") + 1);
}
}
I need to know what value was injected into the constructor parameter clientID so that I can use it to compare with the output of GetClientExtension. Is it possible to do this while still writing this style of test where the SUT is injected into the test method?
If you expose the injected clientID (and dependency as well) as read-only properties, you can always query their values:
public class BuilderStrategy {
private readonly string _clientID;
private readonly IDependency _dependency;
public void BuilderStrategy(string clientID, IDependency dependency) {
_clientID = clientID;
_dependency = dependency;
}
public string GetClientExtension() {
return _clientID.Substring(_clientID.LastIndexOf("-") + 1);
}
public string ClientID
{
get { return _clientID; }
}
public IDependency Dependency
{
get { return _dependency; }
}
}
This doesn't break encapsulation, but is rather known as Structural Inspection.
With this change, you could now rewrite the test like this:
[Theory, MyConventions]
public void GetClientExtensionReturnsCorrectValue(BuilderStrategy sut)
{
var expected = sut.ClientID.Substring(sut.ClientID.LastIndexOf("-") + 1);
var actual = sut.GetClientExtension();
Assert.Equal(expected, actual);
}
Some people don't like duplicating production code in the unit test, but I would rather argue that if you follow Test-Driven Development, it's the production code that duplicates the test code.
In any case, this is a technique known as Derived Value. In my opinion, as long as it retains a cyclomatic complexity of 1, we can still trust the test. Additionally, as long as the duplicated code only appears in two places, the rule of three suggests that we should keep it like that.

How to get NUnit to test all values in a list, rather than just the first failure

Just some example code here, but I have lists of strings that I want to test my functions against. The part that I don't like is that NUnit stops in each test when the first Assert fails. I'd like to test each value and report each failure, rather than just the first one. I don't want to have to write a new [Test] function for each string though.
Is there a way to do this?
using NUnit.Framework;
using System.Collections.Generic;
namespace Examples
{
[TestFixture]
public class ExampleTests
{
private List<string> validStrings = new List<string> { "Valid1", "valid2", "valid3", "Valid4" };
private List<string> invalidStrings = new List<string> { "Invalid1", "invalid2", "invalid3", "" };
[Test]
public void TestValidStrings()
{
foreach (var item in validStrings)
{
Assert.IsTrue(item.Contains("valid"), item);
}
}
[Test]
public void TestInvalidStrings()
{
foreach (var item in invalidStrings)
{
Assert.IsFalse(item.Contains("invalid"), item);
}
}
}
}
Use the [TestCaseSource] attribute to specify values to pass into your (now parameterized) test method.
We use this a lot in Noda Time to test a lot of cases with different cultures and strings.
Here's your example, converted to use it:
using NUnit.Framework;
using System.Collections.Generic;
// Namespace removed for brevity
[TestFixture]
public class ExampleTests
{
private List<string> validStrings = new List<string>
{ "Valid1", "valid2", "valid3", "Valid4" };
private List<string> invalidStrings = new List<string>
{ "Invalid1", "invalid2", "invalid3", "" };
[Test]
[TestCaseSource("validStrings")]
public void TestValidStrings(string item)
{
Assert.IsTrue(item.Contains("valid"), item);
}
[Test]
[TestCaseSource("invalidStrings")]
public void TestInvalidStrings(string item)
{
Assert.IsFalse(item.Contains("invalid"), item);
}
}
Note that another option is to use [TestCase] which means you don't need separate variables for your test data.

Cannot seem to moq EF CodeFirst 4.1.Help anyone?

I have been given the task to evaluate codeFirst and possible to use for all our future projects.
The evaluation is based on using codeFirst with an existing database.
Wondering if it's possible to mock the repository using codeFirst 4.1.(no fakes)
The idea is to inject a repository into a service and moq the repository.
I have been looking on the net but I have only found an example using fakes.I dont want to use fakes I want to use moq.
I think my problem is in the architecture of the DAL.(I would like to use unitOfWork etc.. by I need to show a working moq example)
Below is my attempt(Failed miserably) due to lack of knowledge on Code first 4.1.
I have also uploaded a solution just in case somebody is in good mood and would like to change it.
http://cid-9db5ae91a2948485.office.live.com/browse.aspx/Public%20Folder?uc=1
I am open to suggestions and total modification to my Dal.Ideally using Unity etc.. but I will worry about later.
Most importantly I need to be able to mock it. Without ability to use MOQ we will bin the project using EF 4.1
Failed attempt
//CodeFirst.Tests Project
[TestClass]
public class StudentTests
{
[TestMethod]
public void Should_be_able_to_verify_that_get_all_has_been_called()
{
//todo redo test once i can make a simple one work
//Arrange
var repository = new Mock<IStudentRepository>();
var expectedStudents = new List<Student>();
repository.Setup(x => x.GetAll()).Returns(expectedStudents);
//act
var studentService = new StudentService(repository.Object);
studentService.GetAll();
//assert
repository.Verify(x => x.GetAll(), Times.AtLeastOnce());
}
}
//CodeFirst.Common Project
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}
public interface IStudentService
{
IEnumerable<Student> GetAll();
}
//CodeFirst.Service Project
public class StudentService:IStudentService
{
private IStudentRepository _studentRepository;
public StudentService()
{
}
public StudentService(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
public IEnumerable<Student> GetAll()
{
//TODO when mocking using moq this will actually call the db as we need a separate class.
using (var ctx = new SchoolContext("SchoolDB"))
{
_studentRepository = new StudentRepository(ctx);
var students = _studentRepository.GetAll().ToList();
return students;
}
}
}
//CodeFirst.Dal Project
public interface IRepository<T> where T : class
{
T GetOne(Expression<Func<T, bool>> predicate);
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
T Single(Func<T, bool> predicate);
T First(Func<T, bool> predicate);
}
public class RepositoryBase<T> : IRepository<T> where T : class
{
private readonly IDbSet<T> _dbSet;
public RepositoryBase(DbContext dbContext)
{
_dbSet = dbContext.Set<T>();
if (_dbSet == null) throw new InvalidOperationException("Cannot create dbSet ");
}
protected virtual IDbSet<T> Query
{
get { return _dbSet; }
}
public T GetOne(Expression<Func<T, bool>> predicate)
{
return Query.Where(predicate).FirstOrDefault();
}
public IEnumerable<T> GetAll()
{
return Query.ToArray();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
return Query.Where(predicate).ToArray();
}
public void Add(T entity)
{
_dbSet.Add(entity);
}
public void Delete(T entity)
{
_dbSet.Remove(entity);
}
public T Single(Func<T, bool> predicate)
{
return Query.Where(predicate).SingleOrDefault();
}
public T First(Func<T, bool> predicate)
{
return Query.Where(predicate).FirstOrDefault();
}
}
public class SchoolContext:DbContext
{
public SchoolContext(string connectionString):base(connectionString)
{
Database.SetInitializer<SchoolContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Not sure why I have to do this.Without this when using integration testing
//as opposed to UnitTests it does not work.
modelBuilder.Entity<Student>().ToTable("Student"); }
public DbSet<Student> Students { get; set; }
}
public interface IStudentRepository:IRepository<Student>
{
}
public class StudentRepository : RepositoryBase<Student>, IStudentRepository
{
public StudentRepository(DbContext dbContext)
: base(dbContext)
{
}
public IEnumerable<Student> GetStudents()
{
return GetAll();
}
}
Again feel free to modify or whatever is needed to help me to get something together.
Thanks a lot for your help
When I started with repository and unit of work patterns I used the implementation similar to this (it is for ObjectContext API but converting it to DbContext API is simple). We used that implementation with MOQ and Unity without any problems. By the time implementations of repository and unit of work have evolve as well as the approach of injecting. Later on we found that whole this approach has serious pitfalls but that was alredy discussed in other questions I referenced here (I highly recommend you to go through these links).
It is very surprising that you are evaluating the EFv4.1 with high emphasis on mocking and unit testing and in the same time you defined service method which is not unit-testable (with mocking) at all. The main problem of you service method is that you are not passing repository/context as dependency and because of that you can't mock it. The only way to test your service and don't use the real repository is using some very advanced approach = replacing mocking and MOQ with detouring (for example Moles framework).
First what you must do is replacing your service code with:
public class StudentService : IStudentService
{
private readonly IStudentRepository _studentRepository;
public StudentService(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
public IEnumerable<Student> GetAll()
{
return _studentRepository.GetAll().ToList();
}
}
Btw. this is absolutely useless code and example of silly layering which doesn't offer any useful functionality. Just wrapping the call to repository only shows that service is not needed at all as well as unit testing this method is not needed. The main point here is integration test for GetAll method.
Anyway if you want to unit thest such method with MOQ you will do:
[TestClass]
public class StudentsServiveTest
{
private Mock<IRespository<Student>> _repo;
[TestInitialize]
public void Init()
{
_repo = new Mock<IRepository<Student>>();
_repo.Setup(r => r.GetAll()).Returns(() => new Student[]
{
new Student { StudentId = 1, Name = "A", Surname = "B" },
new Student { StudentId = 2, Name = "B", Surname = "C" }
});
}
[TestMethod]
public void ShouldReturnAllStudents()
{
var service = new StudentsService(_repo.Object);
var data = service.GetAll();
_repo.Verify(r => r.GetAll(), Times.Once());
Assert.IsNotNull(data);
Assert.AreEqual(2, data.Count);
}
}
The issue from what I can see is that you are throwing away the mock object and newing up a new instance
_studentRepository = new StudentRepository(ctx);
Perhaps add a method on the interface to add the context object and reuse the same instance that was injected in the constructor.
using (var ctx = new SchoolContext("SchoolDB"))
{
_studentRepository.Context = ctx;
var students = _studentRepository.GetAll().ToList();
return students;
}
}

Parametric test with generic methods

In NUnit 2.5 you can do this:
[TestCase(1,5,7)]
public void TestRowTest(int i, int j, int k)
{
Assert.AreEqual(13, i+j+k);
}
You can do parametric test.
But I wonder whether you can do this or not, parametric test with generic test method? I.e.:
[TestCase <int>("Message")]
public void TestRowTestGeneric<T>(string msg)
{
Assert.AreEqual(5, ConvertStrToGenericParameter<T>(msg));
}
Or something similar.
Here is the quote from the release note of NUnit 2.5 link text
Parameterized test methods may be
generic. NUnit will deduce the correct
implementation to use based on the
types of the parameters provided.
Generic test methods are supported in
both generic and non-generic clases.
According to this, it is possible to have generic test method in non-generic class. How?
I don't quite understand Jeff's comment. In .net generics is both compile-time and run-time. We can use the reflection to find out the test case attribute associated with a method, find out the generic parameter, and again use reflection to call the generic method. It will work, no?
Update: OK, I now know how and hope it is not too late. You need the generic type to be in the parameter list. For example:
[TestCase((int)5, "5")]
[TestCase((double)2.3, "2.3")]
public void TestRowTestGeneric<T>(T value, string msg)
{
Assert.AreEqual(value, ConvertStrToGenericParameter<T>(msg));
}
You can make custom GenericTestCaseAttribute
[Test]
[GenericTestCase(typeof(MyClass) ,"Some response", TestName = "Test1")]
[GenericTestCase(typeof(MyClass1) ,"Some response", TestName = "Test2")]
public void MapWithInitTest<T>(string expectedResponse)
{
// Arrange
// Act
var response = MyClassUnderTest.MyMethod<T>();
// Assert
Assert.AreEqual(expectedResponse, response);
}
Here is implementation of GenericTestCaseAttribute
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class GenericTestCaseAttribute : TestCaseAttribute, ITestBuilder
{
private readonly Type _type;
public GenericTestCaseAttribute(Type type, params object[] arguments) : base(arguments)
{
_type = type;
}
IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
{
if (method.IsGenericMethodDefinition && _type != null)
{
var gm = method.MakeGenericMethod(_type);
return BuildFrom(gm, suite);
}
return BuildFrom(method, suite);
}
}
Create a private method and call that:
[Test]
public void TypeATest()
{
MyTest<TypeA>();
}
[Test]
public void TypeBTest()
{
MyTest<TypeB>();
}
private void MyTest<T>()
{
// do test.
}