Check the properties of an object passed back to mock using Moq - c#

Is it possible to check what the properties are of an object send to a Mocked method? For example I have:
public class Foo
{
int SomeNumber {get; set;}
}
public class ReceivesFoo: IReceivable
{
public void Process(Foo foo)
{
}
}
public class Bar
{
private IReceivable receiver;
public void SomeMethod(int b)
{
Foo foo = new Foo();
if (b == 0)
{
foo.SomeNumber = 12;
}
else
{
foo.SomeNumber = 7;
}
receiver.Process(foo);
}
}
public class TestBar
{
public void ZeroReceives12()
{
mockReceivable.Setup(x => x.Process(It.IsAny<Foo>());
bar.SomeMethod(0);
}
}
It is quite a simplification but hopefully you know what I am getting at. I know it is a bad idea to create a new class in a method. So that is done somewhere else in a factory of sorts. But all the logic to set the various properties of the new object are done in this method. Because it makes no sense to put that logic in the factory because it has nothing to do with the factory and things will changes depending on the state of Bar.
So basically I just want to be able to do more than just verify that mocked receiver would have received some kind of Foo. I want to make sure that it received an instance of Foo and that its SomeNumber was set to 12.

This is a great reference for you... https://github.com/Moq/moq4/wiki/Quickstart
Basically you want something like this...
public void ZeroReceives12()
{
int input;
mockReceivable.Setup(x => x.Process(It.IsAny<Foo>())
.Callback(y => foo = y);
bar.SomeMethod(0);
// ensure input is what you expect
}

Related

Mock method return value with read only property

I wish to test a method which queries a third-party library. The library returns an object with a IReadOnlyCollection property.
There is no constructor to set the value of the property and the object has no interface for me to mock.
I have used Moq to mock the interface for the service that I call, but I can't create a mocked return value as I can't set the property.
public interface IHitService {
public Hit GetHit();
}
public class Hit {
public Hit() {
}
public IReadOnlyCollection<string> Result { get; }
}
public class TestingClass {
public void MyTest() {
Hit hit = new Hit() {
// cannot set this property
Result = new List<string>() { "hello","goodbye" };
}
Mock<IHitService> service = new Mock<IHitService>();
service.Setup(c => c.GetHit).Returns(hit);
}
}
What would be the best way for me to generate the return value to test my method? Wrapping the object with a new property to hide the base does not work.
You can use unit-test frameworks that allow you to change the behavior of a concrete object, for example in this case i used Typemock Isolator to try and solve your issue, it allows you to change the the return value of the result property so can "set" for your test without changing your code or adding extra code:
public void TestMethod1()
{
List<string> s = new List<string> { "sfas", "asfsa", "blbba" };
var hit = Isolate.Fake.NextInstance<Hit>();
Isolate.WhenCalled(() => hit.Result).WillReturnCollectionValuesOf(s);
}
In this test i mocked the Hit class and modified the return value of the Result property to a list of strings i created.
If you need to test a third-party library, it would be a better idea to create your own abstraction (interface) and rely on that for both testing and real code:
public interface IHitService
{
IHit GetHit();
}
public interface IHit
{
IReadOnlyCollection<string> Result { get; }
}
In your application code, you can create a simple wrapper class that implements IHit by delegating to the concrete third-party class. Now you can test the interface by mocking it as needed.
In general, if you can't change 3rd party code, build an adapter to it and use your own abstraction :-
public interface IHit
{
IReadOnlyCollection<string> Result { get; }
}
public interface IHitService
{
IHit GetHit();
}
public class HitAdapter : IHit
{
private Hit _hit;
public HitAdapter(Hit hit)
{
_hit = hit;
}
public IReadOnlyCollection<string> Result => _hit.Result;
}
public class TestingClass
{
public void MyTest()
{
var hitMock = new Mock<IHit>();
hitMock.Setup(c => c.Result).Returns<IReadOnlyCollection<string>>(x => new List<string>() {"hello", "goodbye"});
var service = new Mock<IHitService>();
service.Setup(c => c.GetHit()).Returns<IHit>(x => hitMock.Object);
}
}

Moq for single line multiple property code

I have these interfaces
public interface Interface1 { Interface2 Items {get;} }
public interface Interface2 { Guid? ApplicationTypeId { get; } }
public interface Interface3 { Class1 Item {get;} }
public interface Interface4 { Guid? ApplicationId { get; set; } }
A class inherits the first interface
public class Class1 : Interface1 {
public Interface2 Items { get; }
}
Another class which consists of few guids
public static class ContentTypeIds
{
public static Guid ContentGuid1 => new Guid("{11798e9d-a167-4cfc-8cfa-9a24fd6caf25}");
public static Guid ContentGuid2 => new Guid("{7d22f5bb-37fd-445a-b322-2fa1b108d260}");
}
I need to unit test the following property
private readonly Interface3 _interface3;
public Ticket Current
{
get
{
//This line is very complicated
Interface4 itemByContentType = _interface3.Item?.Items.GetItemByContentType(ContentTypeIds.ContentGuid2);
if ( itemByContentType?.ContentId != null )
return Get(itemByContentType.ContentId.Value);
return null;
}
}
My test class goes here
[Test]
public class TestClass {
var mock1 = new Mock<Interface1>();
var mock2 = new Mock<Interface2>();
var mock3 = new Mock<Interface3>();
mock1.SetupAllProperties();
mock2.SetupAllProperties();
mock3.SetupAllProperties();
}
The value for 'itemByContentType' goes null.
Could anyone help me to make it simple and testable as it is getting complicated to test this property? I'm using Moq. I will appreciate any help.
Thanks
I'm not an expert on Moq, but it looks like its SetupAllProperties method simply sets up all the properties to act like properties (i.e. the object it creates has a persistent member which can support GET/SET operation). If this isn't done, then as I understand it, the properties will still be available, but they'll always resolve to null. This is very handy when preparing the Mock objects, but on its own, though, that doesn't setup the properties with any sort of value.
I think what you should be doing is using Moq's SetupGet in conjunction with the Returns method to prepare the GET of the Items property with a specific value.
Here is some (simplified) sample code, to demonstrate this:
public interface IFoo { Guid? ApplicationId { get; set; } }
public interface IBar { IFoo Items { get; } }
class Program
{
static void Main(string[] args)
{
// SETUP
// Prepare mocks
Mock<IFoo> MockFoo = new Mock<IFoo>();
Mock<IBar> MockBar = new Mock<IBar>();
// Seting up properties allows us read/write Foo's ApplicationId
MockFoo.SetupAllProperties();
// The mocked Foo object should be what's returned when Items is requested
var expectedFoo = MockFoo.Object;
// Setup the Bar object to return that mocked Foo
MockBar.SetupGet(x => x.Items).Returns(expectedFoo);
// The value written here will be persistent due to SetupAllProperties
expectedFoo.ApplicationId = new Guid("{7d22f5bb-37fd-445a-b322-2fa1b108d260}");
// ACTION
// When the "Items" property is accessed, the IFoo we get should be what we mocked...
var actualFoo = MockBar.Object.Items;
// ... and we can read the value set to Foo's ApplicationId
var actualAppId = actualFoo.ApplicationId;
}
}

Dynamic method access modifier

I would like to restrict access to methods, depending on the type passed in. In my particular situation, I am developing a UDP "manager" if you will.
I want my UDPManager to be used for different things. For example, I might have 1 UDPManager for the communications between client and server, and another UDPManager to handle the communications between server and another server.
I have defined an enum which specifies the type of UDPManager. So for example, ManagerType.A = 1 and...
ManagerType.B = 2
The UDPManager has certain events that can be subscribed to and I do not want them available if these events are not relevant, given the type of UDPManager.
Here is an example of a class
public class Something
{
public int SomethingsType { get; set; }
public void A() { }
public void B() { }
}
How can I make it so that if SomethingsType == MessageType.A, then MessageType.B is not available (ie it is private)?
For further clarity, if I type:
Something something = new Something();
someting.SomethingsType = 1
I do not want something.B() to be available.
UPDATE
I apologise for mentioning runtime. What I mean is, I do not want said method (B) available if said SomethingsType is A.
Interfaces to the rescue:
public interface IUdpManagerA
{
void A();
}
public interface IUdpManagerB
{
void B();
}
public class UdpManager : IUdpManagerA, IUdpManagerB
{
public void A() { }
public void B() { }
}
public class UdpManagerFactory
{
private UdpManager Create() => new UdpManager();
public IUdpManagerA CreateOfA() => Create();
public IUdpManagerB CreateOfB() => Create();
}
UdpManagerFactory factory = new UdpManagerFactory();
IUdpManagerA a = factory.CreateOfA();
IUdpManagerB b = factory.CreateOfB();
Interfaces are a powerful tool to publish certain members while others can remain hidden.
While you might say yeah, but you can always cast IUdpManagerA to IUdpManagerB and vice versa to gain access to hidden members, and my answer is **this isn't safe because there's no clue that IUdpManagerA also implements IUdpManagerB and vice versa.
Oh, and I forgot to mention that you should throw away the ManagerType enumeration, because with interfaces you can always check if a given instance is A or B:
object instance = factory.CreateA();
if(instance is IUdpManagerA)
{
}
if(instance is IUdpManagerB)
{
}
or using as operator:
object instance = factory.CreateA();
IUdpManagerA a = instance as IUdpManagerA;
IUdpManagerB b = instance as IUdpManagerB;
if(a != null)
{
}
else if(b != null)
{
}
This is an extreme simple version of a factory build method based of an enum:
public enum ManagerType
{
A,B
}
public abstract class UDPManager
{
}
public class SomethingA : UDPManager
{
public void A()
{}
}
public class SomethingB : UDPManager
{
public void B()
{}
}
public class UdpManagerFactory
{
public UDPManager Build(ManagerType type)
{
if (type == ManagerType.A)
return new SomethingA();
if(type == ManagerType.B)
return new SomethingB();
throw new Exception("type not found");
}
}

Inject a singleton with parameters

Using Ninject, I have an interface that I want to bind to single instance of a concrete implementation. For example:
public interface IFoo { //... }
public class Foo { //... }
Now normally, I'd just bind something like this like so:
kernel.Bind<IFoo>().To<Foo>().InSingletonScope();
But, I need to add parameters to the constructor for Foo. Normally, again, that wouldn't be too much of a problem (I think):
kernel.Bind<IFoo>()
.To<Foo>()
.InSingletonScope()
.WithConstructorArgument("bar", myBar);
Now the problem is that I can't know the value of myBar at the time I set up all my bindings. I need to defer that until the first time I need an IFoo (and note, in reality I have several arguments to pass). So what I need is a singleton, that will be lazy initialized on first use and only gets arguments at that point.
What's the best way to approach this? I'm assuming something with Factory is probably the solution, but I don't quite see the right way to do this. I don't want to create a new Foo every time.
As in my comment above. the real problem is that you may not have the construction parameters when you need Foo. In this pattern you can Bind all your interfaces as you please and call IInitialiser.Initialise when you are ready (obvs you need to keep a reference or make it static).
Foo will throw an exception if you call it before its been properly set up
IFoo remains unchanged
IInitialiser implementations can be tweaked to poll a DB or respond to events or whatever suits your late configuration senario best
using System;
namespace UnitTestProject3
{
public interface IFoo
{
int GetAllTheFoo();
}
public interface IInitialiser
{
void Initialise(int x);
int GetX();
bool IsReady { get; }
}
public class Foo : IFoo
{
private bool isInitalised;
private int x;
private IInitialiser i;
public Foo(IInitialiser i)
{
this.isInitalised = false;
this.i = i;
}
protected void Init()
{
if (this.isInitalised)
{
return;
}
else if (i.IsReady)
{
x = i.GetX();
this.isInitalised = true;
return;
}
else
{
throw new Exception("you have not set x");
}
}
public int GetAllTheFoo()
{
Init();
return x;
}
}
}
You can use the Factory extension.
public interface IFooFactory
{
IFoo CreateFoo(string bar);
IFoo CreateFoo();
}
public interface IFoo
{
string Bar { get; set; }
}
public class Foo : IFoo
{
public string Bar { get; set; }
public Foo(string bar)
{
Bar = bar;
}
}
kernel.Bind<IFoo>().To<Foo>().InSingletonScope();
kernel.Bind<IFooFactory>().ToFactory();
IFoo foo1 = fooFactory.CreateFoo("myBar");
IFoo foo2 = fooFactory.CreateFoo("myDifferentBar"); // value is basically ignored here
IFoo foo3 = fooFactory.CreateFoo();
This will always return the same instance of Foo. Of course if you call the paremeterless method first it will result in an exception.
Given the other two answers, I could be completely missing the point of the question, but why would not something as simple as this work for you:
kernel.Bind<IFoo>().ToMethod(x => CreateFoo()).InSingletonScope();
CreateFoo will be responsible for constructing your single object with whatever set of parameters that you need. By the time CreateFoo is called you should already know what the parameters are.

What is the most elegant way to overload a constructor/method?

Overloading constructors and methods seems messy, i.e. simply differentiating them by the order and number of parameters. Isn't there a way, perhaps with generics, to do this cleanly so that, even if you just have one parameter (e.g. string idCode / string status) you could still differentiate them?
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TheForm tf1 = new TheForm("online", DateTime.Now);
TheForm tf2 = new TheForm(DateTime.Now, "form1");
}
}
public class TheForm
{
public TheForm(string status, DateTime startTime)
{
//...
}
public TheForm(DateTime startTime, string idCode)
{
//...
}
}
}
If you need that many overloads, perhaps your types are handling too much (see Single Responsibility Principle). Personally I rarely need more than one or a few constructors.
You could consider having a Fluent Builder for the class instead, although it's more work. This would allow you to write something like this:
var form = new TheFormBuilder().WithStatus("foo").WithStartTime(dt).Build();
It's more explicit, but not necessary better. It's definitely more work.
In C# 4, you can optionally write the parameter names when you invoke the constructor:
var form = new TheForm(status: "Foo", startTime: dt);
The new object initialization feature of .NET 3.0 is more flexible than an overloaded constructor. Here is a simple example:
public class Item
{
public string Name {get; set;}
public int Index {get; set;}
public string Caption {get; set;}
}
As it is written now, we can do the following in code:
var x = new item {Name=”FooBar”};
var x = new item {Name=”FooBar”, Index=”1”, Caption=”Foo Bar”};
I would only add an overloaded constructor to the class Item if I want to add functionality during property initialization. For example:
public class Item
{
public Item() {}
public Item(string name)
{
Name = name;
Caption = name; //defaulting name to caption
}
public Item(string name, int index) : this(name)
{
Index = index;
}
public Item(string name, int index, string caption) : this(name, int)
{
Caption = caption;
}
public string Name {get; set;}
public int Index {get; set;}
public string Caption {get; set;}
}
Note: If this was a child class, I could have chained to a parent constructor with the “base” keyword.
If I am writing a “configuration” type of class, I use Fluent Methods in place of Overloaded constructors.
For example, if I added these methods to the Item class:
public Item WithName(string name)
{
Name = name;
return this;
}
public Item WithIndex(int index)
{
Index = index;
return this;
}
public Item WithCaption(string caption)
{
Caption = caption;
return this;
}
I could write code like this:
var x = new Item().WithName(“FooBar”).WithIndex(“99”).WithCaption(“Foo Bar”);
The only way I can think of to differentiate the construction with a single parameter of a given type is to use a non-instance factory method, either on the type itself or in a factory class.
e.g. (on the type itself)
(untested)
public class TheForm
{
public static TheForm CreateWithId(string idCode)
{
}
public static TheForm CreateWithStatus(string status)
{
}
}
Before Fluent builders we sometimes managed to get around with parameter objects or setup objects:
public class FormSetup {
public string Status ...
public string Id ...
}
var frm = new MyForm(new FormSetup { Status = "Bla", ... });
Constructor Forwarding!
Use helper initialization classes to communicate the semantics of your overloads.
So, for instance, define
public class TheForm
{
public class TheForm(ById initializer)
{
//...
}
public class TheForm(ByStatus initializer)
{
//...
}
// ...
public class ById
{
public ById(DateTime startTime, string idCode)
// ...
}
public class ByStatus
{
public ByStatus(string status, DateTime startTime)
// ...
}
}
However, prefer using classes which are more generally usable if you can, not just for initalialization. You may want to factor your classes in a different way instead. I sense the possibility of a code smell: does your TheForm class contain too much business logic? Might you want to split out an MVC Controller, for instance?
In C# (like in many other programming languages) in this case you should use Factory Methods. Something like this:
class TheForm
{
public static TheForm CreateFromId(string idCode);
public static TheForm CreateFromStatus(string status);
}
or fiction parameters:
class TheForm
{
public TheForm(string idCode, int);
public TheForm(string status);
}
Or you can use Eiffel ;):
class THE_FORM create
make_from_id, make_from_status
feature
...
end
We use properties instead of overloading constructors, it's quite clean and easy to implement:
public class x {
public string prop1 {get;set;}
public DateTime prop2 {get;set;}
...
}
and then fill just the properties you need at instantiation time (and/or later)
var obj = new x() {
prop1 = "abc",
prop2 = 123
};
The benefit with this is it works with .Net 3.5 and makes it really clear what is being set. (as opposed to var obj = new x("abc", 123, true, false, ... etc) where you have to guess the meaning of each value, which can get really hairy when there are many overloads)
Here's an example:
Timespan.FromMilliseconds(double)
Timespan.FromSeconds(double)
Timespan.FromMinutes(double)
Timespan.FromHours(double)
Timespan.FromDays(double)
Isn't this where inheritence comes in?
Just have TheForm as a base class and then TheFormWithID and TheFormWithStatus child classes.
Have their constructors take string ID and string Status respectively passing back the DateTime value to the base class.
I haven't got any coding tools infront of me so please excuse the syntax. I'm sure that you'll figure it out.
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TheForm tf1 = new TheFormWithStatus(DateTime.Now, "online");
TheForm tf2 = new TheFormWithID(DateTime.Now, "form1");
}
}
public class TheForm
{
public TheForm(DateTime startTime)
{
//...
}
}
public class TheFormWithID : TheForm
{
public TheFormWithID (DateTime startTime, string idCode) : TheForm (startTime)
{
//...
}
}
public class TheFormWithStatus : TheForm
{
public TheFormWithStatus (DateTime startTime, string status) : TheForm (startTime)
{
//...
}
}
}
Or have TheForm as an abstract class.
Whether you're talking about constructors or not, overloading's pretty limited, and when you start to run up against its limits, that's a hint that it's not the right tool for the job.
It's worth looking at a well-designed API that uses overloading to get a sense of what kind of job the tool is good for. XmlReader.Create is a good example: It supports twelve different overloads. Twelve! And yet, it's actually completely sensible: when you look at them all, they boil down to what would, in Python, be a single calling signature with optional parameters:
XmlReader.Create(input [, settings [, parser_context]])
input, to this method, can be a string containing a URL or filename, a TextReader, or a Stream. But irrespective of its data type, it's still fundamentally the same thing: the source of the data that the XmlReader is going to read.
Now let's look at your case. Forget about data types for a moment. There's clearly some functional difference between a status and an idCode in your application. Your form is going to behave one way if it's given a status and another if it's given an idCode. The API that you're proposing conceals this functional difference. It should be illuminating it.
I would first consider the simplest possible approach, which uses no overloads at all:
TheForm(string idCode, string status)
Make your constructor throw an exception if both values are provided (or if both are null). Note that they're mutually exclusive in the documentation. Call it a day.
My second choice would be:
enum FormType
{
IdCode,
Status
};
TheForm(FormType type, string data)
This is less concise, but it has the very great merit of making the fact that this method supports multiple mutually-exclusive modes explicit.
I called that enum FormType because it seemed like a sensible name, given what I know so far, and the fact that this method's a constructor. But whenever you contemplate creating an enum to determine the type of an instance, you should at least consider the possibility that you should really be creating a type to determine the type of an instance:
class TheFormWhatUsesIdCode : TheForm {...}
class TheFormWhatUsesStatus : TheForm {...}
The functional difference between idCode and status probably relates to a functional difference between a form instantiated with idCode and a form instantiated with status. And that strongly suggests that they should be subclasses.
In all of this analysis, I've never once considered the possibility of doing what you actually asked for, which is to provide multiple overloads. I don't think overloading is the right tool for this job. If idCode were an int and status were a string I still wouldn't think that overloading were the right tool for this job, though I probably wouldn't have ended up noticing it until I had a lot of code I needed to refactor.
I am not getting what "messy" you found in multiple constructors. I felt the static methods for returning an instance of the object also a probable alternate.
But, if somebody want to have the fancy of a single constructor and still have different implementations, we can think of passing an object derived from some interface as the input to the constructor and might check the type of the input to create an instance. This is kind of an abstract factory in this case.
In one place we have a class like the following:
using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
base1 t1 = new type1();
class1 c1 = new class1(t1);
base1 t2 = new type2();
class1 c2 = new class1(t2);
//.....
}
}
public class class1
{
public class1(base1 mytype)
{
switch(mytype.type)
case mytype.types.type1
return createObjectOftype1();
case mytype.types.type2
return createObjectOftype2();
case mytype.types.type3
return createObjectOftype3();
}
public class1 createObjectOftype1()
{
//....
}
public class1 createObjectOftype2()
{
//...
}
public class1 createObjectOftype2()
{
//...
}
}
public class base1
{
publlic Enum Types {0 "type1",....
}
public class type1:base1
{
//.....
}
public class type2:base1
{
//.....
}
}
I personally dont like the idea of other classes being able to set my properties
so this allows my properties to be protected or private, but still have alot of the functionality described by other answers:
public class FooSettings
{
public bool Prop1 { get; set; }
public bool Prop2 { get; set; }
public TimeSpan Prop3 { get; set; }
public FooSettings()
{
this.Prop1 = false;
this.Prop2 = false;
this.Prop3 = new TimeSpan().ExtensionMethod(CustomEnum.Never);
}
public FooSettings BoolSettings
(bool incomingFileCacheSetting, bool incomingRuntimeCacheSetting)
{
this.Prop1 = incomingFileCacheSetting;
this.Prop2 = incomingRuntimeCacheSetting;
return this;
}
public FooSettings Prop3Setting
(TimeSpan incomingCustomInterval)
{
this.Prop3 = incomingCustomInterval;
return this;
}
public FooSettings Prop3Setting
(CustomEnum incomingPresetInterval)
{
return this.Prop3Setting(new TimeSpan().ExtensionMethod(CustomEnum.incomingPresetInterval));
}
}
public class Foo
{
public bool Prop1 { get; private set; }
public bool Prop2 { get; private set; }
public TimeSpan Prop3 { get; private set; }
public CallTracker
(
FooSettings incomingSettings
)
{
// implement conditional logic that handles incomingSettings
}
}
could then be consumed as:
FooSettings newFooSettings = new FooSettings {Prop1 = false, Prop2 = true}
newFooSettings.Prop3Setting(new TimeSpan(3,0,0));
Foo newFoo = new Foo(newFooSettings)
or
FooSettings newFooSettings = new FooSettings()
.BoolSettings(false, true)
.Prop3Setting(CustomEnum.Never)
Foo newFoo = new Foo(newFooSettings)
obviously a bit overkill for a simple class, but it gives alot of control over the types of data that can be funneled down to a single property, IE: TimeSpan can be parsed from a custom enum type using an extension method

Categories