To mock an object, does it have to be either implementing an interface or marked virtual? - moq

or can the class be implementing an abstract class also?

To mock a type, it must either be an interface (this is also called being pure virtual) or have virtual members (abstract members are also virtual).
By this definition, you can mock everything which is virtual.
Essentially, dynamic mocks don't do anything you couldn't do by hand.
Let's say you are programming against an interface such as this one:
public interface IMyInterface
{
string Foo(string s);
}
You could manually create a test-specific implementation of IMyInterface that ignores the input parameter and always returns the same output:
public class MyClass : IMyInterface
{
public string Foo(string s)
{
return "Bar";
}
}
However, that becomes repetitive really fast if you want to test how the consumer responds to different return values, so instead of coding up your Test Doubles by hand, you can have a framework dynamically create them for you.
Imagine that dynamic mocks really write code similar to the MyClass implementation above (they don't actually write the code, they dynamically emit the types, but it's an accurate enough analogy).
Here's how you could define the same behavior as MyClass with Moq:
var mock = new Mock<IMyInterface>();
mock.Setup(x => x.Foo(It.IsAny<string>())).Returns("Bar");
In both cases, the construcor of the created class will be called when the object is created. As an interface has no constructor, this will normally be the default constructor (of MyClass and the dynamically emitted class, respectively).
You can do the same with concrete types such as this one:
public class MyBase
{
public virtual string Ploeh()
{
return "Fnaah";
}
}
By hand, you would be able to derive from MyBase and override the Ploeh method because it's virtual:
public class TestSpecificChild : MyBase
{
public override string Ploeh()
{
return "Ndøh";
}
}
A dynamic mock library can do the same, and the same is true for abstract methods.
However, you can't write code that overrides a non-virtual or internal member, and neither can dynamic mocks. They can only do what you can do by hand.
Caveat: The above description is true for most dynamic mocks with the exception of TypeMock, which is different and... scary.

From Stephen Walther's blog:
You can use Moq to create mocks from both interfaces and existing classes. There are some requirements on the classes. The class can’t be sealed. Furthermore, the method being mocked must be marked as virtual. You cannot mock static methods (use the adaptor pattern to mock a static method).

Related

How to decorate objects created by a custom factory using .NET Core DI?

