How do I mock a private field? - c#

I'm really new to mocks and am trying to replace a private field with a mock object. Currently the instance of the private field is created in the constructor. My code looks like...
public class Cache {
private ISnapshot _lastest_snapshot;
public ISnapshot LatestSnapshot {
get { return this._lastest_snapshot; }
private set { this._latest_snapshot = value; }
}
public Cache() {
this.LatestSnapshot = new Snapshot();
}
public void Freeze(IUpdates Updates) {
ISnapshot _next = this.LastestSnapshot.CreateNext();
_next.FreezeFrom(Updates);
this.LastestSnapshot = _next;
}
}
What I'm trying to do is create a unit test that asserts ISnapshot.FreezeFrom(IUpdates) is called from within Cache.Freeze(IUpdates). I'm guessing I should replace the private field _latest_snapshot with a mock object (maybe wrong assumption?). How would I go about that while still retaining a parameterless constructor and not resorting to making LatestSnapshot's set public?
If I'm totally going about writing the test the wrong way then please do point out as well.
The actual implementation of ISnapshot.FreezeFrom itself calls a heirarchy of other methods with a deep object graph so I'm not too keen on asserting the object graph.
Thanks in advance.

I'm almost citing techniques from "Working Effectively with Legacy Code":
Sub-class your class in a unit test and supersede your private variable with a mock object in it (by adding a public setter or in the constructor). You probably have to make the variable protected.
Make a protected getter for this private variable, and override it in testing subclass to return a mock object instead of the actual private variable.
Create a protected factory method for creating ISnapshot object, and override it in testing subclass to return an instance of a mock object instead of the real one. This way the constructor will get the right value from the start.
Parametrize constructor to take an instance of ISnapshot.

I'm not sure that you can do that. If you're wanting to test _next then you're probably going to have to pass it in as a parameter and then in your unit test pass in a Mock object which you can then test using an Expectation. That's what I'd be doing if I were trying to do it in Moq.
As an example of what I might try using the Moq framework:
Mock<ISnapshot> snapshotMock = new Mock<ISnapshot>();
snapshotMock.Expect(p => p.FreezeFrom(expectedUpdate)).AtMostOnce();
Cache c = new Cache(snapshotMock.Object);
c.Freeze(expectedUpdate);
Note: I haven't tried to compile the above code. Its just there to give an example of how I'd approach solving this.

I don't think you'd need to mock private member variables. Isn't the whole idea of mocking that the public interface for an object works as expected? Private variables are implementation details that mocks aren't concerned with.

This answer might be simple, but looking at the code, is there any way in which ISnapshot.FreezeFrom(IUpdates) is not going to be called? Sounds like you want to assert something that will always be true.
As Jason says, mocking is meant for situations where your class depends on SomeInterface to do it's work, and you want to test YourClass in isolation from whichever implementation of SomeInterface you actually use at runtime.

The question to ask is: what are the externally visible effects if this worked?
What happens to all those Snapshots? One option might to initialise the Cache with its first Snapshot from outside, say in the constructor. Another might be to mock whatever it is that the Snapshot calls that matters outside the cache. It depends on what you care that happens.

It might be too late to respond. Anyways. I also had similar problem.
public class Model
{
public ISomeClass XYZ{
get;
private set;
}
}
I required to set value of XYZ in my test case. I resolved the problem using this syntex.
Expect.Call(_model.XYZ).Return(new SomeClass());
_repository.ReplayAll();
In the case above we can do it like this
Expect.Call(_cache.LatestSnapshot).Return(new Snapshot());
_repository.ReplayAll();

You will probably have to refactor your class like this, in order for it to be injected with a different dependency for ISnapshot. Your class will remain to function the same.
public class Cache {
private ISnapshot _lastest_snapshot;
public ISnapshot LatestSnapshot {
get { return this._lastest_snapshot; }
private set { this._latest_snapshot = value; }
}
public Cache() : this (new Snapshot()) {
}
public Cache(ISnapshot latestSnapshot) {
this.LatestSnapshot = latestSnapshot;
}
public void Freeze(IUpdates Updates) {
ISnapshot _next = this.LastestSnapshot.CreateNext();
_next.FreezeFrom(Updates);
this.LastestSnapshot = _next;
}
}

