How to use moq to test code that calls protected helpers - c#

I currently run tests that look like the following:
// In Blah.cs
public class ClassUnderTest
{
public bool MethodUnderTest()
{
// Do a bunch of stuff...
return HelperMethod();
}
protected virtual bool HelperMethod()
{
bool success = false;
// Proprietary Hardware Access.
// Database Calls.
// File System Modifications.
return success;
}
}
// In TestBlah.cs
public class TestStub : ClassUnderTest
{
public bool HelperMethodReturnValue;
protected override bool HelperMethod()
{
return HelperMethodReturnValue;
}
}
[TestClass]
public class TestingClass
{
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsTrue()
{
var stub = new TestStub();
stub.HelperMethodReturnValue = true;
Assert.IsTrue(stub.MethodUnderTest());
}
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsFalse()
{
var stub = new TestStub();
stub.HelperMethodReturnValue = false;
Assert.IsFalse(stub.MethodUnderTest());
}
}
The above looks fine for simple things, however the stub class gets exponentially bigger and more complex quickly.
I'd like to replace the stub class using Moq. However this won't compile because for some reason I can't set a return value on a protected method.
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsFalse()
{
var mockClass = new Mock<ClassUnderTest>();
mockClass.Protected().Setup("HelperMethod").Returns(false);
Assert.IsFalse(mockClass.Object.MethodUnderTest());
}
Anyone know how I'd go about doing this? Can I do this with moq?

Looking at the moq source code I'd guess you need to explicitly call the generic version of Setup. The non-generic version seems to be used for void methods. So try
mockClass.Protected().Setup<bool>("HelperMethod").Returns(false);
Beside this, I'd recommend re-thinking your class design. If HelperMethod() is doing such a bunch of things it would be worth its own class that is injected as a dependency into ClassUnderTest. Testing a mock object, instead of using a mock object to test something "real", is not what mocking frameworks are made for (not in the first place, at least).

Protected methods are not a great way of isolating dependencies, but it does sometimes come up, particularly when adapting legacy code for testability. One option that avoids the awkward string-based Moq syntax is to make the method 'protected internal' (or just 'internal' if you don't intend to override it in normal usage from other assemblies.) You then use InternalsVisibleTo on the assembly to expose the method. This is a bit of a hack, but using a protected method for this purpose is already a bit of a hack. In some ways I prefer the 'internal' approach, as it makes it clear that this is a backdoor method that you're not supposed to use (except for testing), as opposed to a protected method that you might expect to override in normal usage.

Related

How to Mock Base Class Property or Method in C#

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.)

Unit testing extension methods, had a go, is this right, or gone around the houses?

