Moq a proxy for unit testing - c#

I'm new to using Moq and I cannot find the way for doing this.
I've a generateId private method, called
/// <summary>
/// Generates a call Id for external interfaces
/// </summary>
/// <returns></returns>
private string GenerateCallId()
{
return "EX" + SharedServicesClientProxy.Instance.GenerateId().ToString();
}
I wanted to unit test this method, and for that reason i need to mock the Proxy.
SharedServicesClientProxy is just an object that implements the interface ISharedServices but adds the singleton. I wanted to test that all the strings correctly returned a string starting with "EX". this is my unit test, using Moq
/// <summary>
/// A test for GenerateCallId
/// A CallId for external systems should always start by "EX"
///</summary>
[TestMethod()]
[DeploymentItem("myDll.dll")]
public void GenerateCallIdTest()
{
myService_Accessor target = new myService_Accessor();
var SharedServicesClientProxy = new Mock<ISharedServices>();
SharedServicesClientProxy.Setup(x => x.GenerateId()).Returns(5396760556432785286);
string actual;
string extCallIdPrefix = "EX";
actual = target.GenerateCallId();
Assert.IsTrue(actual.StartsWith(extCallIdPrefix));
}
I guess I'm doing my mock in the wrong place?
In a more general way, how do i mock an object that is going to be called by the method I'm testing?
for eg:
/// <summary>
/// dummy test
///</summary>
[TestMethod()]
[DeploymentItem("myDll.dll")]
public void Foo()
{
myService_Accessor target = new myService_Accessor();
boolexpected = false;
actual = target.Foo();
Assert.IsTrue(actual,expected);
}
/// <summary>
/// Foo
/// </summary>
/// <returns></returns>
private bool Foo()
{
return this.Bar();
}
I need to moq Bar, but where do i need to do it?
Thanks,
Seb

Search for the term "Dependency Injection" before proceeding.
You have a dependency on SharedServicesClientProxy.Instance, which is a Singleton. This will cause problems with test isolation, since you will reuse the same instance across tests and be prone to state-leftover issues.
I'd advise to inject dependencies like this (and OT- you shouldn't be testing private methods... test via the public interface. There it is out of my system..:)
public class AnonClass
{
ISharedServices _sharedServices;
AnonClass(ISharedServices sharedServicesObj)
{
_sharedServices = sharedServicesObj;
}
public string GenerateCallId()
{
return "EX" + _sharedServices.GenerateId().ToString();
}
}
Rewire your current code to create the target class like this
var class = new AnonClass(SharedServicesClientProxy.Instance);
In your test, pass in the mock object instead of the object returned by the Singleton

Related

Unit Testing using Moq and Autofac

