In the following example, I want to test the TestMe.DoSomething() function.
I want to mock the ISomething interface that is used within this method and make it return different values (depending on the specific unit test.)
In real life the ISomething interface winds up calling out to expensive 3rd party resources -- I definitely don't want to just call a real ISomething.
Here is the example structure:
class TestMe
{
public void DoSomething()
{
ISomething s = SomethingFactory();
int i = s.Run();
//do things with i that I want to test
}
private ISomething SomethingFactory()
{
return new Something();
}
}
interface ISomething
{
int Run();
}
class Something : ISomething
{
public int Run()
{
return 1;
}
}
Here is code that doesn't work:
var fakeSomething = new Mock<ISomething>();
var testMe = new TestMe();
Mock.Get(testMe).Setup(p => p.SomethingFactory()).Returns(fakeSomething.Object);
testMe.DoSomething();
Because SomethingFactory() is private, I cannot set the return value from that method to be what I want.
Any advice on how I can solve this?
Make the factory a full interface / class and remove the SomethingFactory method from TestMe.
public interface ISomethingFactory {
ISomething MakeSomething();
}
public sealed class SomethingFactory {
public ISomething MakeSomething() {
return new Something();
}
}
class TestMe
{
private readonly ISomethingFactory _somethingFactory;
public TestMe(ISomethingFactory somethingFactory) {
_somethingFactory = somethingFactory;
}
public void DoSomething()
{
ISomething s = _somethingFactory.MakeSomething();
int i = s.Run();
//do things with i that I want to test
}
}
This will allow you to mock ISomethingFactory to return a mock of ISomething.
While I think you may protest this solution as too drastic a change, I think its better than making a class that's not sealed with a members who's only reason for being virtual is for testing.
You can inject your dependency. If you don't want to break all your callers you can add two constructors and use the one that lets you inject fake in tests
class TestMe
{
private readonly ISomething something;
TestMe() : this(new RealSomething()
{
}
TestMe(ISomething sth)
{
something = sth;
}
public void DoSomething()
{
ISomething s = SomethingFactory();
int i = s.Run();
//do things with i that I want to test
}
private ISomething SomethingFactory()
{
return new Something();
}
}
Second way would be to change the
SomethingFactory
method to protected virtual and override it in derived class and use that class instead, or to setup
class TestableTestMe : TestMe
{
private readonly ISomething something;
TestableTestMe(ISomething testSpecific)
{
something = testSpecific;
}
public void DoSomething()
{
ISomething s = SomethingFactory();
int i = s.Run();
//do things with i that I want to test
}
protected override ISomething SomethingFactory()
{
return something;
}
}
This technique is called "extract and override"
Changing SomethingFactory() to be protected virtual allows you to use Moq.Protected to access the method by its name:
public class TestMe
{
public void DoSomething()
{
ISomething s = SomethingFactory();
int i = s.Run();
//do things with i that I want to test
}
protected virtual ISomething SomethingFactory()
{
return new Something();
}
}
public interface ISomething
{
int Run();
}
public class Something : ISomething
{
public int Run()
{
return 1;
}
}
So you can run this test:
var fakeSomething = new Mock<ISomething>();
fakeSomething.Setup(p => p.Run()).Returns(2);
var testMe = new Mock<TestMe>();
testMe.Protected().Setup<ISomething>("SomethingFactory").Returns(fakeSomething.Object);
testMe.Object.DoSomething();
Related
I have a base class with a protected method that's being called in a public method in the child class I want to test. I'm failing to find a way to moq the base protected method for easier testing in child class.
public class MyBaseClass
{
protected virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
[TestFixture]
public class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var myChildClass = new MyChildClass();
// How do I mock MyMethod used in myBaseClass here?
// var mock = new Mock<MyBaseClass>();
// mock.Protected().Setup<bool>("MyMethod", ItExpr.IsAny<int>()).Returns(false);
// The above mock is correct, but it's in a different instance object than myBaseClass
var result = myChildClass.DoSomething();
Assert.AreEqual(false, result);
}
}
I can't change the classes to have a better architecture and I must do the best I can to implement unit test for DoSomething(), what I did so far is mock and prepare all the data that method uses, but since it's in another class I'd love my MyChildClassTests to not do all that and just limit to test DoSomething().
I've read about partial mocking and a whole lot of other questions and answers and I can't get it to work right.
I appreciate any suggestions!
Edit: Forgot to put public in all the classes, in my real world case, they are public.
class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var myChildClass = new FakeChildClass();
var result = myChildClass.DoSomething(1);
Assert.AreEqual(false, result);
}
}
public class FakeChildClass: MyChildClass
{
protected override bool MyMethod(int number)
{
return number == 1;
}
}
First of all, ensure your classes are public.
Moq will complain about not being able to proxy into them if they're not.
public class MyBaseClass
{
public virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
Next, make your base class method public. You won't be able to set it up unless you do.
After that, create a mock of the child object and mock the parent method.
var mockChild = new Mock<MyChildClass>(){CallBase = true};
mockChild.Setup(x => x.MyMethod(It.IsAny<int>())).Returns(false);
Pull your result.... result will return false even though the actual implementation would have returned true with 1 as a parameter.
var result = mockChild.Object.DoSomething(1);
When calling the DoSomething method, you'll actually enter the real implementation of that (put a breakpoint on if you don't believe me!) - but the mocked version of MyMethod will kick in.
Thanks all for your replies, gathering all I was able to get the actual answer to my use case:
Without changing MyBaseClass and MyChildClass:
public class MyBaseClass
{
protected virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
I was able to mock the protected method and save me a LOT of work and duplicate code (that was in MyBaseClassTests already)
[TestFixture]
public class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var expected = false;
var myChildClass = new Mock<MyChildClass> {CallBase = true};
myChildClass.Protected().Setup<bool>("MyMethod", 1).Returns(expected);
var result = myChildClass.Object.DoSomething(1);
Assert.AreEqual(expected, result);
}
[Test]
public void Expected_Returns_True_WhenPassed_1()
{
var expected = true;
var myChildClass = new Mock<MyChildClass> {CallBase = true};
myChildClass.Protected().Setup<bool>("MyMethod", 1).Returns(expected);
var result = myChildClass.Object.DoSomething(1);
Assert.AreEqual(expected, result);
}
}
Thanks everyone for your help! :)
If we have a class that inherits from multiple interfaces, and the interfaces have methods with the same name, how can we implement these methods in my class? How can we specify which method of which interface is implemented?
By implementing the interface explicitly, like this:
public interface ITest {
void Test();
}
public interface ITest2 {
void Test();
}
public class Dual : ITest, ITest2
{
void ITest.Test() {
Console.WriteLine("ITest.Test");
}
void ITest2.Test() {
Console.WriteLine("ITest2.Test");
}
}
When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type.
var dual = new Dual();
// Call the ITest.Test() function by first assigning to an explicitly typed variable
ITest test = dual;
test.Test();
// Call the ITest2.Test() function by using a type cast.
((ITest2)dual).Test();
You must use explicit interface implementation
You can implement one or both of those interfaces explicitly.
Say that you have these interfaces:
public interface IFoo1
{
void DoStuff();
}
public interface IFoo2
{
void DoStuff();
}
You can implement both like this:
public class Foo : IFoo1, IFoo2
{
void IFoo1.DoStuff() { }
void IFoo2.DoStuff() { }
}
You can implement one interface Explicitly and another implecitely.
public interface ITest {
void Test();
}
public interface ITest2 {
void Test();
}
public class Dual : ITest, ITest2
{
public void Test() {
Console.WriteLine("ITest.Test");
}
void ITest2.Test() {
Console.WriteLine("ITest2.Test");
}
}
ITest.Test will be the default implementation.
Dual dual = new Dual();
dual.Test();
((ITest2)dual).Test();
Output:
Console.WriteLine("ITest.Test");
Console.WriteLine("ITest2.Test");
Sometimes you may even need to do:
public class Foo : IFoo1, IFoo2
{
public void IFoo1.DoStuff() { }
public void IFoo2.DoStuff()
{
((IFoo1)this).DoStuff();
}
}
public class ImplementingClass : AClass1, IClass1, IClass2
{
public override string Method()
{
return "AClass1";
}
string IClass1.Method()
{
return "IClass1";
}
string IClass2.Method()
{
return "IClass2";
}
}
So when calling from different class you will have to type cast the object into required Interface or Abstract class.
ImplementingClass implementingClass = new ImplementingClass();
((AClass1)implementingClass).Method();
public interface IDemo1
{
void Test();
}
public interface IDemo2
{
void Test();
}
public class clsDerived:IDemo1,IDemo2
{
void IDemo1.Test()
{
Console.WriteLine("IDemo1 Test is fine");
}
void IDemo2.Test()
{
Console.WriteLine("IDemo2 Test is fine");
}
}
public void get_methodes()
{
IDemo1 obj1 = new clsDerived();
IDemo2 obj2 = new clsDerived();
obj1.Test();//Methode of 1st Interface
obj2.Test();//Methode of 2st Interface
}
Answer is "By using explicit Interface implementation"
Take one example:
using System;
interface A
{
void Hello();
}
interface B
{
void Hello();
}
class Test : A, B
{
void A.Hello()
{
Console.WriteLine("Hello to all-A");
}
void B.Hello()
{
Console.WriteLine("Hello to all-B");
}
}
public class interfacetest
{
public static void Main()
{
A Obj1 = new Test();
Obj1.Hello();
B Obj2 = new Test();
Obj2.Hello();
}
}
Output:
Hello to all-A
Hello to all-B
Dual dual = new Dual();
(dual as ITest).Test();
(dual as ITest2).Test();
you can use that for your code
I have an abstract class that I want to test. There is an abstract property in this class for my DAO, which I define in inherited classes.
public abstract class DeviceGroupManagerBase<TDeviceGroup> where TDeviceGroup : DeviceGroup
{
protected abstract IDeviceGroupDao<TDeviceGroup> DeviceGroupDao { get; }
public TDeviceGroup UpdateDeviceIndexes(Device device)
{
return DeviceGroupDao.GetDeviceGroup(device.Group.Id);
}
}
I want to test the Updatedeviceindexes method so I'm trying to mock a property called DeviceGroupDao.
[TestFixture]
[Category("Unit")]
public class DeviceGroupManagerBaseTests
{
private IFixture fixture;
private Mock<DeviceGroupManagerBase<DeviceGroup>> subject;
private Mock<IDeviceGroupDao<DeviceGroup>> deviceGroupDaoMock;
private DeviceGroupManagerBase<DeviceGroup> Manager => subject.Object;
[TestFixtureSetUp]
public void Init()
{
fixture = new Fixture().Customize(new AutoMoqCustomization());
deviceGroupDaoMock = fixture.Freeze<Mock<IDeviceGroupDao<DeviceGroup>>>();
subject = fixture.Freeze<Mock<DeviceGroupManagerBase<DeviceGroup>>>();
}
[Test]
public void TestUpdateDeviceIndexes()
{
var device = fixture.Create<Device>();
var deviceGroup = fixture.Create<DeviceGroup>();
deviceGroupDaoMock.Setup(x => x.GetDeviceGroup(It.IsAny<int>())).Returns(deviceGroup);
var result = Manager.UpdateDeviceIndexes(device);
// The resultDeviceGroup will not be contain a previously defined object
Assert.AreEqual(deviceGroup.Id, result.Id);
}
}
I also tried to add registration for my device object in this way:
fixture.Register(() => deviceGroup);
But I'm still getting a new object.
How can I mock IDeviceGroupDao<TDeviceGroup>?
Since DeviceGroupManagerBase is an abstract base class, you'll need a SUT Double. It's easiest to do if you make the DeviceGroupDao property public:
public abstract class DeviceGroupManagerBase<TDeviceGroup> where TDeviceGroup : DeviceGroup
{
public abstract IDeviceGroupDao<TDeviceGroup> DeviceGroupDao { get; }
public TDeviceGroup UpdateDeviceIndexes(Device device)
{
return DeviceGroupDao.GetDeviceGroup(device.Group.Id);
}
}
Otherwise, you'll need to use Moq's API for defining and overriding protected members, which is possible, but more work.
Then you'll need to override subject's DeviceGroupDao property:
subject.SetupGet(x => x.DeviceGroupDao).Returns(deviceGroupDaoMock.Object);
Here's the full test:
[TestFixture]
[Category("Unit")]
public class DeviceGroupManagerBaseTests
{
private IFixture fixture;
private Mock<DeviceGroupManagerBase<DeviceGroup>> subject;
private Mock<IDeviceGroupDao<DeviceGroup>> deviceGroupDaoMock;
private DeviceGroupManagerBase<DeviceGroup> Manager => subject.Object;
[OneTimeSetUp]
public void Init()
{
fixture = new Fixture().Customize(new AutoMoqCustomization());
deviceGroupDaoMock = fixture.Freeze<Mock<IDeviceGroupDao<DeviceGroup>>>();
subject = fixture.Freeze<Mock<DeviceGroupManagerBase<DeviceGroup>>>();
subject.SetupGet(x => x.DeviceGroupDao).Returns(deviceGroupDaoMock.Object);
}
[Test]
public void TestUpdateDeviceIndexes()
{
var device = fixture.Create<Device>();
var deviceGroup = fixture.Create<DeviceGroup>();
deviceGroupDaoMock.Setup(x => x.GetDeviceGroup(It.IsAny<int>())).Returns(deviceGroup);
var result = Manager.UpdateDeviceIndexes(device);
Assert.AreEqual(deviceGroup.Id, result.Id);
}
}
This now passes on my machine.
Because the DeviceGroupDao is protected you will need to find a way to access it externally. Create a stub that would allow you set it value.
public class DeviceGroupManagerBaseStub<TDeviceGroup>
: DeviceGroupManagerBase<TDeviceGroup> where TDeviceGroup : DeviceGroup {
private IDeviceGroupDao<TDeviceGroup> deviceGroupDao;
public DeviceGroupManagerBaseStub(IDeviceGroupDao<TDeviceGroup> deviceGroupDao) {
this.deviceGroupDao = deviceGroupDao;
}
protected override IDeviceGroupDao<TDeviceGroup> DeviceGroupDao {
get {
return deviceGroupDao;
}
}
}
You can then mock IDeviceGroupDao<TDeviceGroup> and inject it into the stub for your test.
Is there a way to force the override of a virtual method if another method is overriden?
public class BaseClass
{
protected virtual void A()
{
// a default action called first
}
protected virtual void B()
{
// a default action called second that,
// if A was overriden, makes no sense
}
}
EDIT
Thanks a lot for the Answers. It's very interresting to see how this could be achieved, but for my explicit case it's not critically important.
Also, i forgot to mention how those Methods would be used: (in BaseClass)
pulbic bool EditEntity(Guid id)
{
A();
// Some code that edits Entites
B();
}
No, you cannot. But this makes me think how could you achieve the same concept?
The best idea I came up with was declaring an interface which had the package of methods to override.
public interface IMyOverridablePackage
{
void A_Override();
void B_Override();
}
Then give the base class a protected method where the child class can explicitly override the set of methods.
protected void SetOverride(IMyOverridablePackage overridablePackage)
{
_overridablePackage = overridablePackage;
}
So then here's two classes, one which does and one which does not override the set of methods:
public class NotOverriding : MyBaseClass
{
}
public sealed class Overriding : MyBaseClass, IMyOverridablePackage
{
public Overriding()
{
SetOverride(this);
}
void IMyOverridablePackage.A_Override()
{
Console.WriteLine("Overriding.A_Override");
}
void IMyOverridablePackage.B_Override()
{
Console.WriteLine("Overriding.B_Override");
}
}
And the implementation of the base class:
public abstract class MyBaseClass
{
private IMyOverridablePackage _overridablePackage;
public void A()
{
_overridablePackage.A_Override();
}
public void B()
{
_overridablePackage.B_Override();
}
private class MyDefaultPackage : IMyOverridablePackage
{
private readonly MyBaseClass _myBaseClass;
internal MyDefaultPackage(MyBaseClass myBaseClass)
{
_myBaseClass = myBaseClass;
}
void IMyOverridablePackage.A_Override()
{
_myBaseClass.A_Impl();
}
void IMyOverridablePackage.B_Override()
{
_myBaseClass.B_Impl();
}
}
protected MyBaseClass()
{
_overridablePackage = new MyDefaultPackage(this);
}
private void A_Impl()
{
Console.WriteLine("MyBaseClass.A_Impl");
}
private void B_Impl()
{
Console.WriteLine("MyBaseClass.B_Impl");
}
protected void SetOverride(IMyOverridablePackage overridablePackage)
{
_overridablePackage = overridablePackage;
}
}
This does achieve the goal, but of course you have to ask 'how much to I want it?' Is it worth the extra code?
Here's a working dotnetfiddle: https://dotnetfiddle.net/xmPn20
Maybe you cannot force it via compiler errors, but you could write a test which asserts that the methods are in sync via some attributes. It would also be visible that there is some dependency.
A crude example would be something like this:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class VersionAttribute : Attribute
{
public VersionAttribute(string version)
{
Version = version;
}
public string Version { get; set; }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class DependentAttribute : Attribute
{
public string DependentOnMethod { get; set; }
public string DependentOnVersion { get; set; }
}
[Dependent(DependentOnMethod = "OtherMethod", DependentOnVersion = "1")]
public static void FirstMethod()
{
}
[Version("1")]
public static void OtherMethod()
{
}
And the test that asserts the version numbers:
[Test]
public void TestVersions()
{
foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
{
foreach (var method in type.GetMethods())
{
foreach (var customAttribute in method.GetCustomAttributes())
{
var dependent = customAttribute as DependentAttribute;
if (dependent != null)
{
var methodInfo = type.GetMethod(dependent.DependentOnMethod);
Assert.That(methodInfo, Is.Not.Null, "Dependent method not found");
VersionAttribute version = methodInfo.GetCustomAttributes().OfType<VersionAttribute>().FirstOrDefault();
Assert.That(version, Is.Not.Null, "No version attribute on dependent method");
Assert.That(dependent.DependentOnVersion, Is.EqualTo(version.Version));
}
}
}
}
}
thus, if you update one of your methods you would need to update the version number of either the Version attribute or the Dependent attribute. Hopefully better than nothing.
You may change your design :
public abstract class BaseClass
{
protected abstract void A();
}
public class BaseClassEx
{
protected sealed override void A()
{
// action Calling B
}
protected virtual void B()
{
// a default action called second
}
}
In the case of Equals (actually both Equals overloads, concrete type and object) and GetHashCode, Resharper includes a rule that shows a warning in its IntelliSense whenever you forget to implement one of these.
You could enforce it in your code with a runtime check in the constructor of the base class:
public class Base
{
public Base()
{
var baseA = typeof (Base).GetRuntimeMethod("MethodA", new Type[0]);
var baseB = typeof (Base).GetRuntimeMethod("MethodB", new Type[0]);
var derivedA = GetType().GetRuntimeMethod("MethodA", new Type[0]);
var derivedB = GetType().GetRuntimeMethod("MethodB", new Type[0]);
if (baseA.DeclaringType == derivedA.DeclaringType ^
baseB.DeclaringType == derivedB.DeclaringType)
throw new InvalidOperationException("You must override MethodA and MethodB together.");
}
public virtual string MethodA() { return "Hello"; }
public virtual int MethodB() { return 123; }
}
Let's say I have an interface IFoo
interface IFoo
{
int Bar();
int Bar2();
void VBar();
//etc,
}
Can I create a wrapper that takes any IFoo object and do something before/after the actual call?
e.g. when I do something like this
IFoo wrappedFoo = new Wrapper<IFoo>(actualFooObject).Object;
wrappedFoo.Bar();
then the wrapper.Bar() method actually execute something like this
PreCall(); //some code that I can define in the wrapper
actualFooObject.Bar();
PostCall();
Is there a simple and clean way to do this?
You can use Code Contracts for this approach. Take a look on section 2.8 Interface Contracts of user manual (pdf).
You can use AOP. I´ve been using this library for quite some time now:
http://www.postsharp.net/products
if you need to have something on PreCall() and PostCall , the simple way is to wrap under the proxy base approach
public abstract class ProxyBase
{
public void Execute()
{
PreCondition();
Call();
PostCondition();
}
private void PreCondition()
{
Console.WriteLine("ProxyBase.PreCondition()");
}
private void PostCondition()
{
Console.WriteLine("ProxyBase.PreCondition()");
}
protected abstract void Call();
}
public class AppProxy<T> : ProxyBase where T : IApp
{
private IApp _app;
public AppProxy<T> Init(IApp app)
{
_app = app;
return this;
}
protected override void Call()
{
Console.WriteLine("AppProxy.Call()");
_app.Call();
}
public IApp Object
{
get { return _app; }
}
}
public interface IApp
{
void Call();
}
public interface IFoo : IApp
{
}
public class ActualFoo : IApp
{
public void Call()
{
Console.WriteLine("ActualFoo.Call()");
}
}
class Program
{
static void Main(string[] args)
{
ActualFoo actualFoo = new ActualFoo();
var app = new AppProxy<IFoo>().Init(actualFoo);
app.Execute();
var o = app.Object as ActualFoo;
Console.ReadLine();
}
}
--------------- Output --------------
ProxyBase.PreCondition()
AppProxy.Call()
ActualFoo.Call()
ProxyBase.PreCondition()
I don't see a "clean and simple" way of doing this.
The best option I can come up with is writing a generic Wrapper<T> that encapsulates and instance of T and implements generic Precall and Postcall methods:
public class Wrapper<T>
{
protected T _instance;
public Wrapper(T instance)
{
this._instance = instance;
}
protected virtual void Precall()
{
// do something
}
protected virtual void Postcall()
{
// do something
}
}
So that you can write your own FooWrapper for interface IFoo (or any other interface) and just delegate method calls:
public class FooWrapper :Wrapper<IFoo>, IFoo
{
public FooWrapper(IFoo foo)
: base(foo)
{
}
public int Bar()
{
base.Precall(); return base._instance.Bar(); base.Postcall();
}
public int Bar2()
{
base.Precall(); return base._instance.Bar2(); base.Postcall();
}
public void VBar()
{
base.Precall(); base._instance.VBar(); base.Postcall();
}
}
So you can use it like this:
IFoo f = new ActualFooClass();
IFoo wf = new FooWrapper(f);
f.Bar();
Of course, if your Precall and Postcall methods are not generic, then there is really no point in using the Wrapper<T> class. Just go with the FooWrapper.