I have my POCO library and i have entities that implement an interface called IEntityDelete.
Interface is very simple, looks something like this
public interface IEntityDelete
{
bool IsDeleted { get; set; }
}
So i have an entity that implements this interface, again very simple, looks something like this
public class MyEntity() : IEntityDelete
{
public bool IsDeleted { get; set; }
}
I have an extension method, which i created this like
public static void MarkAsDeleted(this IEntityDelete entity)
{
entity.IsDeleted = true;
}
Then i needed to check if this method was being called within one of my service methods in my unit tests. Service method is very basic, looks something like this.
public Task<int> DeleteByFlagAsync(MyEntity entity)
{
entity.MarkAsDeleted();
return _context.SaveChangesAsync();
}
Apparently you cannot test extension methods easily, without using Microsofts Moles framework, but i do not want another dependency.
I did some googl'ing and found 2 articles on this, and how to do about it, and would like to know if this is correct, or whether i have done something stupid.
Two articles i found where
http://adventuresdotnet.blogspot.co.uk/2011/03/mocking-static-methods-for-unit-testing.html
http://blogs.clariusconsulting.net/kzu/how-to-mock-extension-methods/
They recommend using a wrapper class which aint static, so i ended up with this.
First created my wrapper interface
public interface IEntityDeleteWrapper
{
void MarkAsDeleted(IEntityDelete entity);
}
Create a class that implements this interface
public class EntityDeleteWrapper : IEntityDeleteWrapper
{
public void MarkAsDeleted(IEntityDelete entity)
{
entity.IsDeleted = true;
entity.DeletedDate = DateTime.Now;
entity.DeletedByUserId = 546372819;
}
}
Inject this interface into my service constructor
public MyService(IEntityDeleteWrapper deleteWrapper)
{
_deleteWrapper = deleteWrapper;
}
Change my service method call to use the wrapper like so
public Task<int> DeleteByFlagAsync(MyEntity entity)
{
_deleteWrapper.MarkAsDeleted(entity);
return _context.SaveChangesAsync();
}
SOLVED
As i was told, this was way too far to go, i can just check if a property has changed. In light of this, i am using my extension method still and updated my unit test to this.
[TestMethod]
public void should_mark_entity_as_deleted()
{
// arrange
var entity = new Attachment
{
IsDeleted = false
};
// act
var result = _service.DeleteByFlagAsync(entity).Result;
// assert
Assert.AreEqual(true, entity.IsDeleted);
_context.Verify(e => e.SaveChangesAsync(), Times.Once);
}
You went too far. Your test should verify observable change to state, not how that change was made. Otherwise you make your tests very brittle, not to mention you add rather unnecessary extra layer. It would be enough to check whether entity properties changed after DeleteByFlagAsync call.
Of course, when deleting gets more complex introducing dependency to delegate this task to makes sense. But then, few questions arise:
What would be the scope of DeleteByFlagAsync? Call two dependencies?
Would it be practical to test it?
...or perhaps tests for said dependency would suffice (as this is where the actual mark-for-deletion will take place)?

c# unit testing with fakes: when and how to setup/dispose ShimsContext's idisposable... and if I don't...?

