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/
Related
I have a base class:
public abstract class MyBaseClass
{
protected virtual void Method1()
{
}
}
and a derived class:
public class MyDerivedClass : MyBaseClass
{
public void Method2()
{
base.Method1();
}
}
I want to write a unit test for Method2 to verify that it calls Method1 on the base class. I'm using Moq as my mocking library. Is this possible?
I came across a related SO link:
Mocking a base class method call with Moq
in which the 2nd answer suggests it can be achieved by setting CallBase property to true on the mock object. However it's not clear how this would enable the call to the base class method (Method1 in the above example) to be verified.
Appreciate any assistance with this.
Unit tests should verify behavior, not implementation. There are several reasons for this:
The results are the goal, not how you get the results
Testing results allows you to improve the implementation without re-writing your tests
Implementations are harder to mock
You might be able to put in hooks or create mocks that verify that the base method was called, but do you really care how the answer was achieved, or do you care that the answer is right?
If the particular implementation you require has side effects that you can verify, then that is what you should be validating.
Mocking the base class from the perspective of the derived class is not possible. In your simple example, I would suggest one of the two options.
Option 1: In the event that MyDerivedClass really shouldn't care what MyBaseClass is up to, then use dependency injection! Yay abstraction!
public class MyClass
{
private readonly IUsedToBeBaseClass myDependency;
public MyClass(IUsedToBeBaseClass myDependency){
_myDependency = myDependency;
}
public void Method2()
{
_myDependency.Method1();
}
}
Elsewhere in test land...
[TestClass]
public class TestMyDependency {
[TestMethod]
public void TestThatMyDependencyIsCalled() {
var dependency = new Mock<IUsedToBeBaseClass>();
var unitUnderTest = new MyClass(dependency.Object);
var unitUnderTest.Method2();
dependency.Verify(x => x.Method1(), Times.Once);
}
}
Option 2: In the event that MyDerivedClass NEEDS to know what MyBaseClass is doing, then test that MyBaseClass is doing the right thing.
In alternative test land...
[TestClass]
public class TestMyDependency {
[TestMethod]
public void TestThatMyDependencyIsCalled() {
var unitUnderTest = new MyDerivedClass();
var unitUnderTest.Method2();
/* verify base class behavior #1 inside Method1() */
/* verify base class behavior #2 inside Method1() */
/* ... */
}
}
What you're describing is not a test of your code, but a test of the behavior of the language. That's fine, because it's a good way to ensure that the language behaves the way we think it does. I used to write lots of little console apps when I was learning. I wish I'd known about unit testing then because it's a better way to go about it.
But once you've tested it and confirmed that the language behaves the way you expect, I wouldn't keep writing tests for that. You can just test the behavior of your code.
Here's a real simple example:
public class TheBaseClass
{
public readonly List<string> Output = new List<string>();
public virtual void WriteToOutput()
{
Output.Add("TheBaseClass");
}
}
public class TheDerivedClass : TheBaseClass
{
public override void WriteToOutput()
{
Output.Add("TheDerivedClass");
base.WriteToOutput();
}
}
Unit test
[TestMethod]
public void EnsureDerivedClassCallsBaseClass()
{
var testSubject = new TheDerivedClass();
testSubject.WriteToOutput();
Assert.IsTrue(testSubject.Output.Contains("TheBaseClass"));
}
I'm new to NSubstitue (and quite new to unit testing in .NET at all). I want to test if my class saves all data in different files for each entry in e.g. StringDictionary.
Say I have my class DataManipulation.cs:
using System;
using System.Collections;
using System.Collections.Specialized;
namespace ApplicationName
{
// interface for NSubstitute
public interface IManipulator
{
void saveAllData();
void saveEntry(string entryKey, string entryValue);
}
public class DataManipulator : IManipulator
{
protected StringDictionary _data {get; private set;}
public DataManipulator()
{
_data = new StringDictionary();
}
public void addData(string name, string data)
{
this._data.Add(name, data);
}
public void saveAllData()
{
// potential implementation - I want to test this
foreach (DictionaryEntry entry in this._data)
{
this.saveEntry(entry.Key.ToString(), entry.Value.ToString());
}
}
public void saveEntry(string entryKey, string entryValue)
{
// interact with filesystem, save each entry in its own file
}
}
}
What I want to test: when I call DataManipulator.saveAllData() it saves each _data entry in a separate file - meaning it runs saveEntry number of times that equals to _data.Count. Is it possible with NSubstitute?
Each time I try to use DataManipulation as tested object and separately as a mock - when I run Received() I have info that no calls were made.
NUnit test template I want to use:
using System;
using System.Collections.Generic;
using NUnit.Framework;
using NSubstitute;
namespace ApplicationName.UnitTests
{
[TestFixture]
class DataManipulatorTests
{
[Test]
public void saveAllData_CallsSaveEntry_ForEachData()
{
DataManipulator dm = new DataManipulator();
dm.addData("abc", "abc");
dm.addData("def", "def");
dm.addData("ghi", "ghi");
dm.saveAllData();
// how to assert if it called DataManipulator.saveEntry() three times?
}
}
}
Or should I do it in different way?
According to some OOP principles and testing needs you have to introduce a dependency or some construction to create "seam" which will fit good for testing.
Using of another dependency as a mock
It will encapsulate data storage and you will check your assertions against it. I recommend you to read about what's the difference between fake, stub and mock.
Add new storage interface and implementation.
public interface IDataStorage
{
void Store(string key, string value);
}
public class DataStorage : IDataStorage
{
public void Store(string key, string value)
{
//some usefull logic
}
}
Use it as dependency (and inject via constructor) in your Manipulator implementation
public class DataManipulator : IManipulator
{
protected IDataStorage _storage { get; private set; }
protected StringDictionary _data { get; private set; }
public DataManipulator(IDataStorage storage)
{
_storage = storage;
_data = new StringDictionary();
}
public void addData(string name, string data)
{
this._data.Add(name, data);
}
public void saveAllData()
{
// potential implementation - I want to test this
foreach (DictionaryEntry entry in this._data)
{
this.saveEntry(entry.Key.ToString(), entry.Value.ToString());
}
}
public void saveEntry(string entryKey, string entryValue)
{
_storage.Store(entryKey, entryValue);
}
}
Test it
[Test]
public void saveAllData_CallsSaveEntry_ForEachData()
{
var dataStorageMock = Substitute.For<IDataStorage>();
DataManipulator dm = new DataManipulator(dataStorageMock);
dm.addData("abc", "abc");
dm.addData("def", "def");
dm.addData("ghi", "ghi");
dm.saveAllData();
dataStorageMock.Received().Store("abc", "abc");
dataStorageMock.Received().Store("def", "def");
dataStorageMock.Received().Store("ghi", "ghi");
//or
dataStorageMock.Received(3).Store(Arg.Any<string>(), Arg.Any<string>());
}
Most important here that you have not to test private method call. It's a bad practice! Unit testing is all about of testing of public contract, not private methods, which are more changeable in time. (Sorry, I miss that saveEntry(..) is public)
Using of DataManipulator as a mock
I think it's not a good idea, but... The only way to do that with NSubstitute is to make method saveEntry virtual:
public virtual void saveEntry(string entryKey, string entryValue)
{
//something useful
}
and test it:
[Test]
public void saveAllData_CallsSaveEntry_ForEachData()
{
var dm = Substitute.For<DataManipulator>();
dm.addData("abc", "abc");
dm.addData("def", "def");
dm.addData("ghi", "ghi");
dm.saveAllData();
dm.Received(3).saveEntry(Arg.Any<string>(), Arg.Any<string>());
}
The need to do some method virtual just for testing needs may be not very attractive but..
As soon as your tests are also the clients of your business logic, one can take it.
It is possible to use some "heavy" testing frameworks like MS Fakes in this certain case, but it seems to be an overkill.
Another solution is to test another unit of work, which covers depicted one (and probably looks like my first solution).
UPD: read it http://nsubstitute.github.io/help/partial-subs/ for better understanding of NSubstitute.
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.
I have a registry class like this:
public class StructureMapRegistry : Registry
{
public StructureMapRegistry()
{
For<IDateTimeProvider>().Singleton().Use<DateTimeProviderReturningDateTimeNow>();
}
I want to test that the configuration is according to my intent, so i start writing a test:
public class WhenConfiguringIOCContainer : Scenario
{
private TfsTimeMachine.Domain.StructureMapRegistry registry;
private Container container;
protected override void Given()
{
registry = new TfsTimeMachine.Domain.StructureMapRegistry();
container = new Container();
}
protected override void When()
{
container.Configure(i => i.AddRegistry(registry));
}
[Then]
public void DateTimeProviderIsRegisteredAsSingleton()
{
// I want to say "verify that the container contains the expected type and that the expected type
// is registered as a singleton
}
}
How can verify that the registry is accoring to my expectations? Note: I introduced the container because I didn't see any sort of verification methods available on the Registry class. Idealy, I want to test on the registry class directly.
Think of a Registry class like a config file - it doesn't really make sense to test it in isolation, but you might want to test how another class responds to it. In this case, you would test how a Container behaves when given a registry, so you were on the right track by introducing the Container to your test.
In your test, you can request an IDateTimeProvider and assert that the concrete type returned is the type you expect. You can also retrieve 2 instances from the container and assert that they are the same instance (ReferenceEquals) to verify the singleton behavior.
Within StructureMap a registry is used to generate a PluginGraph; so to unit test a registry you need to check that it's design produces the correct graph. Unfortunately test verification is best done against an internal property, here's a sample:
public interface IFoo {}
public class SomeFoo : IFoo {}
public class FooRegistry : Registry
{
public FooRegistry()
{
For<IFoo>().Use<SomeFoo>();
}
}
[TestFixture]
public class FooRegistryTests
{
[Test]
public void ForIFoo_UseSomeFoo_AsDefaultInstance()
{
// Arrange
var registry = new FooRegistry();
// Act
var pluginGraph = registry.Build();
var iFooPluginFamily = pluginGraph.FindFamily(typeof(IFoo));
var defaultInstance = iFooPluginFamily.GetDefaultInstance();
// Assert
Assert.IsTrue(defaultInstance.UsesConcreteType<SomeFoo>());
}
}
public static class TestExtensions
{
public static bool UsesConcreteType<T>(this Instance instance)
{
var concreteTypeProperty = typeof (Instance).GetProperty("ConcreteType", BindingFlags.Instance | BindingFlags.NonPublic);
if (concreteTypeProperty == null || concreteTypeProperty.PropertyType != typeof(Type))
{
Assert.Inconclusive("Unable to locate the internal StructureMap.Instance.ConcreteType property");
}
var propertyValue = concreteTypeProperty.GetValue(instance, new object[] {}) as Type;
return typeof (T) == propertyValue;
}
}
Testing against an internal property is never desirable, but in the case of testing registry's it's been the best approach I've found. The extension method tries to be just smart enough to be able to make tests which rely on it inconclusive if the internal API changes.
Check this interesting atircle http://lostechies.com/jimmybogard/2010/01/22/advanced-structuremap-diagnosing-problems/ for example :
[Test]
public void Should_connect_delete_handler_by_registry()
{
var container = new Container(new HandlerRegistry());
var handler = container.GetInstance<IHandler<DeleteEntityCommand<Customer>>>();
handler.ShouldBeInstanceOf<DeleteEntityCommandHandler<Customer>>();
}
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...
}
}