I have a strange trouble. I am not too familiar with Moq, being more a GUI guy. I tried to mock a factory method in my code. The factory looks like this, and returns a ISettings instance which does many IO Operations. I want it to return a memory only ISettings instance to accelerate my test.
public class SettingsFactory
{
internal ISettings mSettingsImpl;
internal virtual ISettings CreateOrGetSettings()
{
return mSettingsImpl ?? (mSettingsImpl = new XmlSettings());
}
}
and the mock is
var imocked = new Mock<SettingsFactory>() {CallBase = false};
imocked.Setup(x => x.CreateOrGetSettings()).Returns(new NonPersistingSettings());
var tryToSeeTheType = imocked.Object.CreateOrGetSettings();
the tryToSeeTheType is however XMLSettings and not NonPersistingSettings as I would expect. Stepping through results into the code shown me that it goes directly into the original factory method. Any suggestions what I do wrong here?
The "Object" property of a mocked object is not actually an instance of the class you are trying to mock.
The purpose of a mock is to be able to replace an object the method you are trying to test depends on.
Imagine that your SettingsFactory performs very expensive operations like for example accessing the network or a database or the file system. You do not want your test to access those expensive resources so you create a mock. I would be something like this:
public class ClassThatUsesSettingsFactory
{
private readonly SettingsFactory _settingsFactory;
public ClassThatUsesSettingsFactory(SettingsFactory settingsFactory)
{
_settingsFactory = settingsFactory;
}
public void MethodThatCallsSettingsFactory()
{
//... do something
var settings = _settingsFactory.CreateOrGetSettings();
//... do something
}
}
By doing this you are able to replace the SettingsFactory with a mock on your unit test like so:
[TestMethod]
public void MakeSureSettingsFactoryIsCalled()
{
var settingsFactoryMock = new Mock<SettingsFactory>();
settingsFactoryMock.Setup(f => f.CreateOrGetSettings(), Times.Once).Verifiable();
var subjectUnderTest = new ClassThatUsesSettingsFactory(settingsFactoryMock.Object);
subjectUnderTest.MethodThatCallsSettingsFactory();
settingsFactoryMock.Verify();
}
This unit test is basically only making sure that the method CreateOrGetSettings gets called once and only once when the MethodThatCallsSettingsFactory gets executed.
What Moq does is to create a different class with a different implementation of its virtual method that will, most likely, set a flag to true once it gets called and then check the value of that flag on the "Verify" method.
There is a lot to grasp here so I hope it is clear enough since you mentioned that you do not have a lot of experience with Moq.
Related
tldr; How do I mock a call to a base method (using moq)?
I need to find a way to either workaround a problem regarding mocking a method that belongs to the class I inherit from, or to actually be able to just mock it.
I will start by posting some code:
The code to test:
public class CustomProductListingService : ProductListingService
{
public override IEnumerable<Product> ListAllProducts(ICategory category)
{
//does some internal filtering and to the developer unkown magic..
//would like to mock the result of this call..
var baseResult = base.ListAllProducts(category);
if(category.Name.StartsWith("A"))
return baseResult.Where(p => p.Name.StartsWith("A"));
else if(category.Name.StartsWith("B"))
return baseResult.Where(p => p.Name.StartsWith("B"));
else
return baseResult;
}
}
The test:
[TestMethod]
public void CustomProductListingService_ShouldOnlyReturnProductsWithNameStartingWithA()
{
//arrange
var customProductListingService = new CustomProductListingService();
ICategory category = new category
{
Name = "Abcd"
};
//act
var result = customProductListingService.ListAllProducts(category);
//assert
foreach(var product in result)
{
Assert.IsTrue(product.StartsWith("A"));
}
}
as you can see I call base.ListAllProducts from within my own implementation of ListAllProducts, now what I would like to be able to do is to mock base.ListAllProducts since I really dont care about what that method does internally and want to be able to control the outcome(return) so I can test my own implementation.
However, there is also another issue, this code is all a part of an implementation for an existing system, where the system normally would just inject the ProductListingService using a DI, but in my case I needed some custom behaviour and thats why the CustomProductListingService exists. What I have basically done then is to override the default registration of the system for ProductListingService and instead told it to inject my custom class CustomProductListingService.
In this case the DI-framework used is StructureMap, so basically the resultning container registration would end up looking something like:
var container = new Container(c =>
{
//use system implementation
c.For<ProductListingService>().Use<ProductListingService>();
//override system with my implementation
c.For<ProductListingService>().Use<CustomProductListingService>();
});
This then causes a problem where I cant simply do this:
public class CustomProductListingService : ProductListingService
{
private readonly ProductListingService _productListingService;
public CustomProductListingService(ProductListingService productListingService)
{
this._productListingService = productListingService;
}
public override IEnumerable<Product> ListAllProducts(ICategory category)
{
//does some internal filtering and to the developer unkown magic..
//would like to mock the result of this call..
var baseResult = this._productListingService.ListAllProducts(category);
if(category.Name.StartWith("A"))
return baseResult.Where(p => p.Name.StartWith("A"));
else if(category.Name.StartWith("B"))
return baseResult.Where(p => p.Name.StartWith("B"));
else
return baseResult;
}
}
Since that would cause a circular dependency and would be sort of strange to inject an instance thats the same type as the class I inherit from. (If this was possible I could simply mock the instance thats passed as a parameter to the constructor).
Any ideas of how to get around this?
Should probably add that the mocking-framework Im using is Moq, if that somehow makes this easier to solve.
i surf over internet for mock base class member in Nunit test case with no luck and finally decide to ask this scrap to stack overflow community.
Below code snippet has scenario in my application. i am going to write unit test for BankIntegrationController class and i want to make stub data or make mock for IsValid property and Print method.
Fremwork : Moq,Nunit
public class CController : IController
{
public bool IsValid {get;set;}
public string Print()
{
return // some stuff here;
}
}
public class BankIntegrationController : CController, IBankIntegration
{
public object Show()
{
if(this.IsValid)
{
var somevar = this.Print();
}
return; //some object
}
}
You don't need to mock anything. Just set the property before calling Show:
[Fact]
public void Show_Valid()
{
var controller = new BankIntegrationController { Valid = true };
// Any other set up here...
var result = controller.Show();
// Assertions about the result
}
[Fact]
public void Show_Invalid()
{
var controller = new BankIntegrationController { Valid = false };
// Any other set up here...
var result = controller.Show();
// Assertions about the result
}
Mocking is a really valuable technique when you want to specify how a dependency would behave in a particular scenario (and particularly when you want to validate how your code interacts with it), but in this situation you don't have any dependencies (that you've shown us). I've observed a lot of developers reaching for mocks unnecessarily, in three situations:
When there's no dependency (or other abstract behaviour) involved, like this case
When a hand-written fake implementation would lead to simpler tests
When an existing concrete implementation would be easier to use. (For example, you'd rarely need to mock IList<T> - just pass in a List<T> in your tests.)
I am new to trying to mock things in unit tests...
Example Code simplified for posting:
namespace MockInvestigate.Monitor
{
internal interface IAgentRepo
{
Dictionary<string, string> GetAgentAppSettings(string moduleName);
}
public class AgentRepo : IAgentRepo
{
public virtual Dictionary<string, string> GetAgentAppSettings(string moduleName)
{
return new Dictionary<string, string> { { "real", "data" } };
}
}
}
This is the method I want to unit test - but override the call to GetAgentAppSettings
namespace MockInvestigate
{
public class Class1
{
public static bool IsInitialized(string taskName)
{
AgentRepo ar = new AgentRepo();
var arReturn = ar.GetAgentAppSettings(taskName);
return arReturn.ContainsKey("real");
}
}
}
The unit test - trying to mock the call to 'GetAgentAppSettings'
[TestMethod]
public void TestMethod1()
{
var repo = Substitute.ForPartsOf<AgentRepo>();
var appReturn = new Dictionary<string, string> { { "bogus", "bogus2" } };
repo.GetAgentAppSettings("somevalue").ReturnsForAnyArgs(appReturn);
bool retValue = Class1.IsInitialized("somevalue");
Assert.IsFalse(retValue);
}
When my test is run, the real GetAgentAppSettings is called, returning "real", "data" and not the bogus data I want.
I have tried .When(...).DoNotCallBase().
Can my test be modified to work? Does the underlying code need to change to work?
Any help would be appreciated.
After creating the substitute repo, you have to inject it inside Class1.
In your code, however, you are creating the AgentRepo inside the IsInitialized method, thus it's not using the substitute you created in the test method.
You have to inject the substitute by constructor injection, property injection or method injection.
As the name suggests, constructor injection is when you inject the dependency from the constructor. Since the method IsInitialized is static, that's not an option.
Likewise, property injection uses properties to inject the dependencies. You could create a static property, usually you'd stay away from it though.
It'd always use the same instance for every thread, hence you'd have to guarantee that the AgentRepo is thread-safe.
As last resort, you can use the method injection. You'd get the AgentRepo instance as a method argument and let the caller be responsible for creating it.
Since this is a small repro, I can't tell you what's the best way to deal with it. What I do know is that the AgentRepo must be injected into Class1 somehow.
I have a class similar to the following:
public class MyProxy : ClientBase<IService>, IService
{
public MyProxy(String endpointConfiguration) :
base(endpointConfiguration) { }
public int DoSomething(int x)
{
int result = DoSomethingToX(x); //This passes unit testing
int result2 = ((IService)this).DoWork(x)
//do I have to extract this part into a separate method just
//to test it even though it's only a couple of lines?
//Do something on result2
int result3 = result2 ...
return result3;
}
int IService.DoWork(int x)
{
return base.Channel.DoWork(x);
}
}
The problem lies in the fact that when testing I don't know how to mock the result2 item without extracting the part that gets result3 using result2 into a separate method. And, because it is unit testing I don't want to go that deep as to test what result2 comes back as... I'd rather mock the data somehow... like, be able to call the function and replace just that one call.
Do you have a preference for mocking frameworks?
The Partial Mock feature in Rhino Mocks seems like it should do what you want.
You can't really do that. You have three choices:
Subclass MyProxy and override DoWork, which will require some fiddling to please the compiler
Mock the Channel property, which will require that it is settable in the base class
Move DoWork out into another class, pass it the Channel in the constructor, and mock that in your tests
Do the following:
Set up an IService property such as:
public IService MyService { get; set; }
Then you can do: int result2 = MyService.DoWork(x) as long as somewhere in the constructor or whatever you set MyService = this;
If you don't want to expose the property you can make it private or whatever and test it using accessors.
You can do it by using latest Microsoft Research project Moles
Once you get it running, you can do following
MMyProxy.DoWork32 = () => put your mock result here.
Remember to set moleBehavior to fall-through for the unmocked methods.
I believe that you have a design issue here, your IService.DoWork should most likely live in another class, it looks like just a thin wrapper on something else. Have you considered refactoring it?
Then if it lives in another class you don't need any special handling for mocking.
Bear with me, I'm new to NUnit. I come from the land of Rails, so some of this is new to me.
I have a line of code that looks like this:
var code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
I'm trying to mock it, like this (assume code is already initialized):
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
When I debug the test, getCodeByCodeNameAndType is returning null, instead of the expected code. What am I doing wrong?
NUnit version: 2.2.8
I'm sorry, but I've never used NUnit.Mocks - but I do have some experience with NMock and Moq [which, by the way, I highly recommend]. Typically, you use a mocking library to generate proxies for Interface definitions, and I presume NUnit.Mocks operates the same way.
Therefore, if you would like to mock your singleton, you will likely have to do the following,
a. Create an interface, say
// All methods you would like to mock from this class, should
// be members of this interface
public interface IWebSiteConfiguration
{
// Should match signature of method you are mocking
CodeType getCodeByCodeNameAndType (
string codeString,
CatalogType catalogType);
}
b. "Implement" interface
// You've already written the method, interface matches signature,
// should be as easy as slapping interface on class declaration
public class WebSiteConfiguration : IWebSiteConfiguration { }
c. Consume interface
alright, so step c. is where most of your work will be. Logically, if you are mocking your singleton, you are actually unit testing the consumer [which you have left out of your sample]. For c. simply add a parameter to the consumer's ctor, or add a publicly accessible property of Type 'IWebSiteConfiguration', and then internally, reference the instance member and invoke your methods against this new interface. Consider this,
was
public class MyClass
{
public MyClass () { }
public void DoSomething ()
{
// bad singleton! bad boy! static references are bad! you
// can't change them! convenient but bad!
code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType (
"some.string",
someCatalog)
}
}
becomes
public class MyClass
{
private readonly IWebSiteConfiguration _config = null;
// just so you don't break any other code, you can default
// to your static singleton on a default ctor
public MyClass () : this (WebSiteConfiguration.Instance) { }
// new constructor permits you to swap in any implementation
// including your mock!
public MyClass (IWebSiteConfiguration config)
{
_config = config;
}
public void DoSomething ()
{
// huzzah!
code = _config.getCodeByCodeNameAndType ("some.string", someCatalog)
}
}
In your unit test, create the mock, pass a reference of the mock to the consumer, and test the consumer.
[Test]
public void Test ()
{
IWebSiteConfiguration mockConfig = null;
// setup mock instance and expectation via
// NUnit.Mocks, NMock, or Moq
MyClass myClass = new MyClass (mockConfig);
myClass.DoSomething ();
// verify results
}
This also serves as a practical introduction to Dependency Injection [DI]. It's simply the practice of passing, or "injecting", references of services [eg your web site configuration class] to the consumer, rather than having the consumer invoke the service directly [eg via static singleton class].
Hope this helps :)
A DynamicMock creates a new object in-memory that represents the interface, or marshallable (inherits from MarshalByRef) class you want to mock.
Try this:
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
WebSiteConfiguration conf = (WebSiteConfiguration)_websiteConfigurationMock.MockInstance;
var x = conf.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
Note that the third line there will not work unless WebSiteConfiguration inherits from MarshalByRef.
What you typically do is mock an interface and get a new object that implements this interface, but behaves the way you've configured it to do, without having to go and make a concrete type for it, so I'm not entirely sure what you're doing is going to work unless you employ a better isolation framework, like TypeMock that can intercept calls to static methods/properties in existing objects.
Seems there is a kind of solution for this using reflection, or maybe I totally misunderstood this.
It is discussed here:
http://www.geekbeing.com/2010/05/23/how-to-unit-test-singleton-hack-in-c
Could it really works?
public class TestableSingleton : SingletonClass
{
public TestableSingleton ()
{
FieldInfo fieldInfo = typeof(SingletonClass)
.GetField("_instance",
BindingFlags.Static | BindingFlags.NonPublic);
fieldInfo.SetValue(Instance, this);
}
}
Project availabe on https://github.com/rbabreu/TestableSingleton
Actually I could not compile it on Visual Studio since the SingletonClass would have a private constructor. If someone get it to work would be great to avoid the overhead of adapter pattern.