Using Verify to confirm expected parameter values in Moq mock class - nunit

I'm trying to verify that a method within a mock is called with an expected object parameter. I'm using Moq, nUnit, and thinking that AutoFixture's Likeness should get the job done.
Below is a simplified version of what i'm trying to do.
Is there a way to do this with AutoFixture? Is there a better way to verify that Something is called with the appropriate parameter?
Overriding Equals in the A class to compare the property values and changing the Verify line to:
barMock.Verify(m => m.Something(a));
passes, however I'd rather not override Equals in every class like A in my project.
namespace Test
{
using Moq;
using NUnit.Framework;
using Ploeh.SemanticComparison.Fluent;
public class A
{
public int P1 { get; set; }
}
public interface IBar
{
void Something(A a);
}
public class Foo
{
public A Data { get; private set; }
public void DoSomethingWith(IBar bar)
{
Data = new A { P1 = 1 };
bar.Something(Data);
}
}
[TestFixture]
public class AutoFixtureTest
{
[Test]
public void TestSample()
{
var foo = new Foo();
var barMock = new Mock<IBar>();
var a = new A { P1 = 1 };
var expectedA = a.AsSource().OfLikeness<A>();
foo.DoSomethingWith(barMock.Object);
expectedA.ShouldEqual(foo.Data); // passes
barMock.Verify(m => m.Something(expectedA.Value)); // fails
}
}
}

In Verify Moq by default checks reference equality for arguments so it only passes when you provide the same instances (except if you've overriden Equals) in your tests and in your implementation.
In you case the expectedA.Value just returns the new A { P1 = 1 } created in the test which, of course, isn't the same instance created in DoSomethingWith.
You need to use Moq's It.Is construct to properly test this without overriding Equals (in fact for this you don't need Autofixture at all):
barMock.Verify(m => m.Something(It.Is<A>(arg => arg.P1 == a.P1)));
But if you have multiple properties like P1,P2,P3... AutoFixture can be useful:
barMock.Verify(m => m.Something(It.Is<A>(arg => expectedA.Equals(a))));
Because you don't need to write out the equality checks manually for all the properties.

If you upgrade to AutoFixture 2.9.1 (or newer) you can call the CreateProxy method on the Likeness instance which will emit a dynamic proxy for the destination type.
The generated dynamic proxy overrides Equals using Likeness which simplifies the syntax (quite a lot).
Here is the original test method, modified to use the Likeness proxy:
[Test]
public void TestSample()
{
var foo = new Foo();
var barMock = new Mock<IBar>();
var expected = new A().AsSource().OfLikeness<A>().CreateProxy();
expected.P1 = 1;
foo.DoSomethingWith(barMock.Object);
Assert.True(expected.Equals(foo.Data)); // passes
barMock.Verify(m => m.Something(expected)); // passes
}
Note that it also makes the test assertion much more specific than accepting Any instance.
You can find more details on this new feature here.

Related

Singleton per string ctor parameter value, for both class A and dependent class B instances

