Unit test with multiple interfaces - c#

I have Web API project with the following service class called from API Controller. I want to write unit testcase for the below class using Moq framework. How can I construct multiple interfaces using Moq? If its not possible using Moq, is there any other framework?
public class MyService : IMyService
{
private readonly IInterface1 _interface1;
private readonly IInterfaces2 _interface2;
private readonly IInterface3 _interface3;
public MyService(IInterface1 interface1,IInterface2 interface2,IInterface3 interface3)
{
_interface1=interface1;
_interface2=interface2;
_interface3=interface3;
}
public SomeModel MyMethod1(1Model model)
{
//do something here....
}
public SomeMode2 MyMethod2(Model2 model)
{
//do something here....
}
public SomeMode3 MyMethod3(Model3 model)
{
//do something here....
}
}

Imagine you have these interfaces:
public interface IOne
{
int Foo();
}
public interface ITwo
{
int Foo(string str);
}
And you have a class which depends on above interfaces:
public class Some
{
private readonly IOne one;
private readonly ITwo two;
public Some(IOne one, ITwo two)
{
this.one = one;
this.two = two;
}
public void Work()
{
// Uses one and two
}
}
And now you want to test the Work() method and you want to mock the dependencies, here is how:
// Arrange
// Let's set up a mock for IOne so when Foo is called, it will return 5
var iOneMock = new Mock<IOne>();
iOneMock.Setup(x => x.Foo()).Returns(5);
// Let's set up the mock for ITwo when Foo is called with any string,
// it will return 1
var iTwoMock = new Mock<ITwo>();
iTwoMock.Setup(x => x.Foo(It.IsAny<string>())).Returns(1);
var some = new Some(iOneMock.Object, iTwoMock.Object);
// Act
some.Work();
// Assert
// Let's verify iOneMock.Foo was called.
iOneMock.Verify(x => x.Foo());
// Let's verify iTwoMock.Foo was called with string "One" and was called only once
iTwoMock.Verify(x => x.Foo("One"), Times.Once());
In my example above I tried to show methods which take an argument, methods which take no argument, verifying method was called and verify method was called once. That should give you and idea of the options available. There are many other options available. Please see the Moq documentation for more.

You can use AutoMoq to solve the dependency injections.
var mocker = new AutoMoqer();
var myService = mocker.Create<MyService>();
var interface1 = mocker.GetMock<IInterface1>();

Related

Mocking a method on a property

I need to set the return value for a method returned by a property, basically I need to set what this does:
mockedObject.TheProperty.GetTheValues()
I just need it to return Enumerable.Empty<MyType>.
For the purposes of demonstrating that the functionality exists assuming
public interface IFoo {
IBar TheProperty { get; set; }
}
public interface IBar {
IEnumerable<MyType> GetTheValues();
}
public class MyType { }
Moq allows for auto mocking hierarchies otherwise known as recursive mocks
[TestClass]
public class RecursiveMocksTests {
[TestMethod]
public void Foo_Should_Recursive_Mock() {
//Arrange
IEnumerable<MyType> expected = Enumerable.Empty<MyType>();
var mock = new Mock<IFoo>();
// auto-mocking hierarchies (a.k.a. recursive mocks)
mock.Setup(_ => _.TheProperty.GetTheValues()).Returns(expected);
var mockedObject = mock.Object;
//Act
IEnumerable<MyType> actual = mockedObject.TheProperty.GetTheValues();
//Assert
actual.Should().BeEquivalentTo(expected);
}
}
Note that at no point was IBar ever initialized or configured. The framework will auto mock that interface because of the setup shown above.
If however, more functionality is needed from an IBar, then a proper mock should be done and configured accordingly. There is also nothing stopping the use of configuring multiple IBar members via the IFoo mock.
Reference Moq Quickstart: Properties
Imagine you have this:
public interface IA
{
IEnumerable<MyType> TheProperty { get; set; }
}
public class MyType {}
Then here is how to mock it so when TheProperty is called, it returns and IEnumerable.Empty<MyType>:
[TestMethod]
public void SomeTest()
{
/* Arrange */
var iAMock = new Mock<IA>();
iAMock.Setup(x => x.TheProperty).Returns(Enumerable.Empty<MyType>());
/* Act */
/* Assert */
}

c# mock return base method

