Rhino Mock using an expect on 'new' method call - c#

Is it possible to do some form of expect NEW in rhino mock.
Example:
public void ToBeTested()
{
ClassForExmaple classForExample = new ClassForExample();
//Other logic.....
}
So I want my unit test to call ToBeTested(), but when the new ClassForExample is called I want it to return a mocked version.

I have not worked with Rhino mock and I am not sure if this is something that is supported by RhinoMock but the fact that the control of creation of the object is embedded within the method violates the principles of DI/IOC and thus is harder to test.. Ideally the class should have been injected to the method either through the constructor of the containing class or to the method itself..
thus
class A
{
IClassForExample _classForExample;
public A(IClassForExample classForExample)
{
_classForExample=classForExample;
}
public void ToBeTested()
{
var classForExample = _classForExample;
//Other logic.....
}
}
Does RhinoSupport extending a non-abstract/interface class - a question I am not sure but I am sure it can mock the interface.

No, it's not possible, for the same reason you cannot expect static things : it is not called on an instance.
If you want to use a mock for an object that is built within your tested code, you should have something like this :
internal virtual ClassForExample NewClassForExempe()
{
return new ClassForExample();
}
and then mock this method in your test.
Note : I put the method internal assuming you have rhino mocks declared in InternalsVisibleToAttribute of your class. Otherwise you'll have to make it public.

Related

Use moq to ignore a method

