Best interface mock / fake with partial implementation - c#

Is there a good tool under C#, to fake complex interfaces (service, repository and the like) with partial test implementations?
The mock framework I am currently using (RhinoMocks) is too slow and too hard to handle for this purpose.
Prerequisites:
No significant performance penalty, compared to real implementations (bulk tests)
Implementation with rudimentary logic and data (e.g.: dictionary instead of database table)
No need to change the tests, when the interface changes.
Full implementation example:
public interface IMyInterface
{
int PropertyA { get; set; }
int PropertyB { get; set; }
void DoSomethingWithX(int x);
int GetValueOfY();
}
public class FakeImplementation : IMyInterface
{
private int _valueOfYCalls = 0;
public int PropertyA { get; set; }
public int PropertyB { get; set; }
public void DoSomethingWithX(int x)
{ }
public int GetValueOfY()
{
return _valueOfYCalls++;
}
}
The counter is just to simulate the rudimentary logic.
Problem is, if the interface gets a new method, like SetSomeZ(int z) , the test won't build/run anymore, without explicit change.
Is there a fake/mock framework, working with basic implementations, but adding members automatically, either via virtual/override, or wrapper?
Such as this:
[ImplementsInterface(nameof(IMyInterface))]
public class FakeImplementationBase
{
private int _valueOfYCalls = 0;
[ImplementsMember(nameof(IMyInterface.GetValueOfY))]
public virtual int GetValueOfY()
{
return _valueOfYCalls++;
}
}
The tool/framework should generate full implementation types at runtime, similar to mocks/stubs, but using the basic implementation, just adding the missing interface parts.
This is not supposed to be for real unit testing, but for more complex purposes. It's also legacy software with huge interfaces and classes, not much about "single responsibility".