I am writing a unit test case with NUnit framework to test our code.
The code has referenced to 3rd party libraries like below:
class MyClass: BaseClass
{
public void override FunctionA()
{
var a = BaseFunctionB();
}
}
we don't have sourcecode for BaseClass, but the BaseFunctionB is non-virtual.
I was trying to
Setup(x=> x.BaseFunctionB()).Reteruns("my values");
but it doesn't allow.
I just want to test the FunctionA in MyClass, I don't care whether it's correct in BasefunctionB.
How to test in this case?
----------------------------2018-01-03 updated---------------------------------
I made some update for the BaseClass:
public abstract class BaseClass1//we dont have source code for this class
{
public int GetValue()
{
//do something here
return 1;//
}
public abstract int GenerateOutPut();
}
class abstract class BaseClass2: BaseClass1
{
public new virtual int GetValue()
{
return base.GetValue();
}
}
class MyClass1: BaseClass2
{
public override int GenerateOutPut()
{
var a = GetValue();
a += 1;
return a;
}
}
class MyClass2: BaseClass2
{
public override int GenerateOutPut()
{
var a = GetValue();
a -= 1;
return a;
}
}
// there are many MyClass
class MyClassN: BaseClass2
{
public override int GenerateOutPut()
{
var a = GetValue();
//different logic here.
return a;
}
}
i made a class for testing MyClass1 like below:
class TestClass1: MyClass1
{
public override int GetValue()
{
return 100;
}
}
test case as below:
public void TestFunction()
{
var test = new TestClass1();
var result = test.GetValue();
assert.AreEqual(101, result);
}
Now I have to create many TestClas which looks not good. but in terms of running out code coverage, i have to make it( i try to use mock object to execute, there is no code covered in report, i guess because it create proxy and run it on proxy, so i create the same thing myself to test the original source code)
Do i have a better solution?
Creating the second base class and the new member to encapsulate the 3rd party dependency was a good idea. It allows you to override the member in derived classes. In general try to avoid mocking what you do not own. Instead encapsulate 3rd party dependencies behind an abstraction you control so as to allow you the flexibility to mock/stub/fake any desired behavior for testing.
Using MyClass1 from your example
public class MyClass1 : BaseClass2 {
public override int GenerateOutPut() {
var a = GetValue();
a += 1;
return a;
}
}
The following test can be done to verify the expected behavior from the subject under test. Note Moq allows for base members to be called by setting CallBase = true on the mocked object.
[TestClass]
public class MyClass1_Test {
[TestMethod]
public void MyClass1_Should_Generate_Output() {
//Arrange
var expected = 0;
var mock = new Mock<MyClass1>() {
CallBase = true //<-- let mock call base members
};
mock.Setup(_ => _.GetValue()).Returns(expected); // <-- mocked behavior
var sut = mock.Object; //<-- subject under test.
//Act
var actual = sut.GenerateOutPut();
//Assert
actual.Should().Be(expected + 1);
}
}
Which is almost like what you did manually but now via the mock proxy.

Testing different concrete implementations of single interface?

I have the following code:
public interface IFoo
{
IResult ResolveTheProblem(IBar inputData);
}
public class FastFoo : IFoo
{
public IResult ResolveTheProblem(IBar inputData)
{
// Algorithm A - resolves the problem really fast
}
}
public class SlowFoo : IFoo
{
public IResult ResolveTheProblem(IBar inputData)
{
// Algorithm B - different algoritm, resolves the problem slow
}
}
The most important thing to test is implementation of each algorithm.
For testing I'm using NUnit and NSubstitute. Right now I have test like this:
[Test]
public void FooTest()
{
IFoo foo = Substitute.For<IFoo>();
IBar bar = Substitute.For<IBar>();
IResult result = foo.ResolveTheProblem(bar);
Assert.IsNotNull(result);
}
My two questions:
Is that test even necessary? I'm not sure about that
How can I test implementation of each IFoo (FastFoo and SlowFoo)?
EDIT: FastFoo and SlowFoo are two completely different implementations. The result of both is a random number from 1 to 10.
No, it's not necessary. Why would you want to test a substitute implementation?
You substitute your dependencies, like IBar.
You test your concrete implementations:
[Test]
public void SlowFooTest()
{
IBar bar = Substitute.For<IBar>();
// Setup bar expectations / canned responses as required
var foo = new SlowFoo(bar);
IResult result = foo.ResolveTheProblem(bar);
// Validate result from concrete class:
Assert.IsNotNull(result);
}
[Test]
public void FastFooTest()
{
IBar bar = Substitute.For<IBar>();
var foo = new FastFoo(bar);
IResult result = foo.ResolveTheProblem(bar);
Assert.IsNotNull(result);
}
Is that test even necessary? I'm not sure about that
That test does not appear to do anything. You appear to be creating a test double for the service under test.
How can I test implementation of each IFoo (FastFoo and SlowFoo)?
Is the answer always going to be the same for FastFoo and SlowFoo, or does FastFoo trade accuracy for speed?
If they are always the same then inheritance. Create a base FooTest with an abstract CreateFoo. Then two concrete implementations.
If they are not always the same, then again inheritance but with a fuzzy element.
abstract class AbstractFooTester {
[Test]
public void WhenBarIsSomethingThenResultIsSomethingElse() {
var mockRandomNumberGenerator = createRandomNumberMock(5);
var mockBar = Substitute.For<IBar>();
// set up Bar
...
var subject = createFoo(mockRandomNumberGenerator);
IResult result = subject.ResolveTheProblem(bar);
AssertResult(result, ...);
}
abstract Foo createFoo(RandomNumberGenertor g);
RandomNumberGenertor createRandomNumberMock(Int i) { ... }
}
class TestFastFoo extends AbstractFooTester {
Foo createFoo(RandomNumberGenertor g) { return new FastFoo(g); }
}
class TestSlowFoo extends AbstractFooTester {
Foo createFoo(RandomNumberGenertor g) { return new SlowFoo(g); }
}