I need to create a single instance, not based on the type or a lifetime scope decl, but on the value of a string parameter to the ctor. I also need this same effect for a dependent instance of another class, using the same string in its own unrelated ctor.
class A {
public A(string appId, B b) {}
}
class B {
public B(string appId) {}
}
In the above example, I need to create an A singleton and a B singleton, for unique values of appId.
I can resolve A and B with a TypedParameter, but the singleton-per-appId-value part I can't figure out. I tried just A alone to simplify (without dependent B involved). I looked at Keyed, Indexed, etc in the docs but none seemed to fit singleton-per-some-user-defined-key-value, unless I write my own Register lambda that uses my own memory cache of unique appId keys.
Does Autofac have a built-in terse way to enforce this?
There is not going to be a good solution to this because dependency injection is generally based on types, not parameter values. It's not the same as, say, setting up caching for a web app based on parameter values. More specifically, Autofac does not have anything "baked in" that will help you. (Nor, to my knowledge, does any other DI framework.)
Likely what you're going to need to do is create a tiny factory that does the caching for you and use that.
Here's an example that I'm not compiling and not testing but is coming off the top of my head to get you unblocked.
First, you'd need to create a little factory for your B class.
public class BFactory
{
private ConcurrentDictionary<string, B> _cache = new ConcurrentDictionary<string, B>();
public B GetB(string appId)
{
return this._cache.GetOrAdd(
appId,
a => new B(a));
}
}
Now you'll register BFactory as singleton, which will get you the one-instance-per-app-ID behavior you want. Register B as a lambda and it can use parameters.
builder.RegisterType<BFactory>().SingleInstance();
builder.Register((c, p) =>
{
var appId = p.Named<string>("appId");
var factory = c.Resolve<BFactory>();
return factory.GetB(appId);
});
Now you can resolve a B as long as there's a parameter passed to Resolve, like
using var scope = container.BeginLifetimeScope();
var b = scope.Resolve<B>(new NamedParameter("appId", "my-app-id"));
You can build something similar for A, but the AFactory can take a BFactory as a parameter so it can get the right instance of A.
public class AFactory
{
private ConcurrentDictionary<string, B> _cache = new ConcurrentDictionary<string, B>();
private readonly BFactory _factory;
public AFactory(BFactory factory)
{
this._factory = factory;
}
public A GetA(string appId)
{
return this._cache.GetOrAdd(
appId,
a => new A(a, this._factory.GetB(a)));
}
}
Same thing here, register the factory as a singleton and get A from the factory.
builder.RegisterType<AFactory>().SingleInstance();
builder.Register((c, p) =>
{
var appId = p.Named<string>("appId");
var factory = c.Resolve<AFactory>();
return factory.GetA(appId);
});
You can get fancy with it, too, like using the Func relationships if there are some things that need to come from the container. For example, let's say your B class really looks like this:
public class B
{
public B(string appId, IComponent fromContainer) { /* ... */ }
}
In there, maybe IComponent needs to come from the container but the appId comes from a parameter. You could make the BFactory be like this:
public class BFactory
{
private ConcurrentDictionary<string, B> _cache = new ConcurrentDictionary<string, B>();
private ILifetimeScope _scope;
public BFactory(ILifetimeScope scope)
{
// This will be the CONTAINER / root scope if BFactory
// is registered as a singleton!
this._scope = scope;
}
public B GetB(string appId)
{
return this._cache.GetOrAdd(
appId,
a => {
// Auto-generated factory! It will get IComponent from
// the container but let you put the string in as a parameter.
var func = this._scope.Resolve<Func<string, B>>();
return func(a);
});
}
}
Be aware if you use that auto-generated factory thing (the Func<string, B> thing) that you will need to register B by itself, like:
// You can't register the factory as the provider for B
// because it's cyclical - the BFactory will want to resolve
// a Func<string, B> which, in turn, will want to execute the
// BFactory.
builder.RegisterType<B>();
builder.RegisterType<BFactory>().SingleInstance();
That means you'd have to switch your code around to take a BFactory instead of a B. You can probably monkey with it to make it work, but you get the idea - you're going to have to make the caching mechanism yourself and that's what you'll hook into Autofac. Hopefully the above snippets can give you some ideas you can expand on and get you unblocked.

run method and store it one variable before each test in Nunit

I need to run a method before each test Like how before method works in TestNg.
What I am expecting is I need to take the Testname and find the relevant test data and store it variable. Currently I have included that step in Test. But it would be good to have to reduce a line of code in each test.
is it possible in Nunit?
Setup attribute is used to provide a common set of functions that are performed just before each test method is called. You can also get the Method name from TestContext.CurrentContext.Test.MethodName. There are also other properties on Test like Arguments or FullName depending on what you need.
[SetUp]
public void Setup()
{
var testName = TestContext.CurrentContext.Test.MethodName;
TestContext.WriteLine($"SetUp for {testName}");
}
Alternately, you can also use TestCaseData class which provides extended test case information for a parameterized test.
public class DemoClass {
[TestCaseSource(typeof(MyDataClass), nameof(MyDataClass.DivideTestCases))]
public int DivideTest(int n, int d)
{
return n / d;
}
[TestCaseSource(typeof(MyDataClass), nameof(MyDataClass.AddTestCases))]
public int AddTest(int a, int b)
{
return a + b;
}
}
public class MyDataClass
{
public static IEnumerable DivideTestCases
{
get
{
yield return new TestCaseData(12, 3).Returns(4);
yield return new TestCaseData(12, 2).Returns(6);
yield return new TestCaseData(12, 4).Returns(3);
}
}
public static IEnumerable AddTestCases
{
get
{
yield return new TestCaseData(10, 15).Returns(25);
yield return new TestCaseData(12, 10).Returns(22);
yield return new TestCaseData(14, 5).Returns(19);
}
}
}

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

autofac: IEnumerable<Lazy<IFoo, IFooMetaData>> --> Lazy.Value(with runtime param)?