Moq is exactly what you want.
public interface IFoo {
int MethodA(int a);
void MethodB(long b);
void MethodC(string c);
...
}
var MoqFoo = new Mock<IFoo>();
MoqFoo.Setup(m => m.MethodA(It.Is(a => a > 0)).Returns<int>(a => a + 1);
MoqFoo.Setup(m => m.MethodC(It.IsAny<string>()).Callback<string>(c => Debug.Write(c));
Note how we didn't do .Setup() for MethodB? When you declare it, all methods and properties get dummy methods/properties, .Setup() will specify your own custom ones.
So if your interface has 10 methods but you only want to test MethodD(), you only need to write code for that.
http://www.developerhandbook.com/unit-testing/writing-unit-tests-with-nunit-and-moq/

Related

Is there a way to control which classes may access certain methods inside a class?

I haven't really found an answer for this, so I'm curious if such a thing is even possible. Let's say I have a DataClass which holds all kinds of data for the program. Something like this, for example:
public class DataClass
{
int Data_One;
int Data_Two;
int Data_Three;
public int GetOne();
public int GetTwo();
public int GetThree();
public void SetOne();
public void SetTwo();
public void SetThree();
}
Now, let's say I have two other classes, class A and class B, both are instanced once, and both isntances may have access to the same instance of DataClass. But what if I want the two classes to have different kind of access to DataClass?
Let's say I want A to be able to read Data_One, and Data_Two, but only set Data_One, and have no access to Data_Three, whereas I want class B to be able to read and set Data_Three and Data_Two, but have no access to Data_One. Is this achieveable in some kind of way, and if so, what is the most convinient way to do it?
To further elaborate: In my example, there were 2 classes, but what I'm looking for is a general solution for any number of classes, that allows me to define which methods may be accessed by each class distinctly, regardless of how many other classes have access to the same method. Sort of like having an 'access table' that contains for each class which methods may be accessed by it. And I want this to be mantainable, so changing accessability permissions wouldn't be a hassle.
The most lifelike case would be having one class, that exclusively sets the data, a few others, that may only read that data, and the rest would have no access to it whatsoever. All this without having to use references between the classes, instad using a 'central' data object.
One idea I came up with was to typecheck the callers in the DataClass for every method, and determine whether or not that type has access to that method. The most ideal would be, if the DataClass would have some sort of Access method, that returns with an object or container-type with references to the accessible methods, although that sounds like too far of a stretch to me.
Use interfaces. You can have
interface ICanBeUsedOnlyByA {
int Data_One { get; set; }
}
interface ICanBeUsedOnlyByB {
int Data_Two { get; set; }
}
class DataClass : ICanBeUsedOnlyByA, ICanBeUsedOnlyByB {
}
And then you have
class A {
public ICanBeUsedOnlyByA A { get; set; }
public A (ICanBeUsedOnlyByA a){
A = a;
}
}
class B {
public ICanBeUsedOnlyByA B { get; set; }
public B (ICanBeUsedOnlyByB b){
B = b;
}
}
And then A will have only access to int Data_One; and B to int Data_Two;
I advise you to read about interfaces and abstract classes.
Basically interfaces:
public class DataClass : IAInterface, IBInterface
{
int Data_One;
int Data_Two;
int Data_Three;
public int GetOne();
public int GetTwo();
public int GetThree();
public void SetOne();
public void SetTwo();
public void SetThree();
}
public class A
{
public void SetA(IAInterface value)
{
//can only access whats in the interface
}
}
public class B
{
public void SetB(IBInterface value)
{
//can only access whats in the interface
}
}
public interface IAInterface
{
int GetOne();
int GetTwo();
}
public interface IBInterface
{
void SetOne();
void SetTwo();
}
One thing I can suggest in that case is to use internal for methods and properties to which you want restrict access and put one class to the other assembly. You also can use interfaces as it is suggested in other answers, but it is better to implement them explicitly in that case.

Down-cast ComponentRegistration to non-generic type

I`m using Castle.Windsor library, and what i want is to get "Implementation" property, from all items in IRegistration[].
I have following interfaces and classes:
public interface IA
{
int a { get; set; }
}
public class A : IA
{
public int a { get; set; }
}
public interface IB
{
int b { get; set; }
}
public class B : IB
{
public int b { get; set; }
}
And a static class which contains this Components:
public static class Bootekstraperek
{
private static readonly IRegistration[] _commonRegistrations =
{
Component.For<IA>().ImplementedBy<A>(),
Component.For<IB>().ImplementedBy<B>()
};
public static void Test()
{
List<IRegistration> list = _commonRegistrations.ToList();
foreach (var registration in list)
{
ComponentRegistration a = registration as ComponentRegistration;
Console.WriteLine(a.Implementation.FullName);
}
}
}
And of course variable a is null after every iteration.
It works only when i cast to Generic ComponentRegistration
var a = registration as ComponentRegistration<A>;
But, that dont helps me if i have too much different components inside this array. So Switch statement is not an option.
I have tried using reflections, but i still didn`t managed to properly cast.
How can i achieve what i want With or Without using reflections?
thxia.
This is not easy because the IRegistration API was never meant to be used in this way.
So my answer has two parts.
How you can do it. Use dynamic.
you only need to change a small bit of your code:
foreach (dynamic registration in list)
{
Console.WriteLine(registration.Implementation.FullName);
}
What is the underlying goal you're trying to achieve here? Have a look at Windsor's diagnostics if your goal is to keep a level of visibility into what gets registered, how and be on a lookout for potential issues.
A small amount of Reflection solves the problem (it is a small amount, but it looks verbose, because Reflection):
foreach (var registration in list)
{
Console.WriteLine(
((Type)registration.GetType().GetProperty(
"Implementation"
).GetGetMethod().Invoke(
registration,new object[] { })
).FullName);
}
Since you won't know the types that are being used as generic type parameters until runtime, I don't think there's a way to do this without any Reflection.
The above assumes that all of the registrations will be ComponentRegistration<T> objects of some sort. If that's an unsafe assumption, there may be some other implementations of IRegistration that don't implement an Implementation property or it may not be publicly accessible - so insert appropriate interim error checking if that's the case.

Default implementation of a method for C# interfaces?

Is it possible to define an interface in C# which has a default implementation? (so that we can define a class implementing that interface without implementing that particular default method).
I know extension methods (as explained in this link for example). But that is not my answer because having a method extension like the following, the compiler still complains about implementing MyMethod in MyClass:
public interface IMyInterface
{
string MyMethod();
}
public static class IMyInterfaceExtens
{
public static string MyMethod(this IMyInterface someObj)
{
return "Default method!";
}
}
public class MyClass: IMyInterface
{
// I want to have a default implementation of "MyMethod"
// so that I can skip implementing it here
}
I am asking this because (at least as far as I understand) it is possible to do so in Java (see here).
PS: having an abstract base class with some method is also not my answer simply because we don't have multiple inheritance in C# and it is different from having a default implementation for interfaces (if possible!).
C# v8 and above allows concrete method implementation in interfaces as well. This will allow your concrete implementation classes to not break when you change the interfaces being implemented in future.
So something like this is now possible:
interface IA
{
void NotImplementedMethod(); //method having only declaration
void M()
{
WriteLine("IA.M");
}//method with declaration + definition
}
Please refer to this GitHub issue # 288. Also Mads Torgersen talks about this feature at length in this channel 9 video.
MS Docs - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/default-interface-methods
I develop games so I often want to have common function for all implementations of an interface but at the same time allow each implementation to do its own thing as well, much like a subclass' virtual / override methods would function.
This is how I do it:
public class Example
{
void Start()
{
WallE wallE = new WallE();
Robocop robocop = new Robocop();
// Calling Move() (from IRobotHelper)
// First it will execute the shared functionality, as specified in IRobotHelper
// Then it will execute any implementation-specific functionality,
// depending on which class called it. In this case, WallE's OnMove().
wallE.Move(1);
// Now if we call the same Move function on a different implementation of IRobot
// It will again begin by executing the shared functionality, as specified in IRobotHlper's Move function
// And then it will proceed to executing Robocop's OnMove(), for Robocop-specific functionality.
robocop.Move(1);
// The whole concept is similar to inheritence, but for interfaces.
// This structure offers an - admittedly dirty - way of having some of the benefits of a multiple inheritence scheme in C#, using interfaces.
}
}
public interface IRobot
{
// Fields
float speed { get; }
float position { get; set; }
// Implementation specific functions.
// Similar to an override function.
void OnMove(float direction);
}
public static class IRobotHelper
{
// Common code for all IRobot implementations.
// Similar to the body of a virtual function, only it always gets called.
public static void Move(this IRobot iRobot, float direction)
{
// All robots move based on their speed.
iRobot.position += iRobot.speed * direction;
// Call the ImplementationSpecific function
iRobot.OnMove(direction);
}
}
// Pro-Guns robot.
public class Robocop : IRobot
{
public float position { get; set; }
public float speed { get; set;}
private void Shoot(float direction) { }
// Robocop also shoots when he moves
public void OnMove(float direction)
{
Shoot(direction);
}
}
// Hippie robot.
public class WallE : IRobot
{
public float position { get; set; }
public float speed { get; set; }
// Wall-E is happy just moving around
public void OnMove(float direction) { }
}
Short Answer:
No, you cannot write implementation of method in interfaces.
Description:
Interfaces are just like contract ,so that the types that will inherit from it will have to define implementation, if you have a scenario you need a method with default implementation, then you can make your class abstract and define default implementation for method which you want.
For Example:
public abstract class MyType
{
public string MyMethod()
{
// some implementation
}
public abstract string SomeMethodWhichDerivedTypeWillImplement();
}
and now in Dervied class:
public class DerivedType : MyType
{
// now use the default implemented method here
}
UPDATE (C# 8 will have support for this):
C# 8 will allow to have default implementation in interfaces
Not directly, but you can define an extension method for an interface, and then implement it something like this
public interface ITestUser
{
int id { get; set; }
string firstName { get; set; }
string lastName { get; set; }
string FormattedName();
}
static class ITestUserHelpers
{
public static string FormattedNameDefault(this ITestUser user)
{
return user.lastName + ", " + user.firstName;
}
}
public class TestUser : ITestUser
{
public int id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string FormattedName()
{
return this.FormattedNameDefault();
}
}
Edit*
It is important that the extension method and the method that you are implementing are named differently, otherwise you will likely get a stackoverflow.
it is possible in C# 8.0. You can add a method with default implementation. You will have to change your target framework version to latest to use this feature.
As a newbe C# programmer I was reading through this topic and wondered if the following code example could be of any help (I don't even know if this is the proper way to do it). For me it allows me to code default behavior behind an interface. Note that I used the generic type specifiction to define an (abstract) class.
namespace InterfaceExample
{
public interface IDef
{
void FDef();
}
public interface IImp
{
void FImp();
}
public class AbstractImplementation<T> where T : IImp
{
// This class implements default behavior for interface IDef
public void FAbs(IImp implementation)
{
implementation.FImp();
}
}
public class MyImplementation : AbstractImplementation<MyImplementation>, IImp, IDef
{
public void FDef()
{
FAbs(this);
}
public void FImp()
{
// Called by AbstractImplementation
}
}
class Program
{
static void Main(string[] args)
{
MyImplementation MyInstance = new MyImplementation();
MyInstance.FDef();
}
}
}
C# 11 feature - Now official:
Static virtual members in interfaces
Docs saying:
C# 11 and .NET 7 include static virtual members in interfaces.
This feature enables you to define interfaces that include overloaded
operators or other static members.
Once you've defined interfaces with static members, you can use those interfaces as constraints to create generic types that use operators or other static methods.
So you can:
Define interfaces with static members.
Use interfaces to define classes that implement interfaces with operators defined.
Create generic algorithms that rely on static interface methods.
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members
Prerequisites
You'll need to set up your machine to run .NET 7, which supports C# 11

Inheritance problem in C#

I'm refactoring some code and want to classes a bit higher in the inheritance chain be a bit more strict with their parameters. As I'm not sure I'm explaining this correctly, here's what I've got:
public interface ISvdPredictor
{
List<string> Users { get; set; }
List<string> Artists { get; set; }
float PredictRating(ISvdModel model, string user, string artist);
float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}
ISvdPredictor uses ISvdModel:
public interface ISvdModel
{
float[,] UserFeatures { get; set; }
float[,] ArtistFeatures { get; set; }
}
Now I want to implement another variation:
public interface IBiasSvdPredictor : ISvdPredictor
{
float PredictRating(IBiasSvdModel model, string user, string artist);
float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
Which uses IBiasSvdModel which derives from ISvdModel:
public interface IBiasSvdModel : ISvdModel
{
float GlobalAverage { get; set; }
float[] UserBias { get; set; }
float[] ArtistBias { get; set; }
}
IBiasSvdPredictor will not work with ISvdModel.
The problem is that when I implement IBiasSvdPredictor I'd have to implement 2 pairs of PredictRating methods. One from ISvdPredictor and the other from IBiasSvdPredictor. What do I need to do to be able to just implement those from IBiasSvdPredictor?
I've tried generics as well, but couldn't restrict the PredictRating for BiasSvdPredictor to IBiasSvdModel using the where directive. I may be doing this all wrong so any suggestion might help. I think you get what I'm trying to do.
EDIT: If anyone needs more context see https://github.com/gligoran/RecommendationSystem. I'm writing this code for my thesis for BSc.
You could use generics and constraints.
public interface ISvdModel
{
float[,] UserFeatures { get; set; }
float[,] ArtistFeatures { get; set; }
}
public interface IBiasSvdModel : ISvdModel
{
float GlobalAverage { get; set; }
float[] UserBias { get; set; }
float[] ArtistBias { get; set; }
}
public interface ISvdPredictor<in TSvdModel>
where TSvdModel : ISvdModel // Require that TSvdModel implements ISvdModel
{
List<string> Users { get; set; }
List<string> Artists { get; set; }
float PredictRating(TSvdModel model, string user, string artist);
float PredictRating(TSvdModel model, int userIndex, int artistIndex);
}
// I would actually avoid declaring this interface. Rather, see comment on the class.
public interface IBiasSvdPredictor : ISvdPredictor<IBiasSvdModel> { }
class BiasSvdPredictor : IBiasSvdPredictor // Preferred : ISvdPredictor<IBiasSvdModel>
{
// ...
public float PredictRating(IBiasSvdModel model, string user, string artist) { }
public float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex) { }
}
The interface should have one method, PredictRating. I wouldn't have two interfaces that have the same method to implement. Confusing.
Create an abstract class that implements your interface. Make PredictRating a virtual method so inheritors can override as they see fit. You could even do a default implementation on the abstract class.
One interface, One abstract class. N concrete class that implement PredictRating as they see fit.
public interface Demo
{
int PredictRating(int param1);
}
public abstract class AbstractDemo : Demo
{
public virtual int PredictRating(int param1)
{
return param1 + 1;
}
}
public class ClassDemo1 : AbstractDemo
{
//This guy uses AbstractDemo Predict Rating
public override int PredictRating(int param1)
{
return base.PredictRating(param1);
}
}
public class ClassDemo2 : AbstractDemo
{
//This guy overrides the predict rating behavior
public override int PredictRating(int param1)
{
return param1 + 2;
}
}
You have to implement all four methods. They have different signatures and thus are considered to be different. However, you can have one delegate to the other, and sometimes using explicit implementation helps with that.
public class Foo : IBiasSvdPredictor {
public float PredictRating(IBiasSvdModel, string user, string artist) { .... }
// this is an expicit implementation of ISvdPredictor's method. You satisfy
// the interface, but this method is not a public part of the class. You have to
// cast the object to ISvdPredictor in order to use this method.
float ISvdPredictor.PredictRating(ISvdModel model, string user, string artist) {
this.PredictRating((IBiasSvdModel)model, user, artist);
}
}
This of course will not work if the ISvdModel is not actually an IBiasSvdModel.
You can use explicit interface implementation to hide the ones from ISvdPredictor, but you should implement them all or have a base abstract class to handle them.
I'd have to implement 2 pairs of PredictRating methods.
Of course you do. What did you expect?
If your IBiasSvdPredictor must take a IBiasSvdModel in its PredictRating method, than IBiasSvdPredictor is not an ISvdPredictor (because it cannot take a ISvdModel as the first parameter to PredictRating) and inheriting IBiasSvdPredictor from ISvdPredictor is the wrong choice.
In my opinion, you should simply keep the interfaces separate and not inherit one from the other.
Without having a full understanding of your object model (so this may not actually apply in your situation), it seems like maybe ISvdModel shouldn't be part of the interface definition. It seems more like it's an implementation detail, not necessarily part of the contract you're trying to enforce. To me it makes more sense to pass ISvdModel (or IBiasSvdModel) into the constructor of your implementation class, not have it as part of your ISvdPredictor interface. Then you wouldn't need 2 separate interface definitions at all, you would just have 2 implementations of the single interface.
You might even be able to take it one step further; if the only difference between ISvdPredictor and IBiasSvdPredictor is that one uses a ISvdModel and the other uses a IBiasSvdModel, you wouldn't even need 2 implementations, just one, and you would pass in the correct instance of ISvdModel for each situation. This is a design pattern called Inversion of Control, specifically using Dependency Injection, and is very powerful to achieve higher levels of code reuse in your programs.

Testing two dependent classes in C#

The problem I want to solve is, how to test two dependent classes in C#. For testing I'm using NUnit and Moq.
Let's say I have a custom collection which autonumerates its items. Values inside collection must be kept in its original order, so that's the reason why it has to be autonumerated. Following code shows the most simple example of mentioned classes:
public interface ICustomItem
{
int Id { get; set; }
ICustomCollection<ICustomItem> ParentCollection { get; set; }
}
public interface ICustomCollection<T> where T : ICustomItem
{
IEnumerable<T> Items { get; set; }
void Add(T t);
// And more of course...
}
public class CustomCollection<T> : ICustomCollection<T> where T : ICustomItem
{
public IEnumerable<T> Items { get; set; }
public void Add(T t)
{
// Some logic here...
t.Id = Items.Count(); // Generate Id
}
}
When adding item to collection, a new Id is generated and assigned to CustomItem. Mechanism of autonumerating should be included also in other methods, such as Remove(), but for this question I've left Add method only.
The question is, how to test if autonumerates works correctly? When the mock is passed as a param, it is not modified inside the class. Should I test the class with simple instance of created-for-tests CustomItem class?
tl;dr
In other words, I want to be able to modify a mock inside a class.
Try to use the class in the test just as you would use it from the production code. This will give you the most usable test in the sense that you are free to refactor the code inside the classes without breaking or even changing a test. The test will also serve as an example on how to use the class.
To start out I would not use Moq, but rather use a short MockCustomItem class that you implement just for the test.
Then use add some values and assert that result is what you expected. Make it a habit to only use one assert in each test like below.
[TestFixture]
public class GivenCustomCollectionWithTwoElements
{
private CustomCollection<MockCustomItem> _customCollection;
[SetUp]
public void SetUp()
{
_customCollection = new CustomCollection<MockCustomItem>();
_customCollection.Add(new MockCustomItem());
_customCollection.Add(new MockCustomItem());
}
[Test]
public void CheckLength()
{
Assert.That(_customCollection.Items, Is.EqualTo(2));
}
[Test]
public void CheckFirstItemId()
{
Assert.That(_customCollection.Items.ElementAt(0).Id, Is.EqualTo(0));
}
[Test]
public void CheckSecondItemId()
{
Assert.That(_customCollection.Items.ElementAt(1).Id, Is.EqualTo(1));
}
private class MockCustomItem : ICustomItem
{
public int Id { get; set; }
public ICustomCollection<ICustomItem> ParentCollection { get; set; }
}
}
Once you get the hang of this, you can also use Moq to create more concise tests with less boilerplate code. In this case NUnit parameterizedtest cases could also be used.
In unit tests you shall only test the unit you are testing right now. So I wold say that you shall mock/fake the ICustomItem and send it in and then looks if the faked object get the Id you expect.
Read my answer here for further info about the same topic Any ASP.NET (WebForm) apps which have good unit tests (CodePlex or anywhere)?
I use FakeItEasy as mock/fake-framework but I guess moq would look pretty similar, here is my code for it
[TestFixture]
public class CustomCollectionTests{
[Test]
public void Add_AddTwoItems_ItemsGetsConsecutiveIds() {
var customItem1 = A.Fake<ICustomItem>();
var customItem2 = A.Fake<ICustomItem>();
var cutomCollection = new CustomCollection<ICustomItem>();
cutomCollection.Add(customItem1);
cutomCollection.Add(customItem2);
Assert.AreEqual(1, customItem1.Id);
Assert.AreEqual(2, customItem2.Id);
}
}
public interface ICustomItem {
int Id { get; set; }
}
public interface ICustomCollection<T> where T : ICustomItem {
void Add(T t);
}
public class CustomCollection<T> : ICustomCollection<T> where T : ICustomItem {
public List<T> innerList = new List<T>();
public void Add(T t) {
// Some logic here...
innerList.Add(t);
t.Id = innerList.Count(); // Generate Id
}
}
Edit
Removed non tested MOQ-example that seemed to be not working.
You're right in the fact that the mock isn't modified. But you should be able to verify the mock after calling the add method like this:
mock.VerifySet(x => x.Id = 42);
Remember to set something in the Items property before calling Add. That something should return 42, when asking for the Count(). That could be a mock as well.

Categories