How to test two objects are equal in xunit.net? - unit-testing

I am reading Test Driven Development: By Example. All examples use Java and Junit (I am on chapter 10). There are one test method that test for equality of two objects. I already override Equals of the class but when run my test it failed.
This is sample code
public class BaseX
{
public string Test { get; set; }
public override bool Equals(object obj)
{
return this.Test == ((BaseX)obj).Test;
}
public override string ToString()
{
return string.Format("Tyep: {0}, Test: {1}", this.GetType().Name, this.Test);
}
}
public class A : BaseX
{
}
This is my test code
[Fact]
public void FunTest2()
{
var b1 = new BaseX();
var a1 = new A();
b1.Test = "a";
a1.Test = "a";
Assert.Equal(a1, b1);
}
When I run the test, it will failed with this message.
TDD1.UnitTest.UnitTest1.FunTest2 : Assert.Equal() Failure
Expected: Tyep: A, Test: a
Actual: Tyep: BaseX, Test: a
I think Assert.Equal compare both value and type of objects. So, I looked on xunit code and found that Assert.Equal call IEqualityComparer.Equals. If I want to compare two object with override method, what method should I use?
Update
I test this on Windows 7, Visual Studio 11 Beta, xunit.net 1.9.0.1566 (get files from nuget)

Before comparing both objects using T's Equals method, xunit compares types:
// Same type?
if (!skipTypeCheck && x.GetType() != y.GetType())
return false;
As I see it, you have two choices:
The simple choice
Assert.True(b1.Equals(a1));
It might be less expected than an Equal overload, but KISS...
The less simple choice
public class BaseXComparer : IEqualityComparer<BaseX>
{
public bool Equals(BaseX x, BaseX y)
{
return x.Test.Equals(y.Test);
}
public int GetHashCode(BaseX obj)
{
return obj.Test.GetHashCode();
}
}
And then:
Assert.Equal(a1, b1, new BaseXComparer());
In this case, consider this.
Until someone will add a new overload (shouldn't be tricky, as the inner implementation has a bool parameter for this) or an extension, I'd recommend using the simple method above.

Related

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

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()))
{
}
}

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;
}
}

Using RhinoMocks, how can I assert that one of several methods was called?

Consider the following service interfaces:
public interface IServiceA
{
void DoSomething(string s);
void DoSomething(string s, bool b);
}
public interface IServiceB
{
void DoSomething();
}
The implementation of IServiceB depends on IServiceA like this:
public class ServiceB : IServiceB
{
private IServiceA _serviceA;
public ServiceB(IServiceA serviceA)
{
_serviceA = serviceA;
}
public void DoSomething()
{
_serviceA.DoSomething("Hello", true);
}
}
Ie. the dependency is injected in the constructor.
Now consider a unit test for the DoSomething() method. I wish to assert that one of the overloaded DoSomething-methods in IServiceA is called, but following a general principle that unit tests shouldn't know too much about the internal workings of the method being tested, I wish to be agnostic about which of the two overloads is called. Consider the following unit test:
[TestFixture]
public class ServiceBTests
{
[Test]
public void DoSomething_CallsServiceA()
{
var serviceAMock = MockRepository.GenerateMock<IServiceA>();
var service = new ServiceB(serviceAMock);
service.DoSomething();
// Problem: How to check if EITHER:
serviceAMock.AssertWasCalled(s => s.DoSomething(Arg<String>.Is.NotNull, Arg<bool>.Is.Anything));
// OR:
serviceAMock.AssertWasCalled(s => s.DoSomething(Arg<String>.Is.NotNull));
}
}
How can I assert that either one or the other of the two methods was called?
You could manually set a boolean flag like so:
[TestFixture]
public class ServiceBTests
{
[Test]
public void DoSomething_CallsServiceA()
{
var serviceAMock = MockRepository.GenerateMock<IServiceA>();
bool called = false;
serviceAMock.Stub(
x => x.DoSomething(Arg<String>.Is.NotNull, Arg<bool>.Is.Anything))
.WhenCalled(delegate { called = true; });
serviceAMock.Stub(x => x.DoSomething(Arg<String>.Is.NotNull))
.WhenCalled(delegate { called = true; });
var service = new ServiceB(serviceAMock);
service.DoSomething();
Assert.IsTrue(called);
}
}
I don't think this very useful though. Unit tests are concerned with anything that is observable from outside of the component boundaries. Method calls to mocks are part of that. In other words, it is OK if you test for a specific overload being called. After all, there must be a reason why you use that overload and not the other one.
If you really want the unit test to remain ignorant of the implementation, you wouldn't be allowed to assert method calls on mocks at all. That would be a severe restriction on your ability to write tests.

Test class constructors not executing when running an xUnit Theory individually?

Toy example code:
public abstract class testBase
{
public testBase()
{
//Some common test setup code, which will initialize ManagerClass
}
}
public class someTests: testBase
{
public someTests()
{
//someTests-specific constructor code.
}
[Theory]
[PropertyData("MyTestData")]
public void test1(Foo foo)
{
//Use foo to do a test
}
public static IEnumerable<object[]> MyTestData
{
get
{
yield return new object[] { ManagerClass.CreateANewFoo(1) };
yield return new object[] { ManagerClass.CreateANewFoo(42) };
}
}
}
In the above example, if I specifically run test1 (I'm using Resharper, but the problem also occurs when I use the xUnit GUI) my test is failing because it seems that neither the testBase nor someTests constructors are being executed. Hence the call to ManagerClass.CreateANewFoo() is throwing a NullReference.
If I run all of the tests in someTests, or any other individual test, the constructor executes as expected and the tests proceed in the expected fashion. The only thing that marks test1 out as different is the fact that it is using the PropertyData attribute.
Any ideas why this is happening/what I'm doing wrong?
We attempted to reproduce this with xUnit.net 1.5 Beta and cannot.

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.
}