I have some troubles with mocking of a local variable in a method of my class.
I try to mock my Worker class but it calls a method that returns null value and my context variable becomes null. Thereby I get an exception when try to get the Name property.
How to force CreateWorkerContext() to return mock values? May be there is a way to mock a local variable (context)?
Thanks!
My code will tell more about the problem:
namespace Moq
{
class Program
{
static void Main(string[] args)
{
var workerMock = new Mock<Worker>();
workerMock.Object.GetContextName();
}
}
public class Worker
{
public string GetContextName()
{
// something happens and context does not create (imitated situation)
WorkerContext context = CreateWorkerContext();
// exception because _context is null
return context.Name;
}
private WorkerContext CreateWorkerContext()
{
// imitate that context is not created
return null;
}
}
public class WorkerContext
{
public string Name { get; set; }
}
}
A few things are arguable here.
First, - but this is just my opinion - you should avoid having partial mocking (partial mocking = mock an abstract class that doesn't implement an interface, and therefore, keeps the original implementation of the methods which weren't mocked.). The best would be to have an IWorker interface which Worker would imlepement.
Second - I would create strict mocks. Loose mocks seem like a nice shortcut, but often will let your methods and properties return the default value when you don't intend to (null in your case)
Third - I would Inject WorkerContext. If you can't inject it because you need to parametrize it with come .ctor arguments, then inject a WorkerContextFactory which will allow you to mock the creation and parametrization of your WorkerContext
Dynamic mock libraries like Moq are, in general, not magic. They can only replace the behaviour that you yourself could replace with code.
In this particular example, Moq can't replace CreateWorkerContext because it's a private method.
One option is to make it virtual:
public class Worker
{
public string GetContextName()
{
WorkerContext context = CreateWorkerContext();
return context.Name;
}
public virtual WorkerContext CreateWorkerContext()
{
return new WorkerContext();
}
}
Another option would be to replace the CreateWorkerContext method with a Strategy:
public class Worker
{
private readonly IWorkerContextFactory factory;
public Worker(IWorkerContextFactory factory)
{
if (factory == null)
throw new ArgumentNullException(nameof(factory));
this.factory = factory;
}
public string GetContextName()
{
WorkerContext context = this.factory.Create();
return context.Name;
}
}
Both of these options would enable Moq to simulate the desired behaviour.
Related
I have class MyService that depends on ABCService (Nuget package/sdk)
public class MyService
{
private readonly ABCService _abc;
public MyService(ABCService abc)
{
this._abc = abc;
}
public async Task Run(string id)
{
// some logic
var result = await this._abc.DoSomething(id);
// some logic
}
}
ABCService looks something like this:
public class ABCService
{
internal ABCService(string someConnectionString, object someSettings)
{
// ... initialization
}
public static CreateFromConnectionString(string someConnectionString, object someSettings)
{
// some logic
return new ABCService(someConnectionString, someSettings);
}
}
Mocking class this way would not work and throws exception. "Parent does not have a default constructor."
var mock = new Mock<ABCService>();
var myService = new MyService(mock.Object);
How should I approach this? Is there a way to mock such classes?
The only thing that comes to my mind is creating interface IABCService and then injecting it in the constructor of MyService
public class IABCService
{
Task DoSomething(string id);
}
public class MyService
{
private readonly IABCService _abc;
public MyService(IABCService abc)
{
this._abc = abc;
}
}
And then I could do this:
var mock = new Mock<IABCService>();
var myService = new MyService(mock.Object);
Popular isolation frameworks such as Moq, NSubstitute or FakeItEasy are constrained. They can substitute only virtual methods. To use them, you will have to use the interface, as you already guessed. This is the recommended way to easily maintain loose coupling and testability.
There are bunch of unconstrained mocking frameworks: TypeMock Isolator, JustMock, Microsoft Fakes (all three are paid) and free open source Prig, Pose, Shimmy, Harmony, AutoFake, Ionad.Fody, MethodRedirect. They allow to mock non-virtual members, including private, static, etc.
Some of them allow you to work wonders, but you should not get too carried away with using them, because in the end it can lead to bad architecture.
As the title suggests, it is possible to determine which instance of a class a particular instance of another class is instantiated from?
Update: Example Code below
class FooBar: Foo
{
private Context context;
public FooBar(Context _context): base(_context)
{
this.context = _context;
}
}
class Foo
{
public Baz baz;
private Context context;
public Foo(Context _context)
{
baz = new Baz();
this.context = _context;
}
}
class Baz
{
public Baz()
{
GetNameOfCaller()
}
private void GetNameOfCaller()
{
....
....
_className = ....;
}
private string _className;
}
Yes, you can do that for constructors the same way as for regular methods. Just use the CallerMemberName to pass in the name of the calling method. You won't have the class name with it, then you need to walk the StackTrace which is much more complicated.
public class X
{
public X([CallerMemberName] string caller = null)
{
this.Caller = caller;
}
public string Caller { get; private set; }
}
Then just call this. The compiler will fill in the caller parameter for you:
static void Main(string[] args)
{
X x = new X();
Console.WriteLine($"Caller = {x.Caller}"); // prints Main
}
You could use System.Diagnostics.StackTrace:
public class Foo
{
public void MethodBah()
{
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
MethodBase callingMethod = t.GetFrame(1).GetMethod();
Type callingMethodType = callingMethod.DeclaringType;
string className = callingMethodType.Name;
}
}
Works even in .NET 1.1.
With your (updated) example you have to use t.GetFrame(2).GetMethod() instead of GetFrame(1) to get FooBar instead of Foo because the child- calls the parent constructor.
I believe that your requirement should be solved using aspect-oriented programming.
OP said in some comment:
[..] Logging purposes for now but may not be limited to it alone [...]
For example, there's an extremely powerful tool called PostSharp which lets you intercept any method call, when it's being called and after it was called:
[Serializable]
public class LogAspect : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
}
public override void OnExit(MethodExecutionArgs args)
{
}
}
Now you can apply the whole aspect as a regular attribute to a method, class or even to an assembly (thus, all methods within the assembly will be loggable).
You can access called method through MethodExecutionArgs.Method (which is of type MethodBase, and this means that you can access which type declares the whole method through MethodBase.DeclaringType.
With a tool like PostSharp you are adding an extra compilation step, but it has the great advantage that your interceptions are injected during compile-time. That is, it will perform like adding the whole code manually in every method.
You can also implement the same thing creating run-time proxies using Castle DynamicProxy to intercept method calls.
I have this situation: An azure cloud service that uses an external DLL and makes API calls. This DLL has an abstract class that has a static method to return a subclass reference I need to use to make the API calls.
Now for testing purposes, we run the cloud service in an emulator and run our unit tests. But we don't want to make that API call to the external system. We need to intercept it somehow. I have spent the better part of yesterday trying to see if I could do some dependency injection (unity) to do this but needless to say, no luck.
The abstract class exposing a static method to get an instance of a subclass to actually make the API call is probably the most restrictive of scenarios.
Below is some decompiled & cleaned up code to show the relevant pieces.
public abstract class EntityManager : System.Object
{
private static object lockObject;
private static Dictionary<System.Type, EntityManager> entityManagers;
private bool isSingleton;
public enum EntityManagerInstanceType : int
{
SingletonInstance = 0,
NewInstance = 1,
}
static EntityManager() { }
protected EntityManager() { }
public static T GetEntityManager<T>(EntityManagerInstanceType instanceType) where T : EntityManager
{
T item;
System.Type type = typeof(T);
T t = default(T);
lock (EntityManager.lockObject)
{
if (instanceType != EntityManagerInstanceType.SingletonInstance || !EntityManager.entityManagers.ContainsKey(type))
{
t = (T)System.Activator.CreateInstance(type, true);
try
{
t.isSingleton = instanceType == EntityManagerInstanceType.SingletonInstance;
}
catch (Exception adapterException)
{
throw;
}
if (instanceType == EntityManagerInstanceType.SingletonInstance)
{
EntityManager.entityManagers[type] = t;
}
return t;
}
else
{
item = (T)EntityManager.entityManagers[type];
}
}
return item;
}
protected object ProcessRequest(string methodName, object request) { return new object(); }
}
public class PersonaEntityManager : EntityManager
{
protected PersonaEntityManager() { }
public PersonaResponseData UpdatePersona(PersonaUpdateRequestData requestData)
{
return (PersonaResponseData)base.ProcessRequest("Mdm.UpdatePersona", requestData);
}
}
public class PublisherWorkerRole : RoleEntryPoint
{
public bool UpdatePersona(PersonaUpdateRequestData contact, string MessageId)
{
PersonaEntityManager mgr = EntityManager.GetEntityManager<PersonaEntityManager>(EntityManager.EntityManagerInstanceType.NewInstance);
var resp = mgr.UpdatePersona(contact);
return resp != null;
}
}
What is the ideal approach in this scenario? Is this even testable short of setting up our own mock API and changing the application config for test to call our mock API instead?
Let me know if you need me to elaborate on this further.
One approach is to use something like ms shims or typemock to mock out the static call. This would reduce the impact to your production code, but if you're not already using them may require a financial investment. These libraries are able to intercept calls that other mocking frameworks can't so in addition to allowing you mock static calls, they would also allow you to create mock versions of the PersonaEntityManager which you would also need.
As you've mentioned in your comment below, the following approach doesn't work because you need to be able to Mock the PersonaEntityManager class so that you can intercept the call to UpdatePersona, which as it's not virtual standard mocking frameworks can't do. I've left the approach below for completeness, since it is the approach I would typically use to isolate a static dependency.
If you don't mind modifying your production code is to isolate the dependency behind a wrapper class. This wrapper class can then be injected into your code in the normal way.
So you would end up with some wrapper code something like this:
public interface IEntityManagerWrapper {
T GetEntityManager<T>(EntityManager.EntityManagerInstanceType instanceType) where T : EntityManager;
}
public class EntityManagerWrapper : IEntityManagerWrapper {
public T GetEntityManager<T>(EntityManager.EntityManagerInstanceType instanceType) where T : EntityManager {
return EntityManager.GetEntityManager<T>(instanceType);
}
}
The IEntityWrapper can be setup to be injected using Unity and then mocked using your mocking framework of choice to return mock instances of the other classes you depend on like PesonaEntityManager.
So, your production code would look like this:
public class MyProductionCode{
private IEntityManagerWrapper _entityManager;
public MyProductionCode(IEntityManagerWrapper entityManager) {
_entityManager = entityManager;
}
public void DoStuff() {
PersonaEntityManager pem = _entityManager.GetEntityManager<PersonaEntityManager>(EntityManager.EntityManagerInstanceType.NewInstance);
var response = pem.UpdatePersona(new PersonaUpdateRequestData());
}
}
And the test code would have looked like this (assuming you're using Moq):
[Test]
public void TestSomeStuff() {
var em = new Mock<IEntityManagerWrapper>();
var pe = new Mock<PersonaEntityManager>();
pe.Setup(x => x.UpdatePersona(It.IsAny<PersonaUpdateRequestData>())).Returns(new PersonaResponseData());
em.Setup(x=>x.GetEntityManager<PersonaEntityManager>(It.IsAny<EntityManager.EntityManagerInstanceType>())).Returns(pe.Object);
var sut = new MyProductionCode(em.Object);
sut.DoStuff();
}
The EntityWrapper class itself is pretty trivial, so I would tend to test it as an integration point, so use integration level testing to ensure it works both when it is written and if it is ever changed.
Hmm how about creating a proxy for that service. Expose necessary interface through proxy and inject provider (mocked or orginal) to it.
I am writing Unit tests for the following class legacy class
Class myLegacyClassPresenter
{
private MethodA(){}
private propertyA {get; set;}
private MethodB(YearValue value){}
//some more properties & method goes here
private struct YearValue
{
public static int One { get { return 365; } }
public static int Two { get { return 730; } }
}
}
Here is my unit test.
public void mytest()
{
//some initializations
var view = myLegacyView();
var service = new Mock<ILegacyService>();
var presenter = new myLegacyClassPresenter(view, service);
var privateObject = new PrivateObject(presenter);
//I can access all private methods and properties as follows
privateObject.invoke("MethodA");
privateObject.GetProperty("propertyA")
// But How can I get the the Struct Year value to pass to MethodB
privateObject.Invoke("MethodB", new object[]{YearValue.One}); //Compile Error for YearValue
//I can't change in the class, One way is to define the same struct locally, Is there any other approach we can have to achieve the same result.
}
Classic example which shows how if you cannot unit test a particular component, REFACTOR the component!
This is where is love what any mocking framework enforces you to do - write decoupled code.
Couple of things:
Testing private methods should be seriously reconsidered. You break encapsulation the moment you test private methods and properties.
In your example, the myLegacyClassPresenter class is very tightly coupled with the YearValue struct. You could decouple it using dependency injection.
If you want to create an instance of the struct you can use something like the following
var theType = Type.GetType("MyNamespace.myLegacyClassPresenter+YearValue");
var parameter = Activator.CreateInstance(theType);
privateobject.Invoke("MethodB", new object[]{parameter});
If you need to pass in YearValue.One, then theType.GetMember() can be used to get the value.
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/