Rhino Mocks, void and properties - c#

Just starting out with Rhino Mocks and im having a very simple problem, how do I mock a class with a void which sets a property?
class SomeClass : ISomeClass
{
private bool _someArg;
public bool SomeProp { get; set; }
public SomeClass(bool someArg)
{
_someArg = someArg;
}
public void SomeMethod()
{
//do some file,wcf, db operation here with _someArg
SomeProp = true/false;
}
}
Obviously this is a very contrived example, Thanks.

In your example you won't need RhinoMocks because you're apparently testing the functionality of the class under test. Simple unit testing will do instead:
[Test]
public void SomeTest()
{
var sc = new SomeClass();
// Instantiate SomeClass as sc object
sc.SomeMethod();
// Call SomeMethod in the sc object.
Assert.That(sc.SomeProp, Is.True );
// Assert that the property is true...
// or change to Is.False if that's what you're after...
}
It's much more interesting to test mocks when you have a class that has dependencies on other classes. In your example you mention:
//do some file, wcf, db operation here with _someArg
I.e. you expect some other class to set SomeClass's property, which makes more sense to mocktest. Example:
public class MyClass {
ISomeClass _sc;
public MyClass(ISomeClass sc) {
_sc = sc;
}
public MyMethod() {
sc.SomeProp = true;
}
}
The required test would go something like this:
[Test]
public void MyMethod_ShouldSetSomeClassPropToTrue()
{
MockRepository mocks = new MockRepository();
ISomeClass someClass = mocks.StrictMock<ISomeClass>();
MyClass classUnderTest = new MyClass(someClass);
someClass.SomeProp = true;
LastCall.IgnoreArguments();
// Expect the property be set with true.
mocks.ReplayAll();
classUndertest.MyMethod();
// Run the method under test.
mocks.VerifyAll();
}

Depends on how much fidelity you'd like in your mock object. The easy way to do it is to not worry about it and write out some dumb expect statements.
[Test]
public void SomeTest()
{
MockRepository mocks = new MockRepository();
ISomeClass mockSomeClass = mocks.StrictMock<ISomeClass>();
using(mocks.Record())
{
using(mocks.Ordered())
{
Expect.Call(MockSomeClass.SomeProp).Return(false);
Expect.Call(delegate{MockSomeClass.SomeMethod();});
Expect.Call(MockSomeClass.SomeProp).Return(true);
}
}
}
If you want something that acts more like the real object without a canned set of ordered responses you'll have to set up delegates with the do method on the expect.
delegate bool propDelegate();
delegate void methodDelegate();
private bool m_MockPropValue = false;
[Test]
public void SomeTest()
{
MockRepository mocks = new MockRepository();
ISomeClass mockSomeClass = mocks.StrictMock<ISomeClass>();
using(mocks.Record())
{
SetupResult.For(MockSomeClass.SomeProp).Do(new propDelegate(delegate
{
return this.m_MockPropValue;
}));
Expect.Call(delegate{MockSomeClass.SomeMethod();}).Do(new methodDelegate(delegate
{
this.m_MockPropValue = true;
}));
}
}

When your preparing something with either SetupResult.For or Expect.Call you need to ensure that they are virtual, otherwise RhinoMocks will be unable to make its own implementation.
Otherwise it's just a matter of setting the results and doing expected calls as Scott Pedersen has shown

It's not totally clear from the question what the object you're trying to test is - if you simply want to check that SomeClass.SomeMethod() sets a property then you don't need mocking since you can just do a simple state-based test:
[TestMethod]
public void SomeMethodTest()
{
SomeClass s = new SomeClass();
s.SomeMethod();
Assert.AreEqual(expectedValue, s.SomeProp);
}
Alternatively, if SomeClass is a dependency for some other class, and you want to test the interaction between that class and SomeClass, then you set up the expectation on the method call during the 'Record' section of the test using RhinoMock, like this:
[TestMethod]
public void CheckInteractionWithSomeClass()
{
MockRepository mocks = new MockRepository();
ISomeClass someClass = mocks.StrictMock<ISomeClass>();
using (mocks.Record())
{
//record expection that someClass.SomeMethod will be called...
someClass.SomeMethod();
}
using (mocks.Playback())
{
//setup class under test - ISomeClass is injected through the constructor here...
ClassUnderTest o = new ClassUnderTest(someClass);
o.MethodOnClassUnderTestThatShouldCallSomeClass.SomeMethod();
//any other assertions...
}
}

Related

c# - Assert Expressions

