How to verify that mock object was "gotten"? - c#

Is there a way to assert that my mocked object was "gotten" ?
public class Car
{
private readonly IValidationDict _validationDict;
public Car(IValidationDict validationDict)
{
_validationDict = validationDict;
}
public void Go()
{
var myValidation = _validationDict; //I would like to assert that _validationDict was indeed assigned to another variable or "gotten"
}
}
In my unit test I would have something like:
var mock = new Mock<IValidationDict>();
var sut = new Car(IValidationDict.Object);
Is there a way to assert that my mocked object was "gotten" ?

No, there is no way to verify that your mock object was used as part of the assignment. The assignment of myValidation happens outside the bounds of the Moq framework and therefore Moq can't do any interception to track it.
As #Lee state, there is an assumption that myValidation is used somewhere else and the use of that variable (which will be a mocked instance) can be checked.
One alternative if you must know if your mock was accessed would be to create a factory class that has a method for obtaining your validation dictionary (something like GetValidation) and then pass a mocked factory to your Car and verify that the GetValidation method was called on the factory.

Related

How to mock same class method in asp.net unit test

public class Controller
{
public GetSomeData()
{
retun someData;
}
public dosomthing(Some someObj)
{
var getData = GetSomeData();
return service.DosomethingElse(getData);
}
}
I have mocked service.DosomethingElse(getData);.
I've also mocked GetSomeData(); but it returns "" (blank value) I want to return with "myData".
I've written a TestMethod like this:
string someData ="myData";
var mockData = new Mock<Controller>();
mockData.Setup(x => x.GetSomeData()).Returns(someData);
var mockDa = new Mock<Service>();
mockDa.Setup(x => x.DosomethingElse(getData)).Returns(response);
Controller cObj= new Controller(mockDa.Object);
var actual = cObj.dosomthing(Some someObj);
Assert.AreEqual("expected",actual);
Please suggest how to mock GetSomeData() method of the same class.
You can't do that. You can't mock the GetSomeData for the controller you are testing. You can only mock the dependencies you inject to the class.
Think about it this way:
A mock is an object with specific behavior, mocking a real class object
A class object has the proper behavior
You can't have a hybrid object, a little bit of mock and a little bit of class.
By the way, even if you could, you shouldn't. When you are testing a method, you also test the other methods of the same class that are used within. This is also the way you are testing the private functions of a class.

C# Mock the object and expect its constructor to return mocked object using Rhino Mocks

I have an object which I initialize inside using block to dispose few things. Then later inside using block I am calling some method of that object.
public void MyMethod()
{
using(var obj = new Someclass())
{
// I want to mock this method call
var result = obj.SomeMethod();
}
}
As I am writing unit test case for this, I have to mock the object and expect my own result by calling SomeMethod.
I understand that If you want to mock any object then that object should be passed as a dependency and then we can expect our own result there but here in this case, if I pass the object as a dependency then I will not be able to use using block. For eg-
public void MyMethod(SomeClass object)
{
// Here can I do something like this ?
// If this works then I can easily send the mocked object
using(var obj = object)
{
// I want to mock this method call
var result = obj.SomeMethod();
}
}
So my question is that
Is there a way that I pass the mock object as a dependency and also use the object initialization but I should expect from my object that If your constructor is called anywhere in the code then please ignore that
Shall I stop thinking of using Using block and call the dispose method manually
Thanks in advance
When adding the depency as parameter to your method, the client of that method isn´t only resposible for creating that depenency, but also for disposing it. Thus there´s no need to have the using in your method. However you´ll need it at the client-side:
using(var mock = Mock<MyClass>()) // don´t know the exact Rhino-syntax to get a mock
{
MyMethod(mock);
}
Now your method becomes something like this:
void MyMethod(MyClass m)
{
m.SomeMethod(); // notice that there´s no using
}
However when having a mock you surely won´t need to dipsoe it at all, at it is a leightweight instance whithout any unmanaged resources.
EDIT: If you are sure that MyMethod is the only place that uses the dependency, you can surely dispose it within that method as well:
void MyMethod(MyClass m)
{
using(m) { m.SomeMethod(); }
}
However thais may lead to confusion to clients of MyMethod, as the dependecy will be disposed after calling this method:
var m = Mock<MyClass>();
MyMethod(m);
m.DoSomething(); // will lead to ObjectDisposedException
There is a way to do this. You want to pass dependency, but only for creation of the object. This way you can mock Dispose assuring you never dispose the object in tests. I don't have knowledge of rhino mock library, but you should get the idea.
You need SomeClassFactory which will be dependency and will return an instance of SomeClass. This way you can mock SomeClass's Dispose method and ignore disposing the object.
//Arrange
var someClassFactoryMock = MockRepository.GenerateMock<ISomeClassFactory>();
var someClassMock = MockRepository.GenerateMock<ISomeClass>();
someClassMock.Stub(s => s.Dispose()); // Ignore Dispose
someClassFactoryMock.Stub(s => s.Get()).Return(someClassMock); // Return mock
var fooClass = new Foo();
fooClass.SomeClassFactory = someClassFactoryMock;
// Act
fooClass.SomeMethod();
// Assert
someClassMock.Expect(s => s.SomeMethod()).Repeat.Times(1); // Assert that it was called once.
SomeClassFactory is just a very simple factory
public class SomeClassFactory : ISomeClassFactory
{
public ISomeClass Get() => new SomeClass();
}
And put it all together:
public class Foo
{
public ISomeClassFactory SomeClassFactory { get; set; }
public void MyMethod()
{
using(ISomeClass obj = SomeClassFactory.Get())
{
// When testing, obj will be a mock with Dispose method mocked to not do anything. This way it will not be disposed.
var result = obj.SomeMethod();
}
}
}
Please note this is only pseudo code. If you want any errors, please let me know.

