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.)
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 have two methods like below.
public bool IsSuccess()
{
// Some logi
}
public bool ShouldSendLogic()
{
var status = IsSuccess();
if(status)
{
SendInvoice();
// do some operation
}
return status;
}
Now I am writing integration/unit tests. I can call the ShouldSendLogic but I want to ensure SendInvoice is not called by setting the Success as false. (Just for negative case). How to write test case for this scenario, please help me with a code for this.
You can change the ShouldSendLogic() to accept status as parameter bool ShouldSendLogic(bool status). In this way, ShouldSendLogic can be tested for positive and negative cases.
Another approach is to have IsSuccess() part of an interface and inject the dependency to the class that has ShouldSendLogic(). The IsSuccess() result can be modified by mockup classes in unit test environment and ShouldSendLogic() can be tested for different status values.
class MyClass
{
ISomeInterface _interfaceObj;
public MyClass(ISomeInterface interfaceObj)
{
_interfaceObj = interfaceObj;
}
public bool ShouldSendLogic()
{
var status = _interfaceObj.IsSuccess();
if (status)
{
SendInvoice();
// do some operation
}
return status;
}
}
Edit
By separating the code that checks for success to an interface, you can now create a "mock" object in your unit tests, where YOU can decide what the value of IsSuccess() should be.
e.g.
public class MockSuccessClass : ISomeInterface
{
public bool IsSuccess { return true; }
}
And then in your "Arrange" section of your unit test, you can create an instance of the MockSuccessClass and pass it to the SUT.
You don't have to use Moq, but it would save time if you let Moq create your Mock classes for you.
I want to write a nunit test to test a method but I am not able to mock an object instantiated inside that method.
Here is the code:
public class Converter()
{
public void modifyScore(string convertTo){
ScoreConverter scoreConverter;
if(convertTo.Equals("decimal"){
scoreConverter = new DecimalScoreConverter();
scoreConverter.determineScore();
}
else{
scoreConverter = new IntegerScoreConverter();
scoreConverter.determineScore();
}
}
I want to write a test for modifyScore and want to test which object's method has called.
How can I test this method using nunit?
First of all you should start working against abstractions.
I think this is needed for all mock frameworks.
From the info you gave me, and a couple of assumptions:
Anyway, here we go:
public Interface IConverter
{
IScoreConverter ScoreConverter { get; set; };//use constructorinjection instead
void ModifyScore(string convertTo);
}
public Interface IScoreConverter
{
DetermineScore();
}
I would recommend taking a look at MoQ.
You need to figure out what you want to be returned by the inner object.
For now you don't return any value from ModifyScore, so you have nothing to test.
If you would return e.g. a string, the test could look like this:
var scoreConverterResponse = "theStringYouWantToBeReturned"
var scoreConverterMock = new Mock<IScoreConverter>();
scoreConverterMock.Setup(sc => sc.DetermineScore())
.Returns(scoreConverterResponse);
scoreConverterMock.Verify(sc => sc.DetermineScore(It.IsAny<string>()), Times.AtLeastOnce());
I fixed the naming conventions toom i.e. CamelCase methods.
I wrote this on the fly, so I apologise if there are compile errors.
Unit tests are mostly based on state change. So, the natural course is to:
Do something on a class
Test whether the state of the class changed as expected
Maybe you can consider a change in your code to test the type of scoreConverter:
public class Converter
{
public ScoreConverter scoreConverter { get; set; }
public void modifyScore(string convertTo){
if(convertTo.Equals("decimal"){
scoreConverter = new DecimalScoreConverter();
}
else{
scoreConverter = new IntegerScoreConverter();
}
scoreConverter.determineScore();
}
Your test can then execute the modifyScore() method, and then Assert the type of scoreConverter variable.
If you don't want to make the property public, another option is to make it internal and then add the InternalsVisibleToAttribute, or maybe to use a Factory class and then mock it in the test, as amcdermott pointed out.
Greetings!
Scratching my head how to do this.
Suppose I had a concrete class Foo with 2 virtual methods, Execute() and GetFile(). Execute() will call GetFile. I want to make sure that when it does, GetFile() will throw a couple of different exceptions that Foo is supposed to handle gracefully in a testable manner.
For my unit tests, I am envisioning instantiating a DynamicProxy<Foo> from castle project where I intercept the GetFile() to throw the exception, and then invoke the DynamicProxy object's Execute() method, and test the results, but I can't see how to do this.
Is this possible/ practical? If so, what would the creation of the dynamic proxy object look like?
You don't need to handcode your own proxy because most the mocking frameworks support your scenario.
Here is an example using Moq (Moq will create a dynamic proxy internally for you):
public class SomeException : Exception { }
public class Foo
{
public virtual int Execute()
{
try
{
GetFiles();
}
catch (SomeException)
{
return 1;
}
return 0;
}
public virtual void GetFiles()
{
//...
}
}
[Test]
public void FooTest()
{
var fooUnderTest = new Mock<Foo>();
fooUnderTest.CallBase = true;
fooUnderTest.Setup(f => f.GetFiles()).Throws(new SomeException());
var result = fooUnderTest.Object.Execute();
Assert.AreEqual(1, result);
}
You just need to take care to set Callbase = true which will:
Invoke base class implementation if no expectation overrides the
member (a.k.a. "Partial Mocks" in Rhino Mocks): default is false.
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.