Autofac dynamic invocation with Func and Dependency Injection

Providing that I have a class as follows
public class Foo
{
public Foo(string someTitle, IFooService fooService)
{
// do stuff
}
}
I know that I can instantiate it like this using DI and autofac
public class Bar
{
public Bar(Func < string, IFooService, Foo > foo, IFooService fooService)
{
var foo = foo("some string", fooService);
}
}
but I'm wondering if there's any way for Bar to not have to know anything about IFooService? I'd like to not have to inject IFooService into Bar just to satisfy the func.
Essentially something like this
// pseudo code - don't use
public class Bar
{
public Bar(Func < string, Foo > foo)
{
var foo = foo("some string");
}
}
What I'm really trying to do in my app is remove all instances of Service Location, and rely solely on Dependency Injection.
Autofac should be able to do exactly what you want by using the Func<T> implicit relationship.
Here is a small repro showing how you can omit the IFooService parameter in the Func<T> and as long as the other dependencies can be resolved by Autofac, you're good to go.
Sample types that do some crazy work...
public class Bar
{
private Foo _foo;
// This constructor looks like what you're aiming for...
public Bar(Func<string, Foo> factory)
{
this._foo = factory("title");
}
public void ShowMeCoolStuff()
{
this._foo.DoWork();
}
}
public class Foo
{
private string _title;
private IFooService _service;
// The Foo class takes the title AND an IFooService...
public Foo(string title, IFooService service)
{
this._title = title;
this._service = service;
}
public void DoWork()
{
Console.WriteLine("Foo title = {0}", this._title);
this._service.DoMoreWork();
}
}
public interface IFooService
{
void DoMoreWork();
}
public class FooService : IFooService
{
public void DoMoreWork()
{
Console.WriteLine("FooService doing more work.");
}
}
When you register, make sure all the dependencies are registered - Foo, Bar, something implementing IFooService:
var builder = new ContainerBuilder();
builder.RegisterType<Foo>();
builder.RegisterType<Bar>();
builder.RegisterType<FooService>().As<IFooService>();
var container = builder.Build();
When you resolve, everything chains down the line. This resolution...
var bar = container.Resolve<Bar>();
bar.ShowMeCoolStuff();
...will yield the following console output:
Foo title = title
FooService doing more work.
There is fairly robust documentation with examples over on the Autofac site.
That's where you use factories for:
public interface IFooFactory
{
Foo CreateFoo(string value);
}
And bar can simply depend on IFooFactory.
The implementation can look as follows:
public class FooFactory : IFooFactory
{
private readonly IFooService fooService;
public FooFactory(IFooService fooService)
{
this.fooService = fooService;
}
public Foo CreateFoo(string value)
{
return new Foo(value, this.fooService);
}
}
But the given string seems like a runtime value, i.e. a value that changes from request to request or from call to call. Prevent mixing runtime values with design time dependencies as explained here, here and here. Instead, pass the runtime value as method argument to the Foo methods you are calling. That will completely remove the problem.

TDD How to Assert that a property of a POCO is set within a method that is being tested

We are creating a C# application using TDD and DI methodologies and NSubstitute.
We are writing a CreateThing method:
name and description strings as parameters
create a new Thing object
set the Name and Description properties of Thing from the method parameters
set the Status to Active
pass the Thing to a method on another class (via constructor injection) for further processing
We know how to write a test for the call to the other class by using Substitute.For and .Received().
How do we write tests for the Thing properties being set?
You can use Argument matchers namely Conditional matcher which looks like Arg.Is<T>(Predicate<T> condition). Your matcher could look like:
anotherClass.Received().Process(Arg.Is<Thing>(thing => !string.IsNullOrEmpty(thing.Name)));
Full listing:
public class Thing
{
public string Name { get; set; }
}
public class AnotherClass
{
public virtual void Process(Thing thing)
{
}
}
public class CreateThingFactory
{
private readonly AnotherClass _anotherClass;
public CreateThingFactory(AnotherClass anotherClass)
{
_anotherClass = anotherClass;
}
public void CreateThing()
{
var thing = new Thing();
thing.Name = "Name";
_anotherClass.Process(thing);
}
}
public class CreateThingFactoryTests
{
[Fact]
public void CreateThingTest()
{
// arrange
var anotherClass = Substitute.For<AnotherClass>();
var sut = new CreateThingFactory(anotherClass);
// act
sut.CreateThing();
// assert
anotherClass.Received().Process(Arg.Is<Thing>(thing => !string.IsNullOrEmpty(thing.Name)));
}
}

Categories

Resources