I have an 'Example' class and I would like to create unit test for it. Take a look on my classes below:
public class Example
{
private readonly Calculator _calculator;
public Example(ICalculator calculator)
{
_calculator = calculator;
}
public void Calculate()
{
_calculator.Execute(operation => operation.Subtract());
}
}
public interface IOperation {
void Sum();
void Subtract();
}
public inferface ICalculator {
void Execute(Action<IOperation> action);
}
public class Calculator {
public void Execute(Action<IOperation> action){}
}
What I want is to create a Unit Test class to verify that my method from Example class Calculate calls the _calculator.Execute passing as parameter the operation.Subtract(). Is it possible?
I know how to mock my ICalculator and verify that Execute is being called once, but I have no idea how to validade if Execute method was called using operation.Subtract() as parameter instead of operation.Sum().
I am using NUnit to create my unit tests. Here you can see how my unit test class is at the moment:
[TestFixture]
public class ExampleTests
{
[Test]
public void Test1()
{
var calculator = new Mock<ICalculator>();
var subject = new Example(calculator.Object);
subject.Calculate();
calculator.Verify(x => x.Execute(It.IsAny<Action<IOperation>>()), Times.Once);
}
}
Hope someone can understand my english, sorry about that.
You cannot directly verify what lambda was passed but you can go around it by actually invoking said lambda with yet another mock:
var calculator = new Mock<ICalculator>();
var operation = new Mock<IOperation>();
// when calculator's Execute is called, invoke it's argument (Action<IOperation>)
// with mocked IOperation which will later be verified
calculator
.Setup(c => c.Execute(It.IsAny<Action<IOperation>>()))
.Callback<Action<IOperation>>(args => args(operation.Object));
var example = new Example(calculator.Object);
example.Calculate();
calculator.Verify(c => c.Execute(It.IsAny<Action<IOperation>>()));
operation.Verify(o => o.Subtract());
You're passing anonymous delegate operation => operation.Subtract() to _calculator.Execute - so you cannot construct it later when asserting for argument.
You can get around it by doing this:
public class Example
{
private readonly ICalculator _calculator;
public Example(ICalculator calculator)
{
_calculator = calculator;
}
public Action<IOperation> Subtract = op => op.Subtract();
public Action<IOperation> Add = op => op.Sum();
public void Calculate()
{
_calculator.Execute(Subtract);
}
}
And asserting like this (ommiting 2nd param defaults to Once):
calculator.Verify(x => x.Execute(subject.Subtract));
However this looks like convoluted design in order to be able to write a test.

Testing Factory Pattern

I have the small sample factory pattern implementation below, and was wondering if someone can help me write proper Moq unit test cases, for maximum code coverage:
public class TestClass
{
private readonly IService service;
public TestClass(Iservice service)
{
this.service = service;
}
public void Method(string test)
{
service = TestMethod(test);
service.somemethod();
}
private IService TestMethod(string test)
{
if(test == 'A')
service = new A();
if(test == 'B')
service = new B();
return service;
}
}
I am looking for some help in Testing the TestClass and more importantly TestMethod when i send Mock, for example my test method goes below :
[TestMethod]
public void TestCaseA()
{
Mock<IService> serviceMock = new Mock<Iservice>(MockBehaviour.strict);
TestClass tClass = new TestClass(serviceMock.Object);
// The Question is, what is best approach to test this scenario ?
// If i go with below approach, new A() will override serviceMock
// which i am passing through constructor.
var target = tClass.Method("A");
}
You would not mock the TestClass, because that is what you are testing.
For this to work, you need to make a read-only property for service.
public IService Service { get; private set; }
You need to test the way that both the constructor and Method modify the state(in this case Service) of the TestClass instance.
Your test would look something like the following for testing the Method for the B test case:
[TestMethod]
public void TestSomeMethod()
{
// Arrange/Act
var target = new TestClass((new Mock<IService>()).Object);
target.Method("B");
// Assert
Assert.IsInstanceOfType(target.Service, typeof(B));
}
Your test would look something like the following for testing the constructor for the A test case:
[TestMethod()]
public void TestCasesA()
{
// Arrange/Act
var target = new TestClass("A");
// Assert
Assert.IsInstanceOfType(target.service, typeof(A));
}
I would recommend only using the constructor approach to inject your IService. This allows you to have an immutable object that will reduce the state of your application.

Unit Testing Interactions of methods in the same class in C#