You can simply add "setSnapshot(ISnapshot)" method to the Cache with your mocked class instance.
You can also add a constructor that takes ISnapshot.

Turn Cache into a template as shown below.
template <typename T=ISnapshot>
public class Cache {
private T _lastest_snapshot;
public T LatestSnapshot {
get { return this._lastest_snapshot; }
private set { this._latest_snapshot = value; }
}
public Cache() {
this.LatestSnapshot = new Snapshot();
}
public void Freeze(IUpdates Updates) {
T _next = this.LastestSnapshot.CreateNext();
_next.FreezeFrom(Updates);
this.LastestSnapshot = _next;
}
}
In production code do:
Cache<> foo;//OR
Cache<ISnapshot> bar;
In test code do:
Cache<MockSnapshot> mockFoo;

Related

How to mock a function call in the method I am testing - currently using NSubsitute

I am new to trying to mock things in unit tests...
Example Code simplified for posting:
namespace MockInvestigate.Monitor
{
internal interface IAgentRepo
{
Dictionary<string, string> GetAgentAppSettings(string moduleName);
}
public class AgentRepo : IAgentRepo
{
public virtual Dictionary<string, string> GetAgentAppSettings(string moduleName)
{
return new Dictionary<string, string> { { "real", "data" } };
}
}
}
This is the method I want to unit test - but override the call to GetAgentAppSettings
namespace MockInvestigate
{
public class Class1
{
public static bool IsInitialized(string taskName)
{
AgentRepo ar = new AgentRepo();
var arReturn = ar.GetAgentAppSettings(taskName);
return arReturn.ContainsKey("real");
}
}
}
The unit test - trying to mock the call to 'GetAgentAppSettings'
[TestMethod]
public void TestMethod1()
{
var repo = Substitute.ForPartsOf<AgentRepo>();
var appReturn = new Dictionary<string, string> { { "bogus", "bogus2" } };
repo.GetAgentAppSettings("somevalue").ReturnsForAnyArgs(appReturn);
bool retValue = Class1.IsInitialized("somevalue");
Assert.IsFalse(retValue);
}
When my test is run, the real GetAgentAppSettings is called, returning "real", "data" and not the bogus data I want.
I have tried .When(...).DoNotCallBase().
Can my test be modified to work? Does the underlying code need to change to work?
Any help would be appreciated.
After creating the substitute repo, you have to inject it inside Class1.
In your code, however, you are creating the AgentRepo inside the IsInitialized method, thus it's not using the substitute you created in the test method.
You have to inject the substitute by constructor injection, property injection or method injection.
As the name suggests, constructor injection is when you inject the dependency from the constructor. Since the method IsInitialized is static, that's not an option.
Likewise, property injection uses properties to inject the dependencies. You could create a static property, usually you'd stay away from it though.
It'd always use the same instance for every thread, hence you'd have to guarantee that the AgentRepo is thread-safe.
As last resort, you can use the method injection. You'd get the AgentRepo instance as a method argument and let the caller be responsible for creating it.
Since this is a small repro, I can't tell you what's the best way to deal with it. What I do know is that the AgentRepo must be injected into Class1 somehow.

Singleton Alternative - is it equivalent?