Using Autofac, I have multiple IFoo components that take a run-time parameter in the constructor. I'm using some Metadata from the types along with the run-time parameter to construct and manage running instances.
interface IFoo
{
int RunTimeId { get; }
}
[FooMeta("ShaqFoo")]
class Foo1 : IFoo
{
public Foo1 (int runtTimeId)
{
...
}
[FooMeta("KungFoo")]
class Foo2 : IFoo
{
public Foo2 (int runtTimeId)
{
...
}
Module/Registration something like:
builder.Register<Func<int, Foo1>>(c =>
{
var cc = c.Resolve<IComponentContext>();
return id => cc.Resolve<Foo1>(TypedParameter.From<int>(id));
})
.As<Func<int, IFoo>>()
.WithMetadata<IFooMetaData>(m => m.For(sm => sm.FooType, typeof(Foo1)));
builder.Register<Func<int, Foo2>>(c =>
{
var cc = c.Resolve<IComponentContext>();
return id => cc.Resolve<Foo2>(TypedParameter.From<int>(id));
})
.As<Func<int, IFoo>>()
.WithMetadata<IFooMetaData>(m => m.For(sm => sm.FooType, typeof(Foo2)));
And a component that creates new Foos with the run-time parameters and metadata. I need to be create ALL IFoos for a given run-time parameter, and need to check for existing instances (essentially using Metadata + RunTimeId as a key) before creating.
public class FooActivator
{
public FooActivator(IEnumerable<Lazy<Func<int, IFoo>, IFooMetaData>> fooFactories)
{
m_FooFactories = fooFactories;
}
private void HandleNewRunTimeIdEvent(int id)
{
CreateFoosForNewId(id);
}
private void CreateFoosForNewId(int id)
{
foreach (var fooFactory in m_FooFactories)
{
if (!FooWithThisMetadataAndIdExists(fooFactory.Metadata.FooType, id))
{
var newFoo = fooFactory.Value(id);
}
}
}
}
Obviously, I can enumerate all of the IFoos and check metadata using the Lazy Enumeration, but can't pass in the run-time parameter to Lazy.Value. Seems like I need to pass in an Enumerable of Func<>s somehow, but can't figure out how to attach the metadata. Or maybe I need an entirely different approach?
Just getting my head wrapped around autofac, and hoping there's a clean way to accomplish this. I could settle for just using the concrete Foo type (instead of metadata) if there's a simple way to enumerate all of them (without creating them), and use the type + run-time Id as my key instead.
Updated the code with a working solution. Figured out how to register Factories properly with metadata. Seems to work.

Creating an object passing a lambda expression to the constructor

I have an object with a number of properties.
I want to be able to assign some of these properties when I call the constructor.
The obvious solution is to either have a constructor that takes a parameter for each of the properties, but that's nasty when there are lots. Another solution would be to create overloads that each take a subset of property values, but I could end up with dozens of overloads.
So I thought, wouldn't it be nice if I could say..
MyObject x = new MyObject(o => o.Property1 = "ABC", o.PropertyN = xx, ...);
The problem is, I'm too dim to work out how to do it.
Do you know?
C# 3 allows you to do this with its object initializer syntax.
Here is an example:
using System;
class Program
{
static void Main()
{
Foo foo = new Foo { Bar = "bar" };
}
}
class Foo
{
public String Bar { get; set; }
}
The way this works is that the compiler creates an instance of the class with compiler-generated name (like <>g__initLocal0). Then the compiler takes each property that you initialize and sets the value of the property.
Basically the compiler translates the Main method above to something like this:
static void Main()
{
// Create an instance of "Foo".
Foo <>g__initLocal0 = new Foo();
// Set the property.
<>g__initLocal0.Bar = "bar";
// Now create my "Foo" instance and set it
// equal to the compiler's instance which
// has the property set.
Foo foo = <>g__initLocal0;
}
The object initializer syntax is the easiest to use and requires no extra code for the constructor.
However, if you need to do something more complex, like call methods, you could have a constructor that takes an Action param to perform the population of the object.
public class MyClass
{
public MyClass(Action<MyClass> populator)
{
populator.Invoke(this);
}
public int MyInt { get; set; }
public void DoSomething()
{
Console.WriteLine(this.MyInt);
}
}
Now you can use it like so.
var x = new MyClass(mc => { mc.MyInt = 1; mc.DoSomething(); });
Basically what Andrew was trying to say is if you have a class (MyObject for eg) with N properties, using the Object Initializer syntax of C# 3.0, you can set any subset of the N properties as so:
MyObject x = new MyObject {Property1 = 5, Property4 = "test", PropertyN = 6.7};
You can set any of the properties / fields that way./
class MyObject
{
public MyObject(params Action<MyObject>[]inputs)
{
foreach(Action<MyObject> input in inputs)
{
input(this);
}
}
}
I may have the function generic style wrong, but I think this is sort of what you're describing.