I have the following logger logger class and I want to know the best to unit testing it.
Some observations:
I needed to create the interface IFileWrapper in order to break dependency with System.IO dependency and been able to user dependency injection (Autofac)
I was able to unit testing the method FileWrapper.WriteLog by implementing IFileWrapper using a MemoryString but if I wanted to test a expected behavior inside the method I won't be able (e.g: throwing exceptions, incorrect path and filename, etc.)
/// <summary>
/// Creates an instance of type <see cref="FileLogger"/>
/// </summary>
/// <remarks>Implements the Singleton Pattern</remarks>
private FileLogger()
{
FileName = string.Format("\\{0: MMM dd, yy}.log", DateTime.Now);
Path = Environment.CurrentDirectory;
FileWrapper = ContainerBuilderFactory.Container.Resolve<IFileWrapper>();
}
/// <summary>
/// Log the <paramref name="Message"/> in the <paramref name="Path"/> specified.
/// The <paramref name="UserName"/>, <paramref name="Host"/> must be supplied
/// </summary>
/// <example>
/// <code>
/// var handler = new LoggerHandlerFactory();
/// var logger = handler.GetHandler<FileLogger>();
/// logger.Log("Hello CSharpLogger");
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="SecurityException"></exception>
/// <exception cref="DirectoryNotFoundException"></exception>
/// <exception cref="UnauthorizedAccessException"></exception>
/// <exception cref="PathTooLongException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="FormatException"></exception>
public void Log(string message, LogLevel level = LogLevel.INFO)
{
lock (_current)
{
var configLevel = CSharpLoggerConfiguration.Configuration.GetLogLevel();
if (configLevel != LogLevel.OFF & level != LogLevel.OFF && configLevel >= level)
{
try
{
FileWrapper.WriteLog(string.Concat(Path, FileName), message, level);
}
catch (CSharpLoggerException)
{
throw;
}
}
}
}
So, I created the following UnitTesting using Moq:
//arrange
CSharpLoggerConfiguration.Configuration.SetLogLevel(LogLevel.DEBUG);
var mock = new Mock<IFileWrapper>();
mock.Setup(x => x.WriteLog(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<LogLevel>()));
logger.FileWrapper = mock.Object;
//act
logger.Log("Hello CSharpLogger", LogLevel.DEBUG);
logger.Log("Hello CSharpLogger", LogLevel.WARN);
//assert
mock.Verify(x => x.WriteLog(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<LogLevel>()), Times.Exactly(2));
So far so good. What I'm not confortable is with this line: logger.FileWrapper = mock.Object; I would like to keep FileWrapper propety private.
Any advise is welcome.
I'll be publishing the code http://csharplogger.codeplex.com/ in case you want more details.
Use constructor injection. In short; instead of providing the service (in this case the file wrapper) by setting a property, make the logger have a public constructor which takes an IFileWrapper argument.
public class Logger
{
public Logger(IFileWrapper fileWrapper)
{
FileWrapper = fileWrapper;
}
public IFileWrapper FileWrapper { get; }
}
// in your test:
var logger = new Logger(mock.Object);
To answer the question about having a singleton file wrapper more thoroughly, here's a code sample for the application (non-test) code:
public static class FileWrapperFactory
{
private static IFileWrapper _fileWrapper;
public static IFileWrapper GetInstance()
{
return _fileWrapper ?? (_fileWrapper = CreateInstance());
}
private static IFileWrapper CreateInstance()
{
// do all the necessary setup here
return new FileWrapper();
}
}
public class StuffDoer
{
public void DoStuff()
{
var logger = new FileLogger(FileWrapperFactory.GetInstance());
logger.WriteLog("Starting to do stuff...");
// do stuff
logger.WriteLog("Stuff was done.");
}
}
Since the FileWrapperFactory maintains a static instance of the file wrapper, you'll never have more than one. However, you can create multiple loggers like that, and they don't have to care. If you, in the future, decide that it's OK to have many file wrappers, the logger code doesn't have to change.
In a real-world application, I'd advice you to choose some kind of DI framework to handle all this book-keeping for you; most have excellent support for singleton instances, doing essentially what the FileWrapperFactory above does (but usually in a more sophisticated and robust way. FileWrapperFactory isnt' thread-safe, for example...).
Since your code comments show that your logger is a singleton, you need a way other than constructor injection for setting the dependency. In his book on Legacy Code, Mike Feathers suggests a function for such purposes, which is adequately named, something like
public void SetInstanceForTesting(IFileWrapper fileWrapper) {...}
Now this function won't hopefully be used for different purposes...

Windsor circular dependency of a transient-lifestyle component