I have a method called GetBESummaries which looks like this:
public string GetBESummaries()
{
CheckPermissions();
/* rest of the code */
}
public void CheckPermissions()
{
method1();
method2();
}
I am writing a unit test method using moq and i want my moq to ignore CheckPermissions so that i can avoid mocking the list of method calls from Check Permissions. I wish to prevent the control frm going inside the CheckPermissions method. What is the best way to achieve this?
At a high level, Moq works by overriding implementation for abstract and virtualized members. You would need to break out your permissions logic into either an abstract class or an interface so that it could be overridden. While you're at it, consider giving it a return type so that you can do something with your permissions validation logic outside of the permissions class. Your main class can then require the permissions object in its constructor. For example,
public interface IPermissionsChecker
{
bool UserHasPermissions( // whatever parameters you need );
}
public class PermissionsChecker : IPermissionsChecker
{
public override bool UserHasPermissions( // same params as above)
{
// logic
}
}
Once you're there, mocking it out is very easy. You just build the mock, write the setup logic for how you want it to behave inside of your tests, and feed it into your consuming class. This has the added bonus of improving your encapsulation: if you want to have different methods of confirming permissions, it's simply a matter of submitting a different one to your constructor or calling method!
var myMock = new Mock<IPermissions>();
myMock.Setup( m => m.UseHasPermissions()).Returns(true);
var classUnderTest = new GenericConsumerClass(myMock);

NUnit/Moq: I have mocked a class but real contructor is executed, why?

I have a large legacy WPF project that I'm now trying to get unit tested with NUnit (v. 2.6.3) and Moq (v. 4.2), but I'm having trouble with mocking certain classes. There's one in particular, a control class derived from System.Windows.Forms.Integration.WindowsFormsHost, that's needed all over the project and has a lot of external dependencies, so it's very important to be able to mock it.
Let's call that class Foo, and here's the test case:
[TestFixture,RequiresSTA]
public class TestMainWindowViewModel {
[Test]
public void Test1() {
var mockRepository = new MockRepository(MockBehavior.Loose) { DefaultValue = DefaultValue.Empty };
var mockFoo = mockRepository.Create<Foo>();
var sut = new MainWindowViewModel(mockFoo.Object);
}
}
My problem is that for some weird reason, while evaluating parameter mockFoo.Object in the last line, we go straight inside the constructor of the concrete class Foo! I have confirmed that this really happens with debugger, and also, the test run crashes with an error of not finding the DLL's the concrete implementation depends on.
Any ideas what could be causing this? As far as I understand, there should be NO connection to the concrete implementation here!
Thanks in advance for any advice!
-Seppo
Any ideas what could be causing this? As far as I understand, there should be NO connection to the concrete implementation here!
Moq creates its objects (mocks) by deriving from concrete implementation (your case) or implementing interface (typical, more common case):
// implement interface
var mock1 = new Mock<IService>();
// derive from ServiceImplementation
var mock2 = new Mock<ServiceImplementation>();
This is how underlying mechanisms work -- in order to create mock, Moq will have to dynamically create new type representing that mock, either by implementing interface or deriving from base class. Which means your Foo constructor should and is executed. This is how it works.
Since this is legacy code class (Foo) I suggest wrapping it with new, mockable interface and make your code depend on this interface instead:
interface IFoo
{
void DoFoo();
}
class FooWrapper : IFoo
{
private readonly Foo legacyFoo;
public FooWrapper(Foo legacyFoo)
{
this.legacyFoo = legacyFoo;
}
public void DoFoo()
{
legacyFoo.DoFoo();
}
}
Your new (non-legacy) code should depend on IFoo, not Foo and you'll be good to go.

moq a class that IS derived from the same interface as the one being moq'd

I am new to the whole MOQ movement... which by the way is pretty cool ... and I am mocking all kinds of stuff now..
Anyway, I ran into this scenario and was wondering how to go about mocking it up.
I have an class that implements the interface that I want to mock:
public interface ImyInterface
{
void doit();
}
public abstract class myBase<TChannel> : ICommunicationObject, IDisposable where TChannel : class
{
protected TChannel Channel { get; private set; }
// ICommunicationObject implementation not shown
}
public class myIIntClass : myBase<ImyInterface>, ImyInterface
{
public myIIntClass()
{
}
public void doit()
{
Channel.doit();
}
}
I think my moq test doesn't mock anything... but I am unsure and hoping to get some insight on how to either write it correctly or refactor my class:
Here is my current MOQ test:
MyClass myClass = null;
Mock<ImyInterface> moq = new Mock<ImyInterface>();
moq.Setup(x => x.doit());
myClass = (MyClass)moq.Object;
myClass.doit();
moq.VerifyAll();
Thanks from one moqer to another... :-)
I feel like maybe you're missing the point of mocking here. You mock dependencies that exist in a unit of work you're testing. So, let's say I'm testing doit here in the concrete implementation of MyClass; I want to make sure it works right. Now, let's say that method has a dependency to another class; it calls a method on it that returns a boolean value. What I want to do is mock that class because I want to make sure that MyClass.doit behaves right when it returns true and when it returns false.
See, in the example above, what I've done is ensured that no other dependencies are affecting the code flow of MyClass.doit; I'm forcing MyClass.doit down a very specific path; I want to test that path.
The code you've created literally performs nothing because it just executes the mocked up method.
You don't mock/stub the unit under test. If you are testing the doIt(), you don't mock that, you mock its (or class) dependencies.

Rhino Mocks Partial Mock

I am trying to test the logic from some existing classes. It is not possible to re-factor the classes at present as they are very complex and in production.
What I want to do is create a mock object and test a method that internally calls another method that is very hard to mock.
So I want to just set a behaviour for the secondary method call.
But when I setup the behaviour for the method, the code of the method is invoked and fails.
Am I missing something or is this just not possible to test without re-factoring the class?
I have tried all the different mock types (Strick,Stub,Dynamic,Partial ect.) but they all end up calling the method when I try to set up the behaviour.
using System;
using MbUnit.Framework;
using Rhino.Mocks;
namespace MMBusinessObjects.Tests
{
[TestFixture]
public class PartialMockExampleFixture
{
[Test]
public void Simple_Partial_Mock_Test()
{
const string param = "anything";
//setup mocks
MockRepository mocks = new MockRepository();
var mockTestClass = mocks.StrictMock<TestClass>();
//record beahviour *** actualy call into the real method stub ***
Expect.Call(mockTestClass.MethodToMock(param)).Return(true);
//never get to here
mocks.ReplayAll();
//this is what i want to test
Assert.IsTrue(mockTestClass.MethodIWantToTest(param));
}
public class TestClass
{
public bool MethodToMock(string param)
{
//some logic that is very hard to mock
throw new NotImplementedException();
}
public bool MethodIWantToTest(string param)
{
//this method calls the
if( MethodToMock(param) )
{
//some logic i want to test
}
return true;
}
}
}
}
MethodToMock is not virtual and therefore can't be mocked. What you want to do is possible with a partial mock (I've done it in cases similar to yours), but the method you want to mock out must be either part of an interface implementation or be marked virtual. Otherwise, you can't mock it with Rhino.Mocks.
I recommend not mocking methods in the class under test, but your situation may be unique in that you can't refactor the class to make it easier to test at present. You might try explicitly making a delegate to prevent the method from being invoked when setting up the call.
Expect.Call( delegate { mockTestClass.MethodToMock(param) } ).Return(true);
Or, switch to using the AAA syntax, omitting the deprecated constructs.
[Test]
public void Simple_Partial_Mock_Test()
{
const string param = "anything";
var mockTestClass = MockRepository.GenerateMock<TestClass>();
mockTestClass.Expect( m => m.MethodToMock(param) ).Return( true );
//this is what i want to test
Assert.IsTrue(mockTestClass.MethodIWantToTest(param));
mockTestClass.VerifyAllExpectations();
}

