I have the following concrete class
public class Service
{
private IRepository _rep;
public Service(IRepository rep)
{
_rep() = rep;
}
public Boolean Foo(Int32 param1)
{
_rep.Foo(param1);
}
public void Bar()
{
_rep.Bar();
}
}
I have created the following shim for it.
using (ShimsContext.Create())
{
ShimService shimService = new ShimService()
{
FooInt32 = (param1) => { return true; },
};
}
I want foo to always return true. This works.
I want Bar to operate normally. This doesn't work.
When I debug _rep is null so I believe I need to pass this an IRepository into the Shims constructor but I can't work out how to do it.
I found the solution. You have to create an instance of the Service you want to Shim which includes the injection of IRepository and pass that that service into the Shim.....so
IRepository rep = new Repository();
Service service = new Service(rep);
ShimSignOffService shimService = new ShimSignOffService(service)
{
IsBookmarkProcessedInt32 = (bookmarkId) => { return true; },
};
Related
I'm new to using Moq with Xunit in Visual Studio 2019.
I want to mock the contructor call of a class that is being called in the contructor of my tested class.
A simple demonstration of my problem:
public class MockedClass : IMockedClass
{
public MockedClass()
{
// don't call this
}
public List<string> Function1()
{ /* return a List<string> here */ }
}
public class MyClass
{
readonly IMockedClass mockedClass = null;
public MyClass()
{
mockedClass = new MockedClass();
}
public string Function2()
{ /* return a string here */ }
}
public class MyClassTest
{
[Fact]
public string Function2Test()
{
var returnMock = new List<string>() { "1", "2", "3" };
var mockMockedClass = new Mock<IMockedClass>();
mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
var myClass = new MyClass();
var result = myClass.Function2();
...
}
}
My problem is, that in the test Function2Test the constructor of MyClass is being called that calls the constructor of MockedClass.
But I don't want the constructor of MockedClass being called.
How can I mock the constructor of MockedClass?
I think you might need to slightly modify your code. You see, obtaining a mock of an interface by itself does not automatically change how other implementations behave when instantiated from other parts of code. You generally want to inject your mocked implementations into tested code via Dependency Injection.
public class MyClass
{
readonly IMockedClass mockedClass = null;
public MyClass(IMockedClass c)
{
mockedClass = c; // now you'll get the correct implemetation
}
public string Function2()
{ /* return a string here */ }
}
void Main()
{
var returnMock = new List<string>() { "1", "2", "3" };
var mockMockedClass = new Mock<IMockedClass>(); // get your mock here
mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
var myClass = new MyClass(mockMockedClass.Object); // inject it here
var result = myClass.Function2();
}
Then you will need to set up your Dependency Injection container to provide you with a concrete MockedClass when your actual application code runs. Depending on your code and requirements, there are heaps of options so I won't recommend a specific framework here.
Theoretically, you might be able to mock out the class in your current code structure. I could potentially see how you either opt for Fakes or fancy reflection techniques. However it likely will be way to much effort for going against what seems to be community-accepted best practice.
You were on the right direction to mock dependencies, but you lack the implementation of the Dependency Inversion Principle.
With your code as-is, you are tying your MyClass to the MockedClass, and furthermore you let MyClass control the MockedClass object's lifetime.
What you should do, is alter the constructor of MyClass to accept an IMockedClass object. Note that you should pass the interface, not the class type.
public class MyClass
{
readonly IMockedClass mockedClass = null;
public MyClass(IMockedClass mockedClass)
{
this.mockedClass = mockedClass();
}
public string Function2()
{ /* return a string here */ }
}
and your test code will be:
public string Function2Test()
{
var returnMock = new List<string>() { "1", "2", "3" };
var mockMockedClass = new Mock<IMockedClass>();
mockMockedClass.Setup(x => x.Function1()).Returns(returnMock);
var myClass = new MyClass(mockMockedClass.Object);
var result = myClass.Function2();
...
}
I've got a setup like this with a concrete class that is instantiated inside the method I want to test. I want to mock this concrete class an not have it execute the code inside. Hence, no exception should be thrown:
public class Executor
{
public bool ExecuteAction(ActionRequest request)
{
switch (request.ActionType)
{
case ActionType.Foo:
var a = new Foo();
return a.Execute(request);
case ActionType.Bar:
var b = new Bar();
return b.Execute(request);
}
return true;
}
}
public class Foo
{
public virtual bool Execute(ActionRequest request)
{
throw new NotImplementedException();
}
}
public class Bar
{
public virtual bool Execute(ActionRequest request)
{
throw new NotImplementedException();
}
}
My NUnit test looks like this:
[Test]
public void GivenARequestToFooShouldExecuteFoo()
{
var action = new Mock<Foo>();
action.Setup(x => x.Execute(It.IsAny<ActionRequest>())).Returns(true);
var sut = new Mock<Executor>();
sut.Object.ExecuteAction(new ActionRequest
{
ActionType = ActionType.Foo
});
}
[Test]
public void GivenARequestToBarShouldExecuteBar()
{
var action = new Mock<Bar>();
action.Setup(x => x.Execute(It.IsAny<ActionRequest>())).Returns(true);
var sut = new Mock<Executor>();
sut.Object.ExecuteAction(new ActionRequest
{
ActionType = ActionType.Bar
});
}
I fiddled around with CallBase, but it didn't get me anywhere. Is there anyway I can solve this easily without dependency injection of these classes and adding interfaces? Is this possible just using Moq?
The only thing I can think to do currently is move the Execute methods into the Executor class and rename them to ExecuteFoo() and ExecuteBar(), but I have a lot of code to move so they'd have to be partial classes (sub classes?).
The problem is not with the mocking of the method but with the creation of the concrete class. The creation of Foo and Bar need to be inverted out of the Executor. It is responsible for executing the action, not creating it. with that this interface was created to handle the creation.
public interface IActionCollection : IDictionary<ActionType, Func<IExecute>> {
}
think of this as a collection of factories or a collection of creation strategies.
A common interface was created for the actions.
public interface IExecute {
bool Execute(ActionRequest request);
}
public class Foo : IExecute {
public virtual bool Execute(ActionRequest request) {
throw new NotImplementedException();
}
}
public class Bar : IExecute {
public virtual bool Execute(ActionRequest request) {
throw new NotImplementedException();
}
}
And the Executor was refactored to use dependency inversion.
public class Executor {
readonly IActionCollection factories;
public Executor(IActionCollection factories) {
this.factories = factories;
}
public bool ExecuteAction(ActionRequest request) {
if (factories.ContainsKey(request.ActionType)) {
var action = factories[request.ActionType]();
return action.Execute(request);
}
return false;
}
}
With that refactor done the Executor can be tested with fake actions.
public void GivenARequestToFooShouldExecuteFoo() {
//Arrange
var expected = true;
var key = ActionType.Foo;
var action = new Mock<Foo>();
action.Setup(x => x.Execute(It.IsAny<ActionRequest>())).Returns(expected);
var actions = new Mock<IActionCollection>();
actions.Setup(_ => _[key]).Returns(() => { return () => action.Object; });
actions.Setup(_ => _.ContainsKey(key)).Returns(true);
var sut = new Executor(actions.Object);
var request = new ActionRequest {
ActionType = ActionType.Foo
};
//Act
var actual = sut.ExecuteAction(request);
//Assert
Assert.AreEqual(expected, actual);
}
A production implementation of the factory collection can look like this
public class ActionCollection : Dictionary<ActionType, Func<IExecute>>, IActionCollection {
public ActionCollection()
: base() {
}
}
and configured accordingly with your concrete types.
var factories = ActionCollection();
factories[ActionType.Foo] = () => new Foo();
factories[ActionType.Bar] = () => new Bar();
I have added a unit test to a mvc5 application manually.
This is my business logic
public void AddTreatments(TreatmentView model)
{
using(var treatment = new TreatmentRepository())
{
var treat = new PhysiqueData.ModelClasses.Treatment()
{
treatmentID = model.treatmentID,
treatmentCost = model.treatmentCost,
treatmentDuration = model.treatmentDuration,
treatmentName = model.treatmentName
}
treatment.Insert(treat);
}
}
This is my repository used in the service layer
public class TreatmentRepository:ITreatmentRepository
{
private ApplicationDbContext _datacontext;
private readonly IRepository<Treatment> _treatmentRepository;
public TreatmentRepository()
{
_datacontext = new ApplicationDbContext();
_treatmentRepository = new RepositoryService<Treatment>(_datacontext);
}
public void Insert(Treatment model)
{
_treatmentRepository.Insert(model);
}
}
The next code is my actual unit test for my treatment and it is not working,
please can I get some guidance on it. I googled a lot of things and still can't get it right.
[TestClass]
public class UnitTest1
{
[TestMethod]
public void AddingTreatmenttodatabase()
{
//var business = new TreatmentBusiness(new TreatmentRepository());
var treatment = new Treatment()
{
treatmentID = 1,
treatmentCost = 250,
treatmentDuration = 45,
treatmentName = "LowerBack"
};
var repositoryMock = new Mock<ITreatmentRepository>();
repositoryMock.Setup(x => x.Insert(treatment));
var business = new TreatmentBusiness(repositoryMock.Object);
business.AddTreatments(treatment);
repositoryMock.Verify(x => x.Insert(treatment), Times.Once());
}
}
So you're instantiating a mock of ITreatmentRepository, setting up some behaviour and injecting it into your TreatmentBusiness class. So far, so good.
But then, in your AddTreatments method, you're instantiating a new TreatmentRepository, instead of using the one injected in via the constructor.
I'm assuming your constructor looks something like this:
public class TreatmentBusiness
{
private readonly ITreatmentRepository repository;
public TreatmentBusiness(ITreatmentRepository repository)
{
this.repository = repository;
}
...
}
In which case, your method should look like this:
public void AddTreatments(TreatmentView model)
{
using (var treatment= this.repository)
{
var treat = new PhysiqueData.ModelClasses.Treatment();
{
treat.treatmentID = model.treatmentID;
treat.treatmentCost = model.treatmentCost;
treat.treatmentDuration = model.treatmentDuration;
treat.treatmentName = model.treatmentName;
}
treatment.Insert(treat);
}
}
Notice the usage of the field repository, as opposed to instantiating a new one.
As per Jimmy_keen's suggestion, in order to ensure your repository is properly instantiated and accessible throughout your class, a factory is advisable.
There are several ways you can achieve a repository factory, either you hand crank a dedicated factory and inject that into your constructor, like so:
public class TreatmentBusiness
{
private readonly ITreatmentRepositoryFactory repositoryFactory;
public TreatmentBusiness(ITreatmentRepositoryFactory repositoryFactory)
{
this.repositoryFactory = repositoryFactory;
}
...
}
And that change the way you access your repository like so:
public void AddTreatments(TreatmentView model)
{
using (var treatment= this.repositoryFactory.Make())
//or whatever method name you've chosen on your factory
If you feel this is too heavy handed, you can opt for a method delegate (Func<>) and inject just a method that instantiates a new TreatmentRepository.
This would change your constructor like so:
public class TreatmentBusiness
{
private readonly Func<TreatmentRepository> getTreatmentRepository;
public TreatmentBusiness(Func<TreatmentRepository> getTreatmentRepository)
{
this.getTreatmentRepository = getTreatmentRepository;
}
....
}
And you would change your method like this:
public void AddTreatments(string model)
{
using (var treatment = this.getTreatmentRepository()) //Or this.getTreatmentRepository.Invoke() - same thing
{
...
}
}
The way you resolve that dependency is up to you, either do it manually and inject that delegate like this when instantiating your Business object:
var treatmentBusiness = new TreatmentBusiness(() => new TreatmentRepository());
or you can use one of the many IoC containers/DI frameworks out there.
I am using Moq library for unit testing. Now what i want is that when I access my object for the first time it should return null, and when i access this on second time it should return something else.
here is my code
var mock = new Mock<IMyClass>();
mock.Setup(?????);
mock.Setup(?????);
var actual = target.Method(mock.object);
in my method i am first checking that whether mock object is null or not, if it is null then do initialize it and then do some calls on it.
bool Method(IMyClass myObj)
{
if (myObj != null)
return true;
else
{
myObj = new MyClass();
bool result = myObj.SomeFunctionReturningBool();
return result;
}
}
what to do setup for mock object,
Also i need to know how to mock this line
bool result = myObj.SomeFunctionReturningBool();
It sounds like you are trying to run two tests with one test method - maybe it would be better to split the tests into two?
You also want to initialise a new object if the method is passed null. To test this, I suggest creating a factory object responsible for creating instances of MyClass. The new code would look like:
interface IMyClassFactory
{
IMyClass CreateMyClass();
}
bool Method(IMyClass myObj, IMyClassFactory myClassFactory)
{
if (myObj != null)
{
return true;
}
myObj = myClassFactory.CreateMyClass();
return myObj.SomeFunctionReturningBool();
}
Then the tests would look like:
[Test]
public void Method_ShouldReturnTrueIfNotPassedNull()
{
Assert.That(target.Method(new MyClass()), Is.True);
}
[Test]
public void Method_ShouldCreateObjectAndReturnResultOfSomeFunctionIfPassedNull()
{
// Arrange
bool expectedResult = false;
var mockMyClass = new Mock<IMyClass>();
mockMyClass.Setup(x => x.SomeFunctionReturningBool()).Returns(expectedResult);
var mockMyFactory = new Mock<IMyClassFactory>();
mockMyFactory.Setup(x => x.CreateMyClass()).Returns(mockMyClass.Object);
// Act
var result = target.Method(null, mockMyFactory.Object);
// Assert
mockMyClass.Verify(x => x.SomeFunctionReturningBool(), Times.Once());
mockMyFactory.Verify(x => x.CreateMyClass(), Times.Once());
Assert.That(result, Is.EqualTo(expectedResult));
}
Here the factory pattern has been used to pass in an object which can create objects of IMyClass type, and then the factory itself has been mocked.
If you do not want to change your method's signature, then create the factory in the class's constructor, and make it accessible via a public property of the class. It can then be overwritten in the test by the mock factory. This is called dependency injection.
Moq - Return null - This working example simply illustrates how to return null using Moq. While the line of code is required is the commented line below, a full working example is provided below.
// _mockShopService.Setup(x => x.GetProduct(It.IsAny<string>())).Returns(() => null);
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
public class Product
{
public string Id { get; set; }
public string Name { get; set; }
}
public interface IShopService
{
Product GetProduct(string productId);
}
public class ShopService : IShopService
{
public Product GetProduct(string productId)
{
if (string.IsNullOrWhiteSpace(productId))
{
return new Product();
}
return new Product { Id = "8160807887984", Name = "How to return null in Moq" };
}
}
public class Shop
{
private static IShopService _shopService;
public Shop(IShopService shopService)
{
_shopService = shopService;
}
public Product GetProduct(string productId)
{
Product product = _shopService.GetProduct(productId);
return product;
}
}
[TestClass]
public class ShopTests
{
Mock<IShopService> _mockShopService;
[TestInitialize]
public void Setup()
{
_mockShopService = new Mock<IShopService>();
}
[TestMethod]
public void ShopService_GetProduct_Returns_null()
{
//Arrange
Shop shop = new Shop(_mockShopService.Object);
//This is how we return null --- all other code above is to bring this line of code home
_mockShopService.Setup(x => x.GetProduct(It.IsAny<string>())).Returns(() => null);
//Act
var actual = shop.GetProduct(It.IsAny<string>());
//Assert
Assert.IsNull(actual);
}
}
To mock a result value you can do simply:
mock.Setup(foo => foo.SomeFunctionReturningBool()).Returns(true); // or false :)
for the other question, just pass null in the unit test instead of passing mock.object and your unit test cover that too. So you basically create two unit test one with:
var actual = target.Method(mock.object);
and the other one with:
var actual = target.Method(null);
Currently your SUT is tight-coupled with MyClass implementation. You can't mock objects which are instantiated with new keyword inside your SUT. Thus you cannot test your SUT in isolation, and your test is not unit test anymore. When implementation of MyClass.SomeFunctionReturningBool will change (it will return true instead of false), tests of your SUT will fail. This shouldn't happen. Thus, delegate creation to some dependency (factory) and inject that dependency to your SUT:
[Test]
public void ShouldReturnTrueWhenMyClassIsNotNull()
{
Mock<IMyClassFactory> factory = new Mock<IMyClassFactory>();
Mock<IMyClass> myClass = new Mock<IMyClass>();
var foo = new Foo(factory.Object);
Assert.True(foo.Method(myClass.Object));
}
[Test]
public void ShouldCreateNewMyClassAndReturnSomeFunctionValue()
{
bool expected = true;
Mock<IMyClass> myClass = new Mock<IMyClass>();
myClass.Setup(mc => mc.SomeFunctionReturningBool()).Returns(expected);
Mock<IMyClassFactory> factory = new Mock<IMyClassFactory>();
factory.Setup(f => f.CreateMyClass()).Returns(myClass.Object);
var foo = new Foo(factory.Object);
Assert.That(foo.Method(null), Is.EqualTo(expected));
factory.VerifyAll();
myClass.VerifyAll();
}
BTW assignment new value to method parameter does not affect reference which you passed to method.
Implementation:
public class Foo
{
private IMyClassFactory _factory;
public Foo(IMyClassFactory factory)
{
_factory = factory;
}
public bool Method(IMyClass myObj)
{
if (myObj != null)
return true;
return _factory.CreateMyClass().SomeFunctionReturningBool();
}
}
You can use TestFixture with parameter. this test will run two times and different type value.
using NUnit.Framework;
namespace Project.Tests
{
[TestFixture(1)]
[TestFixture(2)]
public class MyTest
{
private int _intType;
public MyTest(int type)
{
_intType = type;
}
[SetUp]
public void Setup()
{
if (_intType==1)
{
//Mock Return false
}
else
{
//Mock Return Value
}
}
}
}
I have a dependency being injected via Func<Owned<OwnedDependency>>. One of its dependencies requires a parameter that I will only have at the point of constructing OwnedDependency.
public class OwnedDependency
{
public OwnedDependency(IDependency1 dependency)
{
}
}
public interface IDependency1
{
}
public class Dependency1 : IDependency1
{
public Dependency1(MyParameter parameter)
{
}
}
public class MyClass
{
private readonly Func<Owned<OwnedDependency>> m_ownedDependencyFactory;
public MyClass(Func<Owned<OwnedDependency>> ownedDependencyFactory)
{
m_ownedDependencyFactory = ownedDependencyFactory;
}
public void CreateOwnedDependency()
{
var parameter = new MyParameter(...);
// ** how to setup parameter with the container? **
using (var ownedDependency = m_ownedDependencyFactory())
{
}
}
}
I can't work out a clean way of setting up the instance of MyParameter.
One approach I have explored is to inject ILifetimeScope into MyClass and then do something like:
var parameter = new MyParameter(...);
using (var newScope = m_lifetimeScope.BeginLifetimeScope())
{
newScope.Resolve<IDependency1>(new TypedParameter(typeof(MyParameter), parameter));
var ownedDependency = newScope.Resolve<OwnedDependency>();
// ...
}
but the container is becoming unnecessarily intrusive. Ideally what I would like to do is inject Func<IDependency1, Owned<OwnedDependency>> and the container be willing to use parameters passed in to satisfy any necessary dependency, not just the ones on OwnedDependency.
What about doing the resolution in two steps with using another factory for IDependency1:
public class MyClass
{
private Func<MyParameter, IDependency1> dependency1Factory;
private Func<IDependency1, Owned<OwnedDependency>> ownedDependencyFactory;
public MyClass(
Func<MyParameter, IDependency1> dependency1Factory,
Func<IDependency1, Owned<OwnedDependency>> ownedDependencyFactory)
{
this.dependency1Factory = dependency1Factory;
this.ownedDependencyFactory = ownedDependencyFactory;
}
public void CreateOwnedDependency()
{
var parameter = new MyParameter();
using (var owned = ownedDependencyFactory(dependency1Factory(parameter)))
{
}
}
}