I've got a bunch of classes written like this:
public class MyService1 {
public MyService1(MyService1Settings settings, <service-dependent list of dependencies filled by Windsor>) { ... }
}
which are registered in the Windsor like this:
container.Register(
...
Component.For<MyService1>().LifestyleTransient(),
Component.For<MyService2>().LifestyleTransient(),
...
);
container doesn't have any of the MyServiceXSettings types registered, so the only way to get a service is to resolve it from container like this:
TService service = windsorContainer.Resolve<TService>(new { settings });
The thing is, depending on the parameters in the settings object, one of the services tries to acquire another instance of its type with different settings object.
Something along the lines of:
public class MyService2 {
public MyService2(MyService2Settings settings, <service-dependent list of dependencies filled by Windsor>)
{
this.uplink = settings.Counter == 1
? new AnotherUplink()
: new RecursiveUplink(
container.Resolve<MyService2>(new {
settings = new MyService2Settings(settings.Counter - 1)
});
}
}
This recursive dependency chain is finite (and is about 6 instances deep), but Windsor throws an exception when the first service tries to get another one, stating that it's a circular dependency.
I've advertised all the services as having Transient lifestyles and requesting them with custom parameters. Can I at least specify the maximum allowed depth of the recursion? Or am I missing another way I can do it?
another requirement: I can't use typed factories, because I've got quite many different types of those services, so generating many factory interfaces individually for those services would be undesired.
container doesn't have any of the MyServiceXSettings types registered,
so the only way to get a service is to resolve it from container like
this:
You may also use a dedicated SubResolver or a DependsOn during component registration.
Executing code in a constructor(rather than a simply variable assignement) is a smell, even worst using the container: it should never leak in the application layer.
At the first sight, it seems you are using the settings only to choose the proper component within the constructor: that should be done at CompositionRoot, using a TypedFactory or also by naming convention(you may have multiple component registered for same intercace, but a given parameter name drives the component selection)
As per this answer, I went with lazy resolution.
/// <summary>
/// Represents single component instance producer.
/// </summary>
/// <typeparam name="TComponent">type of the component to create</typeparam>
public interface IComponentCreator<TComponent>
{
/// <summary>
/// Gets the created component.
/// </summary>
TComponent Component { get; }
}
/// <summary>
/// Creates the component only when it's first requested.
/// </summary>
/// <typeparam name="TComponent">type of the component to create</typeparam>
public class LazyCreator<TComponent> : IComponentCreator<TComponent>
{
private readonly Func<TComponent> creatingFunction;
private bool created;
private TComponent component;
public LazyCreator(Func<TComponent> creatingFunction)
{
this.creatingFunction = creatingFunction;
}
public TComponent Component
{
get
{
if (!created)
{
component = creatingFunction();
created = true;
}
return component;
}
}
}
/// <summary>
/// Returns already created component.
/// </summary>
/// <typeparam name="TComponent">type of the component</typeparam>
public class ComponentContainer<TComponent> : IComponentCreator<TComponent>
{
private readonly TComponent component;
public ComponentContainer(TComponent component)
{
this.component = component;
}
public TComponent Component
{
get { return component; }
}
}

AOP Ninject Stop Intercepted Method From Being Called

I'm using Ninject and AOP to do some caching. I have a Attribute that I can apply to any method in my repository and on BeforeInvoke it will return my cached Object if there is one and AfterInvoke create a cached object. This all works great but I can't figure out how to stop initial method from being called, ie if there is a cached object the return that instead of calling a the intyercepted method. My interceptor is here:
public class CacheInterceptor : SimpleInterceptor
{
protected override void BeforeInvoke(IInvocation invocation)
{
Type returnType = invocation.Request.Method.ReturnType;
string cacheKey = CacheKeyBuilder.GetCacheKey(invocation, serializer);
object cachedValue = cache.Get(cacheKey);
if (cachedValue == null)
{
invocation.Proceed();
}
else
{
object returnValue = serializer.Deserialize(returnType, cachedValue);
invocation.ReturnValue = returnValue;
returnedCachedResult = true;
}
}
}
Even though in the else statement I am clearly not saying to call the invoked Method 'invocation.Proceed();' it still invokes it. How do I tell ninject to just return with the invocation.ReturnValue ?
You can't use SimpleInterceptor in this case because that is meant as base class for the most common scenario where you want to do an action before or after the actual method call. Also you are not allowed to call Proceed Instead implement the IInterceptor interface and put your code into the Intercept method.
But probably we should extend SimpleInterceptor in a future version so that you can prevent that the actual method is called:
public abstract class SimpleInterceptor : IInterceptor
{
private bool proceedInvocation = true;
/// <summary>
/// Intercepts the specified invocation.
/// </summary>
/// <param name="invocation">The invocation to intercept.</param>
public void Intercept( IInvocation invocation )
{
BeforeInvoke( invocation );
if (proceedInvocation)
{
invocation.Proceed();
AfterInvoke( invocation );
}
}
/// <summary>
/// When called in BeforeInvoke then the invokation in not proceeded anymore.
/// Or in other words the decorated method and AfterInvoke won't be called anymore.
/// Make sure you have assigned the return value in case it is not void.
/// </summary>
protected void DontProceedInvokation()
{
this.proceedInvocation = false;
}
/// <summary>
/// Takes some action before the invocation proceeds.
/// </summary>
/// <param name="invocation">The invocation that is being intercepted.</param>
protected virtual void BeforeInvoke( IInvocation invocation )
{
}
/// <summary>
/// Takes some action after the invocation proceeds.
/// </summary>
/// <param name="invocation">The invocation that is being intercepted.</param>
protected virtual void AfterInvoke( IInvocation invocation )
{
}
}

Is the Strategy design pattern suitable for logic based on string comparisons?

As of now my code has multiple if else statements branching, depending upon the value of a string. i.e.
if(input == "condition1")
{
// Some logic
}
else if(input =="condition1")
{
// Some other logic
}
I'm planning to use the Strategy Pattern. Is this the right approach? If yes, how can I create the correct Concrete Strategy object depending on the condition?
Thanks
In the code example you have provided, Strategy is not going to get you away from the if conditions you already have. You would end up needing a Factory to create your strategy objects as follows:
static class StrategyFactory
{
static IStrategy CreateStrategy(string input)
{
if (input == "condition1")
{
return new StrategyForCondition1();
}
else if (input == "condition2")
{
return new StrategyForCondition2();
}
}
}
This is why I would not recommend Strategy for your case.
A very elegant alternative solution is to use a Dictionary where the key is the input string value and the Action is the contents of the if statement:
var actions = new Dictionary<string, Action>
{
{"condition1", () => Console.WriteLine("condition1")},
{"condition2", NameOfMethodThatHandlesCondition2}
};
Now, the beauty of this solution is that you use it with only 1 line of code:
actions[input];
See examples here: http://elegantcode.com/2009/01/10/refactoring-a-switch-statement/
One issue in your code sample is that you are comparing to a string... which could be any possible value. If possible, create an enum instead that represents all possible conditions. This will prevent coming up against a string value that you are not anticipating.
Here is a great site with some really good examples of different Pattern types in C#.
Strategy Design Patterns in C# and VB
// Strategy pattern -- Structural example
using System;
namespace DoFactory.GangOfFour.Strategy.Structural
{
/// <summary>
/// MainApp startup class for Structural
/// Strategy Design Pattern.
/// </summary>
class MainApp
{
/// <summary>
/// Entry point into console application.
/// </summary>
static void Main()
{
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyA());
context.ContextInterface();
context = new Context(new ConcreteStrategyB());
context.ContextInterface();
context = new Context(new ConcreteStrategyC());
context.ContextInterface();
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The 'Strategy' abstract class
/// </summary>
abstract class Strategy
{
public abstract void AlgorithmInterface();
}
/// <summary>
/// A 'ConcreteStrategy' class
/// </summary>
class ConcreteStrategyA : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("Called ConcreteStrategyA.AlgorithmInterface()");
}
}
/// <summary>
/// A 'ConcreteStrategy' class
/// </summary>
class ConcreteStrategyB : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("Called ConcreteStrategyB.AlgorithmInterface()");
}
}
/// <summary>
/// A 'ConcreteStrategy' class
/// </summary>
class ConcreteStrategyC : Strategy
{
public override void AlgorithmInterface()
{
Console.WriteLine("Called ConcreteStrategyC.AlgorithmInterface()");
}
}
/// <summary>
/// The 'Context' class
/// </summary>
class Context
{
private Strategy _strategy;
// Constructor
public Context(Strategy strategy)
{
this._strategy = strategy;
}
public void ContextInterface()
{
_strategy.AlgorithmInterface();
}
}
}
Output
Called ConcreteStrategyA.AlgorithmInterface()
Called ConcreteStrategyB.AlgorithmInterface()
Called ConcreteStrategyC.AlgorithmInterface()
Why not just use a switch?
switch (input) {
case "condition1":
// do stuff
break;
case "condition2":
// do stuff....
break;
default:
// default stuff
break;
}
Or failing that use a Dictionary<string,Action>
var actions=new Dictionary<string,Action> { { "condition1", () => {code}}, {"condition2",) => {code}};
Then..
if (actions.ContainsKey(input)) actions[input]();