Given I have a factory class responsible for constructing instances of a certain service that has constructor parameters that can only be resolved at runtime, is there a way to leverage container-driven decoration?
Consider the following class which relies on a parameter that is only defined at runtime:
interface IFooService
{
void DoServicyStuff();
}
class MyFooService : IFooService
{
public MyFooService(string somePeskyRuntimeArgument)
{
this.peskyValue = somePeskyRuntimeArgument;
}
public void DoServicyStuff()
{
// do some stuff here with the peskyValue...
}
}
Since the value can only be provided at runtime, we need to move away from the constructor injection and into a method-level parameter passing. This is commonly achieved using a factory implementation like this:
interface IFooServiceFactory
{
IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter);
}
class FooServiceFactory : IFooServiceFactory
{
public IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return new MyFooService(heyItsNowAMethodLevelPeskyParameter);
}
}
While this works fine if the intent is to just abstract away the construction of the service, it poses a challenge to decorate the IFooService instance.
For scenarios where no runtime parameter is involved, this can be easily achieved by tapping into the container to provide our service for us. The example below uses the Scrutor library to decorate the interface with a logging decorator implementation:
class FooServiceFactory : IFooServiceFactory
{
private readonly IServiceProvider serviceProvider;
public FooServiceFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider
}
public IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return this.serviceProvider.GetRequiredInstance<IFooService>();
}
}
...
services
.AddTransient<IFooService, MyFooService>()
.AddTransient<IFooServiceFactory, FooServiceFactory>()
.Decorate<IFooService, LoggingFooService>();
But since MyFooService takes a primitive value as an argument, we cannot rely on GetRequiredService<T> to obtain the instance, as it will fail to find "a registration for string" when building the concrete class.
Similarly, changing the factory to rely on ActivatorUtilities's .CreateInstance or .CreateFactory methods will end up creating the objects while completely ignoring the container registrations, thus leaving us without any decorator.
I know I have at least 2 options to decorate the objects manually, namely:
Using the factory itself to manually create the decorator:
public IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return new LoggingService(
new MyFooService(heyItsNowAMethodLevelPeskyParameter));
}
Using a factory decorator to inject a decorator after the instance is created:
abstract class FooServiceFactoryDecorator : IFooServiceFactory
{
private readonly IFooServiceFactory fooServiceFactory;
protected FooServiceFactory(IFooServiceFactory fooServiceFactory)
{
this.fooServiceFactory = fooServiceFactory;
}
public virtual IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return this.fooServiceFactory.CreateService(heyItsNowAMethodLevelPeskyParameter);
}
}
class LoggingFooServiceFactory : FooServiceFactoryDecorator
{
private readonly IFooServiceFactory fooServiceFactory;
public FooServiceFactory(IFooServiceFactory fooServiceFactory)
{
this.fooServiceFactory = fooServiceFactory;
}
public override IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return new LoggingFooService(
this.fooServiceFactory.CreateService(heyItsNowAMethodLevelPeskyParameter));
}
}
...
services
.AddTransient<IFooServiceFactory, FooServiceFactory>()
.Decorate<IFooServiceFactory, LoggingFooServiceFactory>()
Neither of these allows me to directly use .Decorate on top of the service interface. The first option works but is heavily coupled (meaning I'd have to keep changing it if I want to add other decorators into the mix), while the second version is less coupled, but still forces me to writing one factory decorator per service decorator and thus leads into a much more complex solution.
Another pain point is dependencies on the decorators themselves (for example, ILogger<T> on the LoggingFooService), which I could potentially solve by leveraging ActivatorUtilities to create the decorators instead of newing them up manually.
I could also potentially generalize the "factory decorator" so that the decoration function is parameterized and thus the class can be reused, but it is still very convoluted and hard to maintain, while also not providing as good a syntax for consumers to add new decorators.
class DecoratedFooServiceFactory<TDecorator> : FooServiceFactoryDecorator
where TDecorator : IFooService
{
private readonly IFooServiceFactory fooServiceFactory;
private readonly IServiceProvider serviceProvider;
public FooServiceFactory(
IFooServiceFactory fooServiceFactory,
IServiceProvider serviceProvider)
{
this.fooServiceFactory = fooServiceFactory;
this.serviceProvider = serviceProvider;
}
public override IFooService CreateService(string heyItsNowAMethodLevelPeskyParameter)
{
return ActivatorUtilities.CreateInstance<TDecorator>(
this.serviceProvider,
this.fooServiceFactory.CreateService(heyItsNowAMethodLevelPeskyParameter));
}
}
...
services
.AddTransient<IFooServiceFactory, FooServiceFactory>()
.Decorate<IFooServiceFactory, DecoratedFooServiceFactory<LoggingFooService>>()
And finally, if I ever want to move away from using a factory and want to change to using the service directly, this will cause a significant setup change where I'd then have to configure all the decorators again in the container directly instead of just removing the factory registration as one normally would do.
How can I use a factory like this, while still keeping the capability of configuring decorators at the container level using the simple Scrutor syntax?
Ok, a couple of disclaimers first:
I agree with Steven here in that this looks like an anti-pattern and you will probably be better off redesigning your code to not require run-time values on service construction.
I additionally want to caution against using scrutor-like Decorate. While much less confident in this than in the first point, I believe hiding logging in decorators is much less convenient in the long run than it seems at first. Or at least that's what I saw after about a year of trying them out.
That said, let's see what can be done.
First, let's put some constraints on where the value is coming from. Specifically, let's say we can have a service providing that value, that looks like this:
public interface IValueProvider
{
string Get();
}
This actually allows us to have quite a bit of range. Implementation of that interface can:
Get value from external API - once or periodically in the background. It can even call it every time Get is called, but this is a very bad idea, as it will make construction asynchronous.
Get value that is stored in memory and allow some other service to update it. Say, expose a 'configuration' endpoint where a user can set a new value every once in a while.
Calculate the value based on some algorithm of your choice.
Once you have this service, you can register it like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IValueProvider, AwesomeValueProvider>();
services.AddSingleton<IFooServiceFactory, FooServiceFactory>();
services.AddTransient<IFooService>(sp =>
{
var factory = sp.GetRequiredService<IFooServiceFactory>();
var valueProvider = sp.GetRequiredService<IValueProvider>();
return factory.Create(valueProvider.Get());
});
}
Hope this helps

What are my options to force users of my API to implement a static method?