I have the following code
public ClassToTest : IClassToTest
{
private readonly DBRepository rep;
public bool MethodA()
{
//Some logic
var result=MethodB();
//Do some logic against result;
}
public ResultType MethodB()
{
return Rep.GetResult();
}
}
If I want to Unit testing MethodA, what is the best practice to test the interaction between MethodA and MethodB? I am thinking to test MethodA like testing MethodB by mocking Database dependency Rep, just like MethodA has the following implementation
public bool MethodA()
{
//Some logic
var result=Rep.GetResult();
//Do some logic against result;
}
But it is not intuitive by checking the logic in the code and the test method. I am looking for a solution similar to the one mentioned here for Java.
unit testing composite service methods
But It is not working for C#.
One extra question, What if MethodB is private, does it make any difference for the Unit testing strategy?
Update: prefer not to change the structure of the class. like not making MethodB as virtual or Move the MethodB out of the class into another test
Thanks in advance.
You don't want to test the interaction between MethodA and MethodB, you want to test that MethodA will return the expected bool result, given some context.
The fact that MethodA calls MethodB is not germaine to this test; but the fact that Rep.GetResult() will at some point be called is.
As you mentioned, you can mock the dependency Rep, so it won't matter whether MethodB is public or private.
Mock and inject the dependency
Call MethodA
Assert against the result
You want to isolate your methods that you test, that is, you want to mock MethodB while testing MethodA, and vice versa.
Also, there is a testing paradigm to test the contract (or interface) of classes. In this paradigm, you wouldn't worry about non-public non-virtual methods. I tend to mock as much as I can.
I recommend you use a mocking framework (smug, rhino mocks, moq, easymock) Smug being the coolest, but it is not yet complete - I'll just show you the code below (this is how it would work without a mocking framework to help you).
public enum ResultType
{
Ok,
NotOk,
}
public abstract class DBRepository
{
public abstract ResultType GetResult();
}
public class ClassToTest
{
public DBRepository Rep { get; set; }
public virtual bool MethodA()
{
//Some logic
var result = MethodB();
//Do some logic against result;
return result == ResultType.Ok;
}
protected virtual ResultType MethodB()
{
return Rep.GetResult();
}
}
public class DBRepositoryMock : DBRepository
{
public ResultType FakeReturn { get; set; }
public override ResultType GetResult()
{
return FakeReturn;
}
}
public class ClassToTest_MethodA : ClassToTest
{
public ResultType MethodB_FakeReturn { get; set; }
protected override ResultType MethodB()
{
return MethodB_FakeReturn;
}
}
// tests
[TestMethod]
public void Test1()
{
ClassToTest mock = new ClassToTest_MethodA();
(mock as ClassToTest_MethodA).MethodB_FakeReturn = ResultType.Ok;
Assert.IsTrue(mock.MethodA());
}
// or using injection
[TestMethod]
public static void Test2()
{
var obj = new ClassToTest();
obj.Rep = new DBRepositoryMock { FakeReturn = ResultType.NotOk };
Assert.IsFalse(obj.MethodA());
}
[TestMethod]
public void MethodAReturnsTrueGivenSomeDataAndCondition()
{
IDBRepository mockRepo = new Mock<IDBRepository>(); //Create a mock of your repository call
ClassToTest subjectToTest = new ClassToTest(mockRepo.Object); //Inject the dependency
mockRepo.SetUp(r=>r.GetResult()).Returns(someSampleTestData); //You're setting up the object that might return you true to return when mock repo will be called, by default it returns the default or null usually
var result = subjectToTest.MethodA();
mockRepo.Verify(r=>r.GetResult(), Times.Once); //Make sure your repo method was called
Assert.IsTrue(result);
}
Something like this, using Moq as a sample mocking framework.

How to test virtual methods using Moles?