Return a string from a Service already running using Remoting

im trying to use .Net Remoting to get a value of a variable that i use in a thread of an windows service.
TcpChannel tcpChannel = new TcpChannel(9998);
ChannelServices.RegisterChannel(tcpChannel, false);
Type commonInterfaceType = typeof(MyNameSpace.Core.Engine);
RemotingConfiguration.RegisterWellKnownServiceType(commonInterfaceType,
"CopyFilePercentage",
WellKnownObjectMode.SingleCall);
myEngine = Engine.EngineInstance;
myEngine.Start();
But it seams that every time that i use the Client to get that value, a new thread is created returning an empty string.
Any idea why is this happening or am I doing something wrong?
Thanks in advance,
Miguel de Sousa
WellKnownObjectMode.SingleCall creates a new instance of your class for each call. try WellKnownObjectMode.Singleton
EDIT
Maybe you should read about client activated objects. Turn your singleton object to a class factory and return a new instance of a real worker class(ofcourse inheriting from MarshalByRefObject) which will be used by the client.
so your client will be something like this
var worker = client.GetWorkerClass();
worker.GetSomeData();
and you will have one server object per connection (this may not be the correct terminology).
well i just used a Global Variable Class not really what I wanted but does the job.
/// <summary>
/// Contains global variables for project.
/// </summary>
public static class GlobalVar
{
/// <summary>
/// Global variable that is constant.
/// </summary>
public const string GlobalString = "Important Text";
/// <summary>
/// Static value protected by access routine.
/// </summary>
static int _globalValue;
/// <summary>
/// Access routine for global variable.
/// </summary>
public static int GlobalValue
{
get
{
return _globalValue;
}
set
{
_globalValue = value;
}
}
/// <summary>
/// Global static field.
/// </summary>
public static bool GlobalBoolean;
}

Categories