In visual studio 2012+, I am using Shims to allow the testing of legacy code without accessing the database. I am using the MSTest framework.
I am trying to avoid code duplication of setting up the shims multiple times; I have instead set up a helper method (e.g. below, BuildShim()) to do so. The idea is that by having the ShimObject built in the helper method, I can have it available for each of the Test methods in my test class.
In the constructor for the test class, I initialize a _idisposable = ShimsContext.Create() (which actually returns an IDisposable). In the methods, I have try {} and finally { _idisoposable.Close() };
Microsoft explicitly advises (see http://msdn.microsoft.com/en-us/library/hh549176.aspx ) using a ShimContext like this, however:
using (ShimsContext.Create()){
...
}
Questions:
Is it bad that I'm not doing it the Microsoft way? If I do it the Microsoft way, how can I avoid duplicating Shim setup code? Or it okay to put the ShimsContext initialization in the constructor and disposal in the finally {} blocks as long as I know what I'm getting into? (e.g. it might be bad if I were using ShimObject.AllInstances type methods, since I could accidentally affect a property in one place and inadvertently affect it elsewhere.)
Is there anything wrong creating the ShimsContext in the test constructor and disposing the _shimcontextDisposal in the finally block like this instead?
What happens if I don't dispose of ShimsContext? Will my computer blow up, figuratively? (e.g. will the shims never be unloaded and I would start to get weird behavior if I actually run the app?)
Example code below.
[TestClass()]
public class Tests {
//Variable to store ShimsContext idisposable. Note that we're not holding the ShimsContext,
//but rather the IDisposable object returned by the ShimsContext.Create() method
private IDisposable _shimscontextDisposable;
//Test class constructor
public Tests(){
_shimscontextDisposable = ShimsContext.Create();
}
//Test method
[TestMethod()]
public TestMethod1(){
try {
//Call the helper method below to get the shim
ShimObject shim = this.GetShimObject();
DataObject data = shim.Instance;
//... do something in test method 1
}
finally {
_shimscontextDisposable.Dispose();
}
}
//Test method 2
[TestMethod()]
public TestMethod2(){
try {
//Call the helper method below to get the shim
ShimObject shim = this.GetShimObject();
DataObject data = shim.Instance;
//... do something in test method 2
}
finally {
_shimscontextDisposable.Dispose();
}
}
//Reusable method to Build shims across methods, avoid duplicating shim setup
public ShimObject BuildShim(){
ShimObject shim = new ShimObject();
shim.TitleGet = () => { return "title"; };
shim.UrlGet = () => { return new Uri("http://www.google.com"); };
return shim;
}
For MSTest Unit Tests it is best practice not to use a constructor. Instead use the ClassInitialize or TestInitialize attribute methods, followed by the TestCleanup or ClassCleanup attribute methods.
For your case, you would set your IDisposable object in the Initialize and dispose of it in the Cleanup.
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.classinitializeattribute.aspx
namespace TestNamespace
{
[TestClass]
public class DivideClassTest
{
[ClassInitialize]
public static void ClassInit(TestContext context)
{
}
[TestInitialize]
public void Initialize()
{
}
[TestCleanup]
public void Cleanup()
{
}
[ClassCleanup]
public static void ClassCleanup()
{
}
}
}

Moq - mock.Object.MyMethod mocking does not work

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.

TDD can force the creation of "fake" dependencies

I'm using a boilerplate implementation of Model-View-Presenter in an ASP.NET WebForms application. My View has two events of consequence, one that signals that the user has filled out enough fields on the domain model to initiate a duplication check, and the other is a regular Save event. My pseudo code looks like this:
public class ItemNewPresenter : PresenterBase<IItemNewView>
{
public IItemService Service { get; private set; }
public IItemNewView View { get; private set; }
public ItemNewPresenter(IItemService service, IItemNewView view)
{
Service = service;
View = view;
View.OnSave += DoItemSave;
View.OnItemIsDuplicateCheck+= DoItemIsDuplicateCheck;
}
private void DoItemIsDuplicateCheck(object sender, CheckItemDuplicateEventArgs e)
{
CheckForItemDuplication(e.Item);
}
private void CheckForItemDuplication(Item item){
if (Service.IsDuplicateItem(item))
{
View.RedirectWithNotification(BuildItemUrl(item), "This item already exists");
}
}
private void DoItemSave(object sender, SaveItemEventArgs e)
{
DoItemIsDuplicateCheck(this, e.ToItemDuplicateEventArgs());
Service.Save(e.Item);
}
}
Here's my test for ensuring that my presenter behaves properly when OnItemIsDuplicateCheck is raised from the view:
[Test]
public void presenter_checking_for_existing_item_should_call_redirect_if_found()
{
var service = new Mock<IItemService>();
var view = new Mock<IItemNewView>();
var presenter = new ItemNewPresenter (service.Object, view.Object);
var onCheckExistingHandler = view.CreateEventHandler <CheckItemDuplicateEventArgs>();
view.Object.OnExistingDenominatorCheck += onCheckExistingHandler;
var eventArgs = new CheckItemDuplicateEventArgs();
service.Setup(s => s.IsDuplicate(It.Is<CheckItemDuplicateEventArgs>(c => c.Equals(eventArgs)))).Returns(true);
onCheckExistingHandler.Raise(eventArgs);
view.Verify(v => v.RedirectWithNotification(It.IsAny<String>(), It.IsAny<string>()), Times.Once());
service.Verify();
}
For consistency, I would like to have the same duplicate check fired when the View raises the OnSave event. My question is around how I am supposed to write my test when one of the methods I want to verify (CheckForItemDuplication) is declared on the class under test. The alternative to verifying the method invocation on the SUT (bad) would be to write my save test with lots of duplicated code (setup and assertion of all my mocks would be copied from the above test) and it also makes the unit test less focused.
[Test]
public void presenter_saving_item_should_check_for_dupe_and_save_if_not_one() {
//duplicate mocks/setups/asserts from duplicate check fixture
//additional mocks/setups/asserts to test save logic
}
I think TDD would suggest pulling this private method out into a separate class that collaborates with my Presenter and would be injected via DI. But adding another dependency to my Presenter for functionality that doesn't seem worthy of being a freestanding abstraction *and*represents an internal implementation detail of my Presenter seems...well...crazy. Am I way off base here? There must be some design pattern or refactoring I can apply that would avoid the need to turn a private method into a dependency.
What I have done sometimes, when confronted with this dilemma, is to extract the function, make an internal constructor with the object as argument, AND a public constructor without. The public ctor is forwarded to the internal with a new object such as:
public class ClassThatUseInjection
{
private readonly SomeClass _injectedClass;
public ClassThatUseInjection(): this(new SomeClass()) {}
internal ClassThatUseInjection(SomeClass injectedClass)
{
_injectedClass = injectedClass;
}
}
public class SomeClass
{
public object SomeProperty { get; set; }
}
Thus, you can use the empty constructor from outside, and the other constructor for when you want to inject a stubbed argument for testpurposes. As long as the empty constructor only forwards the call without any logic of its own, you can still test it, like it has only one constructor.
I would go with testing the class as is by adding the duplicate setup code. Once that test is passing and you are confident all test cases are covered you can then refactor your test code to remove duplication.
You can move the dependencies (service and view) to private fields, then add a method to create the SUT:
private Mock<IItemService> _service;
private Mock<IItemNewView> _view;
private PresenterBase<IItemNewView> CreateSUT()
{
_service = new Mock<IItemService>();
_view = new Mock<IItemNewView>();
return new ItemNewPresenter (service.Object, view.Object);
}
(I think most people would prefer to initialize the Mock objects in the Setup method.)
Call the CreateSUT from your tests and now there is a little less duplication. Then you may want to add private method(s) for creating the event handler / raising the event as long as it is something that is being done the same or similar in more than one tests case.
Having this CreateSUT method cuts down on the amount of test code that is calling your constructor making it easier in the future if you were to add / remove / change dependencies. If you treat your test code like any other code and use the DRY principle when you see duplication it can result in more explicit, easier to read, maintainable test code. Dealing with very similar setup and test context is a common issue with unit testing and should not always change how the class being tested is/was designed.
I'll be interested if there are better answers, as I encounter this all the time.
The alternative to verifying the method invocation on the SUT (bad) would be to write my save test with lots of duplicated code (setup and assertion of all my mocks would be copied from the above test) and it also makes the unit test less focused.
I'm not sure why you feel it makes the test less focused, but in your shoes I would do exactly what it sounds like you don't want to do--have duplicated setup code to test isolated cases for the SUT. You are testing the external behavior of the SUT with the test you supplied, which seems exactly right to me.
I am personally not a fan of exposing more than is necessary from a class and/or making behavior that should be the responsibility of the SUT into a dependency just to facilitate testing. The "natural boundry" of the class's responsibility should not be violated just because you want to test it.
It is easier to unit-test the calculation of the url than to unit-test that redirection has occured.
If i understood you corretly you want to test that the mvp-s CheckForItemDuplication() redirects to a certain url by raising
the view-mock-s OnItemIsDuplicateCheck event.
private void CheckForItemDuplication(Item item)
{
if (Service.IsDuplicateItem(item))
{
View.RedirectWithNotification(BuildItemUrl(item),
"This item already exists");
}
}
In my opinion you are doing to much.
What if you rewrite your code as
internal protected GetErrorUrlForItem(Item item)
{
if (Service.IsDuplicateItem(item))
{
return BuildItemUrl(item,
"This item already exists");
}
return null;
}
private void CheckForItemDuplication(Item item)
{
var result = GetErrorUrlForItem(item);
if (result != null)
{
View.RedirectWithNotification(result);
}
}
In the unittest just test the internal method GetErrorUrlForItem(). You have to use the InternalsVisibleTo attribute to allow accessing the internal method.

Categories