How can I test the IsHappy function using Moles?
class SomeClass
{
protected virtual bool IsHappy(string mood)
{
return (mood == "Happy");
}
}
I tried to test if by using Stub:
SSomeClass stub = new SSomeClass();
stub.CallBase = true;
Assert.IsTrue(stub.IsHappyString("Happy"));
... but the IsHappyString method returns null thus throwing a NullReference exception.
So, how can I test the default implementation of IsHappy method?
I'd forget about stubs here. Stubs/mocks are for when you want to fake the behavior of a dependency. You'd stub your SomeClass if had SomeClassClient that you wanted to test and it used SomeClass:
public class Foo
{
public virtual int GetFoosInt()
{
return 12;
}
}
public class FooClient
{
private Foo _foo;
public FooClient(Foo foo)
{
_foo = foo;
}
public int AddOneToFoosInt()
{
return _foo.GetFoosInt() + 1;
}
}
In this example, when testing FooClient, what you want to test is that it returns one more than "GetFoosInt()". You don't actually care what FoosInt is for testing the FooClient. So, you create a Foo stub where you can setup GetFoosInt to return whatever you want.
In your case, testing a protected virtual member, I'd go with this:
[TestClass]
public class SomeClassTest
{
private class DummySomeClass : SomeClass
{
public bool IsHappyWrapper(string mood)
{
return IsHappy(mood);
}
}
[TestMethod]
public void SomeTest()
{
var myClass = new DummySomeClass();
Assert.IsTrue(myClass.IsHappyWrapper("Happy"));
}
}
This gives you 'direct' access to the protected virtual to test default behavior. Only word of caution is that if you start defining abstract members and adding to SomeClass in general, you'll have to add them to this dummy inheritor as well, adding to testing maintenance overhead.
The purist in me says that you should leave protected members alone and only test them through the public interface. But, that may or may not be practical in your situation, and I don't really see any harm in this approach.
Stubs and Moles are for isolating a class from any dependencies it has, either environmental dependencies or class dependencies. This class has no dependencies whatsoever, so why are you trying to mole or stub it?
If you want to make sure this base class works properly when people override it, then you'll need to create a test implementation. In that case this is more or less what your test cases should look like:
public SomeClassTestAdapter : SomeClass
{
public bool GetIsHappy(string mood)
{
return IsHappy(mood);
}
}
[Test]
public void ShouldReturnTrueWhenPassedHappy()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy("Happy");
Assert.IsTrue(result, "Expected result to be true");
}
[Test]
public void ShouldReturnFalseWhenPassedLowerCaseHappy()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy("happy");
Assert.IsFalse(result, "Expected result to be false");
}
[Test]
public void ShouldReturnFalseWhenPassedNull()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy(null);
Assert.IsFalse(result, "Expected result to be false");
}
Etc.
There is no place in this code that stubs or moles should be squeezed in.
If you don't want to create an adapter class for this case, you can use built-in .Net features rather than a big, paid dependency like Moles. Reflections and dynamic let you get access to protected or private members. See this example:
http://igoro.com/archive/use-c-dynamic-typing-to-conveniently-access-internals-of-an-object/

Moq a MEF Import?

I have a class A which has the following:
public class A {
[Import(typeof(IMyService)]
public IMyService MyService { get; set; }
public A() {
CompositionInitializer.SatisfyImports(this);
}
public void DoWork() {
//Blah
MyService.DoIt();
//Blah
}
}
And a Test to test this (seperate Dll - obviously)
[TestMethod]
public void TestDoWork() {
//Blah
DoWork();
//Assert assert
}
This fails as attempting to call 'MyService' gives me null.
I've then tried:
[ClassInitialize]
public void InitialiseClass() {
var myService = new Mock<IMyService>();
MyService = myService.Object;
}
with 'MyService' declared as:
[Export(typeof(IMyService))]
public IMyService MyService { get; set; }
But still no joy, am I missing something - is this even possible?
I'm using SL3, MEF Preview 9 and MOQ.
Any help appreciated!
Cheers
Chris
Your class should look like this:
public class A
{
private readonly IMyService _myService;
[ImportingConstructor]
public A(IMyService myService)
{
_myService = myService;
}
public void DoWork() {
//Blah
_myService.DoIt();
//Blah
}
}
And your test should look like this:
[TestMethod]
public void DoWork_invokes_IMyService_DoIt()
{
// arrange mock and system under test
var myService = new Mock<IMyService>();
var a = new A(myService.Object);
// act
a.DoWork();
// assert that DoIt() was invoked
myService.Verify(x => x.DoIt());
}
The fact that you use MEF should not be important in unit tests. MEF only comes into play when wiring many components together, which is exactly the opposite of what happens in a unit test. A unit test is by definition a test of a component in isolation.
Edit: if you prefer property injection, then your class doesn't need a constructor and the arrange part in your unit test should look like this instead:
var myService = new Mock<IMyService>();
var a = new A();
a.MyService = myService.Object;
Where you've added [Export] to your IMyService instance, have you actually added that to the composition container? If not, it won't take part in composition. To add a mocked object to the container, do the following:
container.ComposeExportedValue<IMyService>(mock.Object);
Or just:
container.ComposeExportedValue(mock.Object); // type inference.
Doing this before you've created an instance of A will enable it to be composed inside your A instance.
You shouldn't be firing up MEF in your unit tests. Composition is way beyond unit test's scope, not dissimilar to an IoC container.
Insted, you should inject required dependencies manually:
[TestClass]
public class ATest {
Mock<IMyService> myService ;
[TestInitialize]
public void InitialiseClass() {
myService = new Mock<IMyService>();
}
[TestMethod]
public void DoWorkShouldCallDoIt {
A a = new A();
a.MyService = myService.Object;
a.DoWork();
myService.Verify(m=>m.DoIt(), Times.Once());
}
}

Categories

Resources