How to use Moq to have an ability to use method operation of mocked object?

I have an instantiation in constructor in test:
public class Car{
public string Method()
{
return "test";
}
}
private readonly ICar _classUnderTest;
public CarTests()
{
var collaboratingClass = new CollaboratingClass();
_classUnderTest = new Car(collaboratingClass );
}
If I use moq and pass mock instance like this:
var collaboratingClass = new Mock<ICollaboratingClass>();
_classUnderTest = new Car(collaboratingClass .Object);
...then I can't call method. The method from this mocked instance is not being called, so I can't use it for calculation. How can I make my mock object to be able to access method and do operation with mock object?
As you can see I don't want to have concrete dependencies here.
You can fake a return to your mocked class method. If you need the behavior from your dependency, it's no longer a unit test

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.

NUnit Mocking not working for Singleton Method

Bear with me, I'm new to NUnit. I come from the land of Rails, so some of this is new to me.
I have a line of code that looks like this:
var code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
I'm trying to mock it, like this (assume code is already initialized):
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
When I debug the test, getCodeByCodeNameAndType is returning null, instead of the expected code. What am I doing wrong?
NUnit version: 2.2.8
I'm sorry, but I've never used NUnit.Mocks - but I do have some experience with NMock and Moq [which, by the way, I highly recommend]. Typically, you use a mocking library to generate proxies for Interface definitions, and I presume NUnit.Mocks operates the same way.
Therefore, if you would like to mock your singleton, you will likely have to do the following,
a. Create an interface, say
// All methods you would like to mock from this class, should
// be members of this interface
public interface IWebSiteConfiguration
{
// Should match signature of method you are mocking
CodeType getCodeByCodeNameAndType (
string codeString,
CatalogType catalogType);
}
b. "Implement" interface
// You've already written the method, interface matches signature,
// should be as easy as slapping interface on class declaration
public class WebSiteConfiguration : IWebSiteConfiguration { }
c. Consume interface
alright, so step c. is where most of your work will be. Logically, if you are mocking your singleton, you are actually unit testing the consumer [which you have left out of your sample]. For c. simply add a parameter to the consumer's ctor, or add a publicly accessible property of Type 'IWebSiteConfiguration', and then internally, reference the instance member and invoke your methods against this new interface. Consider this,
was
public class MyClass
{
public MyClass () { }
public void DoSomething ()
{
// bad singleton! bad boy! static references are bad! you
// can't change them! convenient but bad!
code = WebSiteConfiguration.Instance.getCodeByCodeNameAndType (
"some.string",
someCatalog)
}
}
becomes
public class MyClass
{
private readonly IWebSiteConfiguration _config = null;
// just so you don't break any other code, you can default
// to your static singleton on a default ctor
public MyClass () : this (WebSiteConfiguration.Instance) { }
// new constructor permits you to swap in any implementation
// including your mock!
public MyClass (IWebSiteConfiguration config)
{
_config = config;
}
public void DoSomething ()
{
// huzzah!
code = _config.getCodeByCodeNameAndType ("some.string", someCatalog)
}
}
In your unit test, create the mock, pass a reference of the mock to the consumer, and test the consumer.
[Test]
public void Test ()
{
IWebSiteConfiguration mockConfig = null;
// setup mock instance and expectation via
// NUnit.Mocks, NMock, or Moq
MyClass myClass = new MyClass (mockConfig);
myClass.DoSomething ();
// verify results
}
This also serves as a practical introduction to Dependency Injection [DI]. It's simply the practice of passing, or "injecting", references of services [eg your web site configuration class] to the consumer, rather than having the consumer invoke the service directly [eg via static singleton class].
Hope this helps :)
A DynamicMock creates a new object in-memory that represents the interface, or marshallable (inherits from MarshalByRef) class you want to mock.
Try this:
var _websiteConfigurationMock = new DynamicMock(typeof(WebSiteConfiguration));
_websiteConfigurationMock.ExpectAndReturn("getCodeByCodeNameAndType", code);
WebSiteConfiguration conf = (WebSiteConfiguration)_websiteConfigurationMock.MockInstance;
var x = conf.getCodeByCodeNameAndType("CATALOG_Brands_MinQty", item.Catalog);
Note that the third line there will not work unless WebSiteConfiguration inherits from MarshalByRef.
What you typically do is mock an interface and get a new object that implements this interface, but behaves the way you've configured it to do, without having to go and make a concrete type for it, so I'm not entirely sure what you're doing is going to work unless you employ a better isolation framework, like TypeMock that can intercept calls to static methods/properties in existing objects.
Seems there is a kind of solution for this using reflection, or maybe I totally misunderstood this.
It is discussed here:
http://www.geekbeing.com/2010/05/23/how-to-unit-test-singleton-hack-in-c
Could it really works?
public class TestableSingleton : SingletonClass
{
public TestableSingleton ()
{
FieldInfo fieldInfo = typeof(SingletonClass)
.GetField("_instance",
BindingFlags.Static | BindingFlags.NonPublic);
fieldInfo.SetValue(Instance, this);
}
}
Project availabe on https://github.com/rbabreu/TestableSingleton
Actually I could not compile it on Visual Studio since the SingletonClass would have a private constructor. If someone get it to work would be great to avoid the overhead of adapter pattern.

Categories