How to Mock a Static Singleton?

I have number of classes I've been asked to add some unit tests to with Rhino Mocks and having some issues.
First off, I know RhinoMocks doesn't allow for the mocking of Static members. I'm looking for what options I have (besides using TypeMock).
An example of the class I have is similar to the below:
class Example1 : ISomeInterface
{
private static ISomeInterface _instance;
private Example1()
{
// set properties via private static methods
}
static Example1()
{
_instance = new Example1();
}
public static ISomeInterface Instance()
{
get { return _instance; }
}
// Instance properties
// Other Instance Properties that represent objects that follow a similar pattern.
}
So when I call the above class, it looks something like this...
Example1.Instance.SomeObject.GoDownARabbitHole();
Is there a way for me to mock out the SomeObject.GoDownARabbitHole() in this situation or mock out the Instance?
Discouraged by threads like this, it took me quite some time to notice, that singletons are not that hard to mock. After all why are we using c#?
Just use Reflection.
With provided sample code you need to make sure the static constructor is called before setting the static field to the mocked object. Otherwise it might overwrite your mocked object. Just call anything on the singleton that has no effect before setting up the test.
ISomeInterface unused = Singleton.Instance();
System.Reflection.FieldInfo instance = typeof(Example1).GetField("_instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
Mock<ISomeInterface> mockSingleton = new Mock<ISomeInterface>();
instance.SetValue(null, mockSingleton.Object);
I provided code for mocking with Moq, but I guess Rhino Mocks is quite similar.
Singletons are at odds with Testability because they are so hard to change. You would be much better off using Dependency Injection to inject an ISomeInterface instance into your consuming classes:
public class MyClass
{
private readonly ISomeInterface dependency;
public MyClass(ISomeInterface dependency)
{
if(dependency == null)
{
throw new ArgumentNullException("dependency");
}
this.dependency = dependency;
}
// use this.dependency in other members
}
Notice how the Guard Claus together with the readonly keyword guarantees that the ISomeInterface instance will always be available.
This will allow you to use Rhino Mocks or another dynamic mock library to inject Test Doubles of ISomeInterface into the consuming classes.
Here's a low-touch approach that uses a delegate, which can be set initially and changed at runtime. It's better explained by example (specifically, mocking DateTime.Now):
http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/11/09/systemtime-versus-isystemclock-dependencies-revisited.aspx
Example from Book: Working Effectively with Legacy Code
To run code containing singletons in a test harness, we have to relax the singleton property. Here’s how we do it. The first step is to add a new static method to the singleton class. The method allows us to replace the static instance in the singleton. We’ll call it
setTestingInstance.
public class PermitRepository
{
private static PermitRepository instance = null;
private PermitRepository() {}
public static void setTestingInstance(PermitRepository newInstance)
{
instance = newInstance;
}
public static PermitRepository getInstance()
{
if (instance == null)
{
instance = new PermitRepository();
}
return instance;
}
public Permit findAssociatedPermit(PermitNotice notice)
{
...
}
...
}
Now that we have that setter, we can create a testing instance of a
PermitRepository and set it. We’d like to write code like this in our test setup:
public void setUp() {
PermitRepository repository = new PermitRepository();
...
// add permits to the repository here
...
PermitRepository.setTestingInstance(repository);
}
Check out Dependency Injection.
You've already began this, but for hard to test classes (statics etc...) you can use the adapter design pattern to write a wrapper around this hard to test code. Using the interface of this adapter, you can then test your code in isolation.
For any unit testing advice, and further testing issues check out the Google Testing Blog, specifically Misko's articles.
Instance
You say you are writing tests, so it may be too late, but could you refactor the static to the instance? Or is there a genuine reason why said class should remain a static?
You can mock the interface, ISomeInterface. Then, refactor the code that uses it to use dependency injection to get the reference to the singleton object. I have come across this problem many times in our code and I like this solution the best.
for example:
public class UseTheSingleton
{
private ISomeInterface myX;
public UseTheSingleton(ISomeInterface x)
{
myX = x;
}
public void SomeMethod()
{
myX.
}
}
Then ...
UseTheSingleton useIt = UseTheSingleton(Example1.Instance);
You don't have to fix all the uses at once, just the one you're dealing with now. Add an ISomeInterface field to the class under test and set it through the constructor. If you're using Resharper (you are using Resharper, aren't you?), most of this will be trivial to do. If this is really fiddly, you can have more than one constructor, one which sets the new dependency field, the other which calls the first one with the singleton as a default value.

Categories

Resources