I know that the standard singleton pattern is as follows:
Original
public class Singleton1
{
public static Singleton1 _Instance;
public static Singleton1 Instance
{
get
{
if (_Instance == null)
{
_Instance = new Singleton1();
}
return _Instance;
}
}
private Singleton1()
{
}
}
But it seems like this code is unnecessary. To me, you could accomplish the same thing with either of the following simple design patterns:
Version 2
public class Singleton2
{
public static readonly Singleton2 Instance = new Singleton2();
private Singleton2()
{
}
}
Version 3
public class Singleton3
{
static Singleton3()
{
}
}
To me, it seems like version 2 is the superior method of doing this because it allows you to pass in parameters (or not) yet still have a finite number of instance. My application is fairly latency/performance sensitive - do any of these patterns have a performance gain?
It would seem that while it will longer to access each one the first time because the object is being created. Also, it would seem that the original one is ever so slightly slower because it must check to see whether its backing field is null every time something else accesses it.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
Fast, clean, thread-safe.
One problem with singletons implemented as static instances is that they make testing and mocking more difficult.
See this scenario:
public void BusinessLogicMethod()
{
var initialValue = MySingleton.Instance.GetInitialValue();
var processedValue = initialValue + specialSomething + businessLogic;
MySingleton.Instance.SaveProcessedValue(processedValue);
}
Now, let's say I want to write a unit-test for this method. Ideally, I want to write a test that specifies input and output and tests only the business logic. But with a static singleton, the method's implementation is tied to the singleton's implementation. Can I set the InitialValue easily at the beginning of the test, or is it dependent on other factors/DB access/whatever?
However, if I use a non-static singleton, coupled with some dependency injection or service locator pattern, I can build my function like this:
public void BusinessLogicMethod()
{
var singleton = ServiceLocator.Resolve<MySingleton>();
var processedValue = singleton.InitialValue + specialSomething + businessLogic;
singleton.SaveProcessedValue(processedValue);
}
and my test can go like this, using vaguely Moq-like mock syntax:
public void TestBusinessLogic()
{
MySingleton fakeSingleton = new Mock<MySingleton>();
fakeSingleton.Setup(s => s.InitialValue).Returns(5);
// Register the fake in the ServiceLocator
ServiceLocator.Register<MySingleton>(fakeSingleton.Object);
// Run
MyBusinessMethod();
// Assert
fakeSingleton.Verify (s => s.SaveProcessedValue()).Called(Exactly.Once);
}
without worrying about the REAL singleton implementation.
Singleton2 is not the same as Singleton1 as the Instance is not "lazy" evaluated. In Singleton1, Instance is created only when it is accessed and from then on the same one is used. In SingleTon2, the Instance is initialized with the class and before being actually accessed.
My favourite singleton implementation is this one:
http://www.codeproject.com/Articles/14026/Generic-Singleton-Pattern-using-Reflection-in-C
Make sure your .ctor is not public, which is the most common mistake, then, it is safely/fully reusable.
(I need to have a close look at Peter Kiss' one which looks nice too)
To answer your performance question, the time it takes to check whether the private field is null is negligible. Therefore I wouldn't be worrying about how it is implemented with regards to performance here.

Rhino Mocks, Interfaces and properties

I have a class that has a property that I need to stub. I can't pass it as part of the constructor because the object constructing it does not know the parameters of the constructor.
When running unit tests, I want to be able to have the property be created as a stub.
This is what I have tried, but it does not work:
private DeviceMediator deviceMediator;
private IDeviceControlForm deviceControlForm;
private IDataAccess data;
private ICallMonitor callMonitor;
// Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
// This line works fine
deviceControlForm = MockRepository.GenerateStub<IDeviceControlForm>();
// This line works fine
data = MockRepository.GenerateStub<IDataAccess>();
// This has to be an ICallMonitor. If I try to make it a
// CallMonitor then it fails.
callMonitor = (CallMonitor)
MockRepository.GenerateStub<ICallMonitor>();
// This line does not compile. Because it wants to
// return a CallMonitor not an ICallMonitor.
Expect.Call(new CallMonitor(null)).Return(callMonitor);
// This is the class that has the CallMonitor (called callMonitor).
deviceMediator = new DeviceMediator(deviceControlForm, data);
}
Is there anyway to catch the constructor call to CallMonitor and make it actually be a stub?
In case it is relevant, here is the related code in DeviceMediator:
private IDeviceControlForm form;
private readonly IDataAccess data;
public ICallMonitor CallMonitor { get; set; }
public DeviceMediator(IDeviceControlForm form, IDataAccess data)
{
this.form = form;
this.data = data;
CallMonitor = new CallMonitor(OnIncomingCall);
}
Thanks in advance for any help.
Since the CallMonitor property is writable, you can just overwrite the original value with a mock instance (your DeviceMediator actually implements the Property Injection design pattern).
So you can write a test like this:
[TestMethod]
public void MyTest()
{
var deviceControlForm = MockRepository.GenerateStub<IDeviceControlForm>();
var data = MockRepository.GenerateStub<IDataAccess>();
var mockCallMonitor = MockRepository.GenerateStub<ICallMonitor>();
var deviceMediator = new DeviceMediator(deviceControlForm, data);
deviceMediator.CallMonitor = mockCallMonitor;
// The rest of the test...
}
Firstly you can stub/mock classes directly in RhinoMock so if you want an actual CallMonitor stub rather than ICallMonitor you can, and this will overcome the casting issue in your code. The reason the cast fails is that RhinoMock creates a 'dynamic proxy' object which is not CallMonitor.
Secondly you cannot mock constructor calls, and most importantly there is no way to mock the call to new CallMonitor in the DeviceMediator constructor since there is no way to inject an instance.
The usual way to do what you want would be to change the DeviceMediator constructor to this:
public DeviceMediator(IDeviceControlForm form, IDataAccess data, ICallMonitor callMonitor) { ... }
Then your test can inject a stub/mock instance of this interface into the constructor.
EDIT: If you really can't inject an instance into the constructor then you have a few options:
Create a factory which you can stub:
public class CallMonitorFactory
{
public virtual CallMonitor CreateMonitor(args...) { }
}
public DeviceMediator(IDeviceControlForm form, IDataAccess data, CallMonitorFactory factory)
{
this.form = form;
this.data = data;
CallMonitor = factory.CreateMonitor(OnIncomingCall);
}
Add a protected factory method on DeviceMediator which returns a CallMonitor. You will then have to manually create a sub-class of DeviceMediator in your test so you can return the mock CallMonitor object.
Move the constructor argument for CallMonitor into a method/property that is called in the DeviceMediator constructor.
It appears you're trying to listen for an event of some kind on the CallMonitor, so you could (and should if this is the case) add an event which the DeviceMediator subscribes to. In this case you can use RhinoMock to mock the event raising call like this:
[Test]
public void IncomingCallTest()
{
IEventRaiser callEvent;
CallMonitor monitor = mocks.Stub(args..);
using(mocks.Record())
{
callEvent = monitor.Stub(m => m.IncomingCall += null).IgnoreArguments().GetEventRaiser();
//rest of expectations...
}
using(mocks.Playback())
{
DeviceMediator mediator = new DeviceMediator(form, data, monitor);
callEvent.Raise(sender, args);
}
}
However, as noted above, you cannot mock constructor calls using RhinoMock since this would require some changes to the generated IL (assuming it's even possible).
I do not have too much experience with Rhino in particular, but did you try casting the callMonitor to a CallMonitor in the call to Return?
For example:
Expect.Call(new CallMonitor(null)).Return((CallMonitor)callMonitor);
EDIT:
On second thought, it looks like Return might be a generic method, which means this could be an additional option
Expect.Call(new CallMonitor(null)).Return<CallMonitor>(callMonitor);

How can one type access a private setter of another type's property?

All I need is a way to make a property of one class only 'settable' from one other class (a sort of manager class).
Is this even possible in c#?
My colleague 'reliably' informs me that I have a design flaw, but I feel I should at least ask the community before I concede defeat!
No, it's not really possible to do this in any clean way in C#. You probably have a design flaw ;-)
You can use the internal modifier, which lets all types in the same assembly access the data (or nominated assemblies if using [InternalsVisibleTo] - but no: there is no friend equivalent in C#.
For example:
public string Foo {get; internal set;}
You have a design flaw. Also, don't be paranoid about data hiding. Here's 3.5's way to do it:
class Program
{
static void Main(string[] args)
{
Managed m = new Managed();
Console.WriteLine(m.PrivateSetter);
m.Mgr.SetProperty("lol");
Console.WriteLine(m.PrivateSetter);
Console.Read();
}
}
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(s => PrivateSetter = s)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
}
public class Manager
{
private Action<string> _setPrivateProperty;
public Manager(Action<string> setter)
{
_setPrivateProperty = setter;
}
public void SetProperty(string value)
{
_setPrivateProperty(value);
}
}
Here's how we'd do it in pre-lambda days:
public class Managed
{
private Manager _mgr;
public Manager Mgr
{
get { return _mgr ?? (_mgr = new Manager(this)); }
}
public string PrivateSetter { get; private set; }
public Managed()
{
PrivateSetter = "Unset";
}
public class Manager
{
public void SetProperty(string value)
{
m.PrivateSetter = value;
}
private Managed m;
public Manager(Managed man)
{
m = man;
}
}
}
The best way to do it would be:
/// <summary>
/// Gets or sets foo
/// <b>Setter should only be invoked by SomeClass</b>
/// </summary>
public Object Foo
{
get { return foo; }
set { foo = value; }
}
When you have some complex access or inheritance restriction, and enforcing it demands too much complexity in the code, sometimes the best way to do it is just properly commenting it.
Note however that you cannot rely on this if this restriction has some security implications, as you are depending on the goodwill of the developer that will use this code.
You cannot do that on that way, but you can access a property's setter method from a derived class, so you can use inheritance for the purpose. All you have to do is to place protected access modifier. If you try to do so, your colleague is right :). You can try doing it like this:
public string Name
{
get{ return _name; }
protected set { _name = value; }
}
keep in mind that the set method of the property is only accessible from the derived class.
Or you could have these two classes in an assembly alone and have the setter as internal. I would vote up for the design flaw though, unless the previous answer by milot (inheriting and protected) makes sense.
You could do:
public void setMyProperty(int value, Object caller)
{
if(caller is MyManagerClass)
{
MyProperty = value;
}
}
This would mean that you could use a 'this' pointer from the calling class. I would question the logic of what you're attempting to achieve, but without knowing the scenario I can't advise any futher. What I will say is this: if it is possible to refactor your code to make it clearer, then it is often worthwhile doing so.
But this is pretty messy and certinly NOT fool-proof ... you have been warned!
Alternativly...
You could pass a delegate from the Class with the Property (Class A) to the Manager Class (Class B). The delegate can refer to a private function within A to allow B to call that delegate as any normal function. This precludes that A knows about B and potentially that A is created before B. Again... messy and not fool-proof!
You can achieve to this by making a Public property in your "settable class" that will inherit from the real class that will have a protected property... this way only the inherit class can SET and not class that doesn't inherit. But the drawback is that you will require to have an inherit class...
Reflection, though I would agree that having to do this just to get around an access modifier is probably an indication of a bad design.
public class Widget
{
private int count;
public int Count
{
get { return this.count; }
private set { this.count = value; }
}
}
public static class WidgetManager
{
public static void CatastrophicErrorResetWidgetCount( Widget widget )
{
Type type = widget.GetType();
PropertyInfo info = type.GetProperty("Count",BindingFlags.Instance|BindingFlags.NonPublic);
info.SetValue(widget,0,null);
}
}
The reason this is a design flaw is because it seems muddled between the scope of the two objects.
The properties of a class should be accessible in the context of that class, at least internally.
It sounds like the settable property on your item class is really a property of the manager class.
You could do something similar to what you want by closely coupling the two classes:
public class MyItem {
internal MyItemManager manager { get;set; }
public string Property1 {
get { return manager.GetPropertyForItem( this ); }
}
}
Unfortunately this isn't great design either.
What your looking for is what C++ calls a Friend class but neither c# or vb has this functionality. There is a lot of debate as to the merit of such functionality since it almost encourages very strong coupling between classes. The only way you could implement this in c# would be with reflection.
If your goal is to have a class Foo let some property (e.g. Bar, of type Biz) to be changed by some other object, without exposing it publicly, a simple way to do that is to have an instance of Foo which is supposed to be changeable by some other object to pass that other object an Action<Biz> which points to a private method that changes Bar to the passed-in value. The other object may use that delegate to change the Bar value of the object that supplied it.
If one wishes to have give all instances of some type Woozle the ability to set the Bar value of any instance of Foo, rather than exposing such abilities on a per-instance basis, one may require that Woozle have a public static method Woozle.InstallFooBarSetter which takes a parameter of type Action<Foo, Biz> and one of type Object. Foo should then have a static method WoozleRequestBarSetter which takes an Object, and passes it to Woozle.InstallFooBarSetter along with an Action<Foo,Biz>. The class initializer for Woozle should generate a new Object, and pass it to Foo.RequestBarSetter; that will pass the object to Woozle.InstallFooBarSetter along with a delegate. Woozle can then confirm that the passed-in object is the one that it generated, and--if so--install the appropriate delegate. Doing things this way will ensure that nobody but Woozle can get the delegate (since the delegate is only passed to Woozle.InstallFooBarSetter), and Woozle can be sure its delegate comes from Foo (since nobody else would have access to the object that Woozle created, and Woozle.InstallFooBarSetter won't do anything without it).
if it is a design flaw depends on what you want to do. You could use the StackTrace class from System.Diagnostics to get the Type of the class setting your property and then compare to the type you want to allow setting yor property..but maybe there are better ways for performing something like this (e.g. boxing)

How to unit test immutable class constructors?

I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case.
Simple Example
This class is defined in Assembly1:
public class Class2Test
{
private readonly string _StringProperty;
public Class2Test()
{
_StringProperty = ConfigurationManager.AppSettings["stringProperty"];
}
}
This class is defined in Assembly2:
[TestClass]
public class TestClass
{
[TestMethod]
public void Class2Test_Default_Constructor()
{
Class2Test x = new Class2Test();
//what do I assert to validate that the field was set properly?
}
}
EDIT 1: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it.
This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work?
EDIT 2: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.
Nothing, unless you are using that field. You don't want over-specification via tests. In other words, there is no need to test that the assignment operator works.
If you are using that field in a method or something, call that method and assert on that.
Edit:
assume the constructor has some more complex logic
You shouldn't be performing any logic in constructors.
Edit 2:
public Class2Test()
{
_StringProperty = ConfigurationManager.AppSettings["stringProperty"];
}
Don't do that! =) Your simple unit test has now become an integration test because it depends on the successful operation of more than one class. Write a class that handles configuration values. WebConfigSettingsReader could be the name, and it should encapsulate the ConfigurationManager.AppSettings call. Pass an instance of that SettingsReader class into the constructor of Class2Test. Then, in your unit test, you can mock your WebConfigSettingsReader and stub out a response to any calls you might make to it.
I have properly enabled [InternalsVisibleTo] on Assembly1 (code) so that there is a trust relationship with Assembly2 (tests).
public class Class2Test
{
private readonly string _StringProperty;
internal string StringProperty { get { return _StringProperty; } }
public Class2Test(string stringProperty)
{
_StringProperty = stringProperty;
}
}
Which allows me to assert this:
Assert.AreEqual(x.StringProperty, "something");
The only thing I don't really like about this is that it's not clear (without a comment) when you are just looking at Class2Test what the purpose of the internal property is.
Additional thoughts would be greatly appreciated.
In your edit, you now have a dependancy on ConfigurationManager that is hard to test.
One suggestion is to extract an interface to it and then make the Class2Test ctor take an IConfigManager instance as a parameter. Now you can use a fake/mock object to set up its state, such that any methods that rely on Configuration can be tested to see if they utilize the correct values...
public interface IConfigManager
{
string FooSetting { get; set; }
}
public class Class2Test
{
private IConfigManager _config;
public Class2Test(IConfigManager configManager)
{
_config = configManager;
}
public void methodToTest()
{
//do something important with ConfigManager.FooSetting
var important = _config.FooSetting;
return important;
}
}
[TestClass]
public class When_doing_something_important
{
[TestMethod]
public void Should_use_configuration_values()
{
IConfigManager fake = new FakeConfigurationManager();
//setup state
fake.FooSetting = "foo";
var sut = new Class2Test(fake);
Assert.AreEqual("foo", sut.methodToTest());
}
}

Categories