I am currently using the BLoC pattern to implement firebase/firestore functionality. It seems common to implement a model, an entity (which is basically the model hold by the database) and a repository which handels requests of the program.
To convert the model into the entity and vice versa the model requires a toEntity and fromEntity method. I want my class to look like this:
#immutable
abstract class DatabaseModel {
final id;
DatabaseEntity toEntity();
DatabaseModel({#required this.id});
static DatabaseModel fromEntity(DatabaseEntity entity);
}
However, this is not possible. Dart does not allow static methods without a function body as mentioned in Can one declare a static method within an abstract class, in Dart?, based on the fact that static methods aren't inherited anyways.
I thought about implementing the fromEntity method as a member method of DatabaseModel model with an additional static method which calls the member method, like this:
abstract class DatabaseModel {
final id;
DatabaseEntity toEntity();
DatabaseModel({#required this.id});
static DatabaseModel createFromEntity(DatabaseEntity entity, DatabaseModel instance) {
return instance.fromEntity(entity);
}
DatabaseModel fromEntity(DatabaseEntity entity);
}
But because of the following drawbacks I decided against using this method:
The inheriting class cannot longer be #immutable
Creating a new instance is not really straight forward since e.g. an object of class YouTubeComment would be instantiated like this - DatabaseModel.createFromEntity(entity, YouTubeComment()).
This requires the inheriting class to implement an empty constructor to create the instance.
Since it is not possible to implement a static method or an appropriate constructor, Is there a way to signal the developer that it is intended to implement a static method?

Using Unity to load plug-in providers in Web API

I was looking at another question:
Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?
Everyone scolded the person asking the question for 'doing it wrong'. But if you look at all the examples and sites describing this, they all describe injecting an interface into a Controller, typically via the constructor.
The problem here is that suppose I have a Web API which, for example returns a phrase in a different language:
http://mywebapi/api/SayHello/FR
The FR tells the WebAPI that we want Hello in French. I could easily use English, Chinese or any other language.
Now, I decide to build a set of Assemblies, one for each language, all implementing an interface called ILanguage. I make a Unity Container, put named type mappings in the config file (resolving the ILanguage interface with "FR" would return a ILanguage implemented by the French assembly, etc).
The code does NOT know when it's called WHICH implementation it's going to get. Injecting an ILanguage implementation into the Controller constructor seems wrong. Only when the URL is parsed and we get into the method do we see the "FR" parameter passed in, and that tells us to call:
container.Resolve<ILanguage>("FR")
to get the correct ILanguage interface for calling to return the appropriate phrase.
A dogmatic "never call container.Resolve" in your code anywhere, sounds very nice and purist, but it doesn't solve this problem. So, what is the recommended approach? It looks a lot like a ServiceLocator in the sense that we want to find a service dynamically using a 'key' of some kind, but I certainly do NOT want my Web API controller assembly having direct knowledge of all these little language assemblies. I have this working using the system above, but I'm wondering what all the DI/IoC purists would say about this code, and if they don't like it, how they solve the 'dynamic plug-in' problem in a Web API Controller.
I would recommend making your controllers accept a language factory (i.e. a Func<string, ILanguage>) that returns the ILanguage implementation based on the language code you pass into it.
The reason that a factory function should be favored over not declaring any dependencies in your constructor and instead calling container.Resolve() is that the latter obscures the fact that you depend on ILanguage, whereas taking a dependency on a Func<string, ILanguage> makes this very clear.
I.e.:
public interface ILanguage
{
string SayHello();
}
public class Program
{
public static void Main(string[] args)
{
UnityContainer container = new UnityContainer();
container.RegisterType<Func<string, ILanguage>>(new InjectionFactory(con => LanguageFactory));
//Use it:
MyController controller = container.Resolve<MyController>();
string result = controller.TalkToMe("en");
}
private static Func<string, ILanguage> LanguageFactory = delegate(string languageCode)
{
//Create the correct ILanguage here based on the languageCode.
//It's OK to call container.Resolve() here, for example to
//resolve named instances.
return (ILanguage)null;
};
}
public class MyController
{
private Func<string, ILanguage> _languageFactory;
public MyController(Func<string, ILanguage> languageFactory)
{
_languageFactory = languageFactory;
}
public string TalkToMe(string languageCode)
{
ILanguage language = _languageFactory(languageCode);
return language.SayHello();
}
}
As an alternative, you could also use the IUnityContainer that you get passed into the InjectionFactory to do the resolving in the language factory:
container.RegisterType<Func<string, ILanguage>>(new InjectionFactory(con => CreateLanguageFactory(con)));
//...
private static Func<string, ILanguage> CreateLanguageFactory(IUnityContainer container)
{
return delegate(string languageCode)
{
//Create the correct ILanguage here based on the languageCode.
ILanguage result = container.Resolve<ILanguage>(languageCode);
return result;
};
}

Handling specimen creation inconsistencies between AutoFixture and Moq

I am using AutoMoqCustomization in my test conventions.
Consider the code below. Everything works great until I add a constructor to one of the concrete classes. When I do, I get "could not find a parameterless constructor". We know AutoFixture doesn't have an issue with the constructor because it delivered me the test object one which proved to be assignable from IThings... no failure there. So it must be moq.
This makes some sense because I assume builder was generated by moq and passed into the GetCommands method. So I think I can see that control has been passed from AutoFixture to moq at that point.
That takes care of the why, but what should I do about it? Is there a way to instruct moq on how to deal with the ThingOne or is there a way to instruct AutoFixture to ignore moq for IThingBuilders and instead do something Fixtury?
public class TestClass
{
public interface IThingBuilders
{
T1 Build<T1>() where T1 : IThings;
}
public interface IThings
{
}
public class ThingOne : IThings
{
public ThingOne(string someparam)
{
}
}
public class ThingTwo : IThings
{
}
public class SomeClass
{
public List<IThings> GetCommands(IThingBuilders builder)
{
var newlist = new List<IThings>();
newlist.Add(builder.Build<ThingOne>());
newlist.Add(builder.Build<ThingTwo>());
return newlist;
}
}
[Theory, BasicConventions]
public void WhyCannotInstantiateProxyOfClass(ThingOne one, ThingTwo two, IThingBuilders builder, SomeClass sut)
{
Assert.IsAssignableFrom<IThings>(one);
Assert.IsAssignableFrom<IThings>(two);
var actual = sut.GetCommands(builder);
Assert.Equal(1, actual.OfType<ThingOne>().Count());
Assert.Equal(1, actual.OfType<ThingTwo>().Count());
}
}
As there's no extensibility point in Moq that enables AutoFixture to hook in and supply a value of ThingOne, there's not a whole lot you can do.
However, you can use the SetReturnsDefault<T> method of Moq. Modifying the above test would then be like this:
[Theory, BasicConventions]
public void WhyCannotInstantiateProxyOfClass(
ThingOne one, ThingTwo two, IThingBuilders builder, SomeClass sut)
{
Assert.IsAssignableFrom<IThings>(one);
Assert.IsAssignableFrom<IThings>(two);
Mock.Get(builder).SetReturnsDefault(one); // Add this to make the test pass
var actual = sut.GetCommands(builder);
Assert.Equal(1, actual.OfType<ThingOne>().Count());
Assert.Equal(1, actual.OfType<ThingTwo>().Count());
}
This is a bit easier than having to write a specific Setup/Returns pair, but not much. You could move that code to an AutoFixture Customization, but again, since this is a generic method on a a Mock instance, you'll explicitly need to call this for e.g. ThingOne in order to set the default for that return type. Not particularly flexible.

How to allow client pass my object through webservice?

Sorry if this is stupid question, because I'm a bit confused about .NET remoting and distributed object.
I want to write a webservice, and in one of its methods, I want user to pass one my object's instance as parameter. It will greatly reduces number of parameters, and help user call this method more effectively. I create some class, but when distributing them to client, only class name remains, all properties and methods are gone, just like this
public class CameraPackages
{
private readonly List<CameraPackage> _packages;
public CameraPackages()
{
_packages = new List<CameraPackage>();
}
public void AddNewCamera(CameraPackage package)
{
_packages.Add(package);
}
public void RemoveCamera(CameraPackage package)
{
if(_packages.Contains(package))
_packages.Remove(package);
else
throw new ArgumentException();
}
}
into this: (in Reference.cs)
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "2.0.50727.3082")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/")]
public partial class CameraPackages {
}
How can I do to allow user use my object?
Thank you so much.
Web Services will only serialise public properties, so you can't do that (in that way) using web services.
You will need to manage your list of objects client side, then send the data in a transfer object (a class with just properties).
Have a look at this.

Resources