I want to create generic Unit Test classes for Services. My base class is as generic as possible and I wanna pass the Service constructor as a parameter to my base class from the derived class, but I don't no how to do it in C#.
public interface IBaseServiceUnitTest<TEntity> where TEntity : BaseEntity
{
//...some methods
}
public class BaseServiceUnitTest<TEntity> : IBaseServiceUnitTest<TEntity> where TEntity : BaseEntity
{
private IBaseService<TEntity> _service;
public BaseServiceUnitTest(Constructor ctor)
{
_service = ctor();
}
//...implemented methods from IBaseServiceUnitTest
}
public class CustomEntityServiceUnitTest : BaseServiceUnitTest<CustomEntity>
{
public CustomEntityServiceUnitTest()
: base(Constructor ctor)
}
I think a factory method would serve you well here.
Mark your base test fixture as abstract and define a protected abstract method with the same signature as the service constructors. Then, call that method in your base fixture's setup logic.
You will have to implement the abstract method for each derived test class, but I think it's a reasonable compromise.
Note that I also removed the interface from the test class. Based on the sample code you provided, it's entirely redundant with the now-abstract base class. Of course, it might be useful for some reason not apparent from your example--if so, you can keep it.
public class BaseServiceUnitTest<TEntity> where TEntity : BaseEntity
{
private IBaseService<TEntity> _service;
public BaseServiceUnitTest(Constructor ctor)
{
_service = Create(/* your mocked dependencies here */);
}
protected abstract IBaseServce<TEntity> Create(Dependency1 d1, Dependency2 d2);
//...implemented methods from IBaseServiceUnitTest
}
public class CustomEntityServiceUnitTest : BaseServiceUnitTest<CustomEntity>
{
// "arg1, arg2"
protected override IBaseService<CustomEntity> Create(Dependency1 d1, Dependency2 d2) =>
new BaseService<CustomerEntity>(d1, d2);
}
Addendum
If you really want to make things automagic, you could try the answer to this question. It'll work, but you'll sacrifice "F12-ability" (the ability to find and navigate through references using Visual Studio's shortcuts) and compile-time verification of your constructors and their arguments. Personally, I'd probably use the factory method.
Addendum #2
For completeness, it's also worth noting that if your service-under-test had no constructor arguments, you might also be able to use the new constraint. Based on your comments, it doesn't sound like it will work in this case, but it might be useful another time.
Related
We have an interface to deal with DAL with pretty simple definition:
interface IRepository<T> : IQueriable<T> // so we can read data from database
{
Save(T document); // dozen of methods here
}
Mostly we use two implementations: real version and in memory version for unit testing. Here is declarations of one of class:
public RealRepository : IRepository<AccountEntity> { ... }
// typical IOC usage
services.AddSingleton<IRepository<AccountEntity>, RealRepository<AccountEntity>>();
Now we are working to spin off for main codebase to custom version of project and we need custom fields in data and occassional custom behavior in repository. Most of classes are fine with base implementation but others would require specific implementation. So my goal is to get to following services in:
var repository = new RealRepository<CustomAccountEntity>();
services.AddSingleton(IRepository<AccountEntity>, repository);
// for new classes
services.AddSingleton(IRepository<CustomAccountEntity>, repository);
I tried to add out T to IRepository but I am using T in input parameters and this gave compile time "Invalid variance" error.
I can see a solution by adding second type parameter to interface so it looks like:
IRepository<TBase, out TChild> : IQueriable<TChild> {
Save (T document);
}
Finally, Question: How can make change 100% backward compatible?
What I tried:
Add IRepository<T>: IRepository<T,T> -> complies, but RealRepository is not implementing IRepository anymore.
Add 2 interfaces in implementation: public class RealRepository<TBase, TChild>: IRepository<TBase, TChild>, IRepository<TChild> but this gives compliation error 'cannot implement both ... and ... because they may unify for some type parameter substitutions'
Save(T document) has T in a contravariant position. That means in T, not out T.
Let's recap what contravariance means. Suppose you had this code:
using System;
public class Entity {}
public class AccountEntity : Entity {}
public class CustomAccountEntity : AccountEntity {}
public interface IQueryable<in T>
where T : Entity
{}
public interface IRepository<in T>
where T : Entity
{
void Save(T record);
}
public class EntityRepository<T> : IRepository<T>
where T : Entity
{
public void Save(T record) {}
}
public class Program
{
public static void Main()
{
// This is ***VALID***:
IRepository<CustomAccountEntity> repo = new EntityRepository<AccountEntity>();
Console.WriteLine(repo == null ? "cast is invalid" : "cast is valid");
}
}
https://dotnetfiddle.net/cnEdcm
So whenever you need a IRepository<CustomAccountEntity>, you can use a concrete EntityRepository<AccountEntity> instance. Seems counter-intuitive, but it's actually totally right: If the concrete method is Save(AccountEntity), it can obviously handle CustomAccountEntity instances too; OTOH if the concrete method were Save(CustomAccountEntity), it would NOT be able to handle simple AccountEntity instances.
Having said that, then I think you should
Use contravariance instead;
Declare all dependencies using the most specialised type, e.g. IRepository<CustomWhateverEntity>;
In the IoC registration code, for each particular entity, setup either Repository<CustomeWhateverEntity>, if you need the extra behaviour, or just Repository<WhateverEntity> otherwise.
I have the following problem:
The base class expects to receive some data but the data is initialized by the derived class constructor which in C# is called after the base constructor was called.
Context / What I'm trying to solve:
Let's call the base class Track, its role is to build a mesh that represents a track for a video game.
The derived classes, e.g. Track1 each fetch track data from a particular file format, with significant differences that forbids implementing the whole code in base class Track.
The main job of Track is to abstract the data incoming from derived classes and for this it has abstract members that derived classes have to implement, e.g. int GetVertexCount, Vector3 GetVertex(int).
Think more of less of it being an IPicture interface that can load from different formats, e.g. BMP, JPEG, and return the whole thing as an abstraction.
The problem I am facing:
In C#, base class constructors are called before derived class constructor, but I must initialize something in the derived class constructor that in turn I must pass to the base class constructor. And while I'm on it, I would like to have members to be immutable, i.e. readonly.
Question:
How can I run some code in derived class constructor first, so I can pass the result to the base constructor ?
Answer:
Following #Kit answer here's how I ended up doing and it's just fine:
Ironically, it ended up being a C-like API :)
Assuming you don't need an instance of your derived class to do the logic you want, you can call a static method from your derived constructor prior to calling the base constructor.
Here is a simplistic example
public class Base
{
protected Base(SomeType data)
{
// base logic using data
}
}
public class DerivedOne : Base
{
public DerivedOne(int some, string data) : base(DerivedLogic(some, data))
{
...
}
private static SomeType DerivedLogic(int some, string data) => ...
}
public class DerivedTwo : Base
{
public DerivedTwo (string moreStuff) : base(DerivedLogic(moreStuff))
{
...
}
private static SomeType DerivedLogic(string moreStuff) => ...
}
This runs in the following order:
Static method DerivedLogic
Base class constructor (using the value from DerivedLogic)
Derived constructor
Now, that's slightly weird. What might be better is the derived logic not be a part of the derived class at all. What do I mean? I mean you have a third class that is passed into the derived constructor, and then on to the base constructor. That gives you the same effect.
public class Base
{
protected Base(SomeOtherType dataWrapper)
{
var data = dataWrapper.DerivedLogic();
// base logic using data
}
}
public class DerivedOne : Base
{
public DerivedOne(SomeOtherType otherType) : base(otherType)
{
...
}
}
Or calculate SomeType somewhere prior to calling any constructors and then pass it in. Either of these ways is a better design because it follows SRP:
Base class responsible for what it does.
Logic for constructing a track has that single responsibility.
Derived class has it's single responsibility.
There's not a really elegant way to do exactly what you're asking for, but I would question whether it's really necessary. It's usually a code smell to see logic in a constructor.
There are lots of other approaches you can take, like using a static Create() method.
class Derived : Base
{
private readonly object _o;
private Derived(object o, string s) : base(s)
{
_o = o;
}
public static Derived Create(string path)
{
var o = new object();// initialize from path
var s = o.ToString(); // get s from o.
return new Derived(o, s)
}
}
You could also consider using composition over inheritance:
class Base
{
private readonly string _s;
public Base(string s)
{
_s = s.ToLower();
}
}
class Derived
{
private readonly object _o;
private readonly Base _b;
public Derived(string path)
{
_o = new object();// initialize from path
_b = new Base(_o.ToString());
}
}
But it's really difficult to know which of these approaches might be appropriate without knowing what your actual goals and constraints are. You've told us how you want to solve your problem, and not what problem you're trying to solve.
I have a class using a group of properties in similar ways (only two shown in the example, for brevity).
The general behavior is defined on a base class, while the specific behavior is defined in specific interfaces
The problem is: If I declare them as base class, I have to cast them to interface to call interface methods. Now if I declare them as interface, I have to cast them to base class when I want to call base methods.
My goal when using interfaces here is to improve testability (with dependency injection, later), and to cultivate the habit of "programming to the interface", but I cannot decide which way is best, or even if the whole rationale is good in the first place.
public class Conductor
{
// These properties inherit from base class
// and implement one specific interface each:
// declared as interface:
IPlotterHelper _plotter_helper = new PlotterHelper();
// declared as base class:
Helper _file_writer_helper = new FileWriterHelper();
// When using handlers defined in specific interfaces:
// have to cast this:
this.NewFrame += ((IPlotterHelper)_file_writer_helper).ProcessFrame();
// but not this:
this.NewSamples += _plotter_helper.ProcessSamples();
// While when using handlers from the base class
// have to cast this to the base class (since it is an interface):
this.CommandSent += ((Helper)_plotter_helper).RunCommand;
// but not this:
this.CommandSent += _file_writer_helper.RunCommand;
}
internal class FileWriterHelper : Helper, IFileWriterHelper
{
IFileWriterHelper.ProcessFrame()
{
// ...
}
// ...
}
internal class PlotterHelper : Helper, IPlotterHelper
{
IPlotterHelper.ProcessSamples ()
{
///
}
// ...
}
internal class Helper
{
internal void RunCommand()
{
// ...
}
}
When I am faced with the desire to have default behavior in an interface, I would generally consider using an abstract base class either with protected helper methods and a set of abstract interface methods or a default implementations of the "interface" methods. This may be the case even if I start with only a single concrete implementation.
Many people treat abstract classes and interfaces as being in the same broad category of implementation options.
The problem with abstract classes is single inheritance, so we should only use an abstract class if it really is to be the base of a class hierarchy (even a shallow one). Interfaces can be used to decorate classes (from diverse hierarchies) with common behavior.
For testing, I don't see much difference between faking with an interface and faking with an abstract class - but that might depend on your testing infrastructure.
In this case, I would use an abstract class and forget about the interface (unless it already exists, in which case you don't have any choice anyway).
It's hard to exactly see what you're trying to do, but it seems like this might be a more suitable design:
public class Conductor
{
private IPlotterHelper _plotter_helper = new PlotterHelper();
private IFileWriterHelper _file_writer_helper = new FileWriterHelper();
public void Conduct()
{
_file_writer_helper.ProcessFrame();
_file_writer_helper.RunCommand();
_plotter_helper.ProcessSamples();
_plotter_helper.RunCommand();
}
}
internal interface IHelper
{
void RunCommand();
}
internal interface IFileWriterHelper : IHelper
{
void ProcessFrame();
}
internal interface IPlotterHelper : IHelper
{
void ProcessSamples();
}
internal class FileWriterHelper : Helper, IFileWriterHelper
{
public void ProcessFrame()
{
}
}
internal class PlotterHelper : Helper, IPlotterHelper
{
public void ProcessSamples()
{
}
}
internal class Helper : IHelper
{
public void RunCommand()
{
}
}
Interfaces and abstract classes have the same purpose: provide abstraction. Make that abstraction coherent, and if the base class has public members, make sure they're also on the interface.
But then, why would I need the abstract class or interface for? - right. get rid of either the base class or the interface - you likely don't really need both. I'd drop the base class.
This question already has answers here:
How to mock non virtual methods?
(8 answers)
Closed last year.
I have a C# class that gets generated using the wsdl.exe tool that looks something like this:
public partial class SoapApi : System.Web.Services.Protocols.SoapHttpClientProtocol
{
public SOAPTypeEnum AskServerQuestion()
{
object[] results = return this.Invoke("AskServerQuestion");
return (SOAPTypeEnum) results[0];
}
}
I have some thin wrapper code around this that keeps track of the result, etc. Is it possible to use any of the object mocking frameworks to make a fake SoapApi class and return predictable results for each of the calls to the thin wrapper functions?
I can't make the AskServerQuestion() function virtual because it's auto-generated by the wsdl.exe tool.
The way I've accomplished this was to inject an ISoapApi instead, where the ISoapApi interface mimics the automatically generated SOAP API.
For your case:
public interface ISoapApi
{
SOAPTypeEnum AskServerQuestion ();
}
Then, take advantage of the fact that the generated SoapApi class is partial, and add this in another file:
public partial class SoapApi : ISoapApi
{
}
Then, consumers should just take an ISoapApi dependency that can be mocked by any of the mocking frameworks.
One downside is, of course, when the SOAP api changes, you need to update your interface definition as well.
The class is partial so you could make the class implement an interface in the partial class part you write.
You can then mock the interface.
I worked out a technique that will work for the case where the class is non-partial. Suppose this is the original class:
// Generated class, can't modify.
public class SomeClass
{
// Non-virtual function, can't mock.
public void SomeFunc() { //... }
}
First, extract the interface from that class:
public interface ISomeClass
{
void SomeFunc();
}
Now make a new class that inherits from both of the above:
public SomeClass2 : SomeClass, ISomeClass
{
// The body of this class is empty.
}
Now you can use SomeClass2 in your program. It will behave the same as SomeClass. And you can mock ISomeClass.
In a C# program, I have an abstract base class with a static "Create" method. The Create method is used to create an instance of the class and store it locally for later use. Since the base class is abstract, implementation objects will always derive from it.
I want to be able to derive an object from the base class, call the static Create method (implemented once in the base class) through the derived class, and create an instance of the derived object.
Are there any facilities within the C# language that will allow me to pull this off. My current fallback position is to pass an instance of the derived class as one of the arguments to the Create function, i.e.:
objDerived.Create(new objDerived(), "Arg1", "Arg2");
Try using generics:
public static BaseClass Create<T>() where T : BaseClass, new()
{
T newVar = new T();
// Do something with newVar
return T;
}
Sample use:
DerivedClass d = BaseClass.Create<DerivedClass>();
Summary
There are two main options. The nicer and newer one is to use generics, the other is to use reflection. I'm providing both in case you need to develop a solution that works prior to .NET 2.0.
Generics
abstract class BaseClass
{
public static BaseClass Create<T>() where T : BaseClass, new()
{
return new T();
}
}
Where the usage would be:
DerivedClass derivedInstance = BaseClass.Create<DerivedClass>();
Reflection
abstract class BaseClass
{
public static BaseClass Create(Type derivedType)
{
// Cast will throw at runtime if the created class
// doesn't derive from BaseClass.
return (BaseClass)Activator.CreateInstance(derivedType);
}
}
Where the usage would be (split over two lines for readability):
DerivedClass derivedClass
= (DerivedClass)BaseClass.Create(typeof(DerivedClass));
You want to create a new instance of derived from inside another instance of derived, using a static factory method on the abstract base class? if so, I wonder Why... But ...
public abstract class MyBase
{
public static T GetNewDerived<T>() where T : MyBase, new()
{
return new T();
}
}
public class DerivedA : MyBase
{
public static DerivedA GetNewDerived()
{
return GetNewDerived<DerivedA>();
}
}
public class DerivedB : MyBase
{
public static DerivedB GetNewDerived()
{
return GetNewDerived<DerivedB>();
}
}
Is this what you want ?
Sounds like you need to make the Create() method abstract. And once you do that you might as well rename it and make it the constructor as well. Then you can have a different Init() method that you call after the object is constructed if you need to, and normal polymorphism effects will handle things.
You can't do it without outside information; either the type of the derived class, an instance of it, or the fully-qualified name of the derived class. Any of these are equivalent to what you're already doing; there isn't a better solution I'm aware of. The very nature of static methods precludes anything more elegant.
I'm not sure what your design goals are but from what you asked it sounds like it might end up with alot of code smell. I think you should really look into the Inversion of Control(IoC) / Dependency Injection (DI) design patterns that are implemented in numerous frameworks such as Microsoft Unity, Castle Windsor, StructureMap, Ninject, Spring.Net and so forth.
I think if you look at using an IoC container it will solve your problem in a much cleaner and loosely coupled way.