I'm new to Moq. I'm mocking a PagingOptions class. Here is how the class looks like:
public class PagingOptions
{
[Range(1, 99999, ErrorMessage = "Offset must be greater than 0.")]
public int? Offset { get; set; }
[Range(1, 100, ErrorMessage = "Limit must be greater than 0 and less than 100.")]
public int? Limit { get; set; }
public PagingOptions Replace(PagingOptions newer)
{
return new PagingOptions
{
Offset = newer.Offset ?? Offset,
Limit = newer.Limit ?? Limit
};
}
}
Here is my mock version of the class,
var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.Setup(po => po.Limit).Returns(25);
mockPagingOptions.Setup(po => po.Offset).Returns(0);
I get the below error when setting up the property values. Am I making something wrong. Looks like I cannot Moq concrete class? Only Interfaces can be Mocked? Please assist.
Thanks,
Abdul
Moq creates an implementation of the mocked type. If the type is an interface, it creates a class that implements the interface. If the type is a class, it creates an inherited class, and the members of that inherited class call the base class. But in order to do that it has to override the members. If a class has members that can't be overridden (they aren't virtual, abstract) then Moq can't override them to add its own behaviors.
In this case there's no need to mock PagingOptions because it's easy to use a real one. Instead of this:
var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.Setup(po => po.Limit).Returns(25);
mockPagingOptions.Setup(po => po.Offset).Returns(0);
Do this:
var pagingOptions = new PagingOptions { Limit = 25, Offset = 0 };
How do we determine whether or not to mock something? Generally speaking, we mock something if we don't want to include the concrete runtime implementation in our test. We want to test one class not both at the same time.
But in this case PagingOptions is just a class that holds some data. There's really no point in mocking it. It's just as easy to use the real thing.
I had the same error, but in my case I was trying to mock the class itself and not its interface:
// Mock<SendMailBLL> sendMailBLLMock = new Mock<SendMailBLL>(); // Wrong, causes error.
Mock<ISendMailBLL> sendMailBLLMock = new Mock<ISendMailBLL>(); // This works.
sendMailBLLMock.Setup(x =>
x.InsertEmailLog(
It.IsAny<List<EmailRecipient>>(),
It.IsAny<List<EmailAttachment>>(),
It.IsAny<string>()));
In case you reached this question based on the original title Non-overridable members may not be used in setup / verification expressions and none of the other answers have helped you may want to see if reflection can satisfy your test needs.
Suppose you have a class Foo with a property defined as public int I { get; private set; }
If you try the various methods in the answers here few of them will work for this scenario. However you can use .net reflection to setup a value of an instance variable and still keep fairly good refactoring support in the code.
Here is a snippet that sets a property with a private setter:
var foo = new Foo();
var I = foo.GetType().GetProperty(nameof(Foo.I), BindingFlags.Public | BindingFlags.Instance);
I.SetValue(foo, 8675309);
I do not recommend this for production code. It has proven very useful in numerous tests for me. I found this approach a few years ago but needed to look it up again recently and this was the top search result.
I want to improve Scott's answer and give a general answer
If the type is a class, it creates an inherited class, and the members of that inherited class call the base class. But in order to do that it has to override the members. If a class has members that can't be overridden (they aren't virtual, abstract) then Moq can't override them to add its own behaviors.
In my situation i had to make the prop virtual. So answer to your class code is:
public class PagingOptions {
[Range (1, 99999, ErrorMessage = "Offset must be greater than 0.")]
public virtual int? Offset { get; set; }
[Range (1, 100, ErrorMessage = "Limit must be greater than 0 and less than 100.")]
public virtual int? Limit { get; set; }
public PagingOptions Replace (PagingOptions newer) {
return new PagingOptions {
Offset = newer.Offset ?? Offset,
Limit = newer.Limit ?? Limit
};
}
}
use same:
var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.Setup(po => po.Limit).Returns(25);
mockPagingOptions.Setup(po => po.Offset).Returns(0);
On occasion you may be working with a class from a third party library that has properties which can be directly set or mocked.
Where the answer by above is not sufficient you can also invoke the setter method directly, for example where a class has a property called "Id" with no accessible setter:
var idSetter = account.GetType().GetMethod("set_Id", BindingFlags.Instance | BindingFlags.NonPublic);
idSetter!.Invoke(account, new[] { "New ID Here" });
In my case I was mocking a public method which was not virtual. Making the method virtual made the trick.
As an old Java developer, I'm used to the approach that all public methods are already virtual, there is no need to mark them separately as virtual so that sub classes can override them. C# is different here.
Maybe someone can explain if it is ok to mark a public method in a production code as virtual for testing purposes in C#.
Related
To further explain: i have a class let's say A, with a property of type let's say X; what i would like to do is to be able to instantiate A somewhere and assign the attribute using the instance without accessing the property itself or using methods, and possibly doing some other operation. Something like this:
public class A
{
private X _inside; //it actually can be public also
private DateTime _timeStamp;
public A() {X = new X();}
}
A anInstance = new A();
X aParameter = new X();
anInstance = aParameter
aParameter should be set to the _inside property of anInstance, while also assign DateTime.UtcNow to _timeStamp. Is it possible to do so? I am aware that doing so through a method or get and set is way easier, i'd get the same result and is possibly more efficient, but i would like to do so.
Also, I don't know if this thing has a specific name, therefore this question may be a duplicate; I am highlighting this because i had a problem with circular headers once but i didn't know that they were called so and my question was marked as a duplicate (not an english native seaker), which is not a problem as long as pointing we have an answer.
Anyway, thanks in advance!
Edit lexicon fixed as suggested in the comments
I believe what you're asking for is similar to VB classic's default properties1. Imagine that C# (and .NET in general) had adopted this concept, and that we're allowed to declare one2:
//Not legal c#
public class A
{
public default A _inside {get;set; }
private DateTime _timeStamp;
public A() {}
}
It's perfectly legal for classes to have properties of their own types, and introducing restrictions just for these default properties to avoid the problems I'm about to talk about are worse than disallowing the existence of these default properties3.
So you now have the code:
A anInstance = new A();
A aParameter = new A();
anInstance = aParameter;
Pop quiz - what does line 3 do? Does it assign _inner? Of does it reassign anInstance?
VB classic solved this issue by having two different forms of assignment. Set and Let. And it was a frequent source of bugs (Option Explicit being off by default didn't help here either).
When .NET was being designed, the designers of both C# and VB.Net looked at this and said "nope". You can have indexers (c#)/default properties (VB.Net) but they have to have additional parameters:
public class A
{
private Dictionary<int,A> _inner = new Dictionary<int,A>();
public A this[int i] {
get { return _inner[i]; }
set { _inner[i] = value; }
}
private DateTime _timeStamp;
public A() {}
}
And now we can disambiguate the different assignments in a straightforward manner:
A anInstance = new A();
A aParameter = new A();
anInstance = aParameter;
anInstance[1] = aParameter;
Lines 3 and 4 are, respectively, reassigning the reference and reassigning the property value.
1VB.Net does have default properties but, as discussed later, they're not precisely the same as VB classic's.
2Note that we can't assign it an instance in the constructor now - that would lead to a stack overflow exception since constructing any instance of A would require constructing an additional instance of A which would require constructing an additional instance of A which would...
3A concrete example of this would be a Tree class that has subtrees and a SubTree class that inherits from Tree and has a Parent property of tree. If that were the "default property" for the SubTree class you'd encounter these same property/reference assignment issues discussed lower down if trying to assign a parent of a subtree of a subtree.
Which basically means that you have to disallow default properties of both the actual type in which it's declared and any type to which it's implicitly convertible, which includes all types in its inheritance hierarchy.
Did you think about inheritance?
public class A : X
{
private DateTime _timeStamp;
public A() : base() {}
}
A anInstance = new A();
X aParameter = new X();
anInstance = (A)aParameter;
In my domain layer I create a lot of classes which looks like this
public class Route
{
public Route(Location origin, Location destination)
{
this.Origin = origin;
this.Destination = destination;
}
public Location Origin { get; }
public Location Destination { get; }
}
Now I need to unit-test this constructor
[Test]
public void PropertiesAreAssigned()
{
var origin = new Location(...);
var destination = new Location(...);
var route = new Route(origin, destination);
route.Origin.Should().Be(origin);
route.Destination.Should().Be(destination);
}
I have quite a few of those classes and tests which are very similar to each other. What I'd like is to have some kind of method which just accepts the type arguments, and then does all the testing for me, i.e.
instantiate a variable per constructor parameter (with whole graph of dependencies needed)
pass these variables to constructor
checks that the property values are assigned correctly
I'm pretty sure I can do this with a bit of reflection, but maybe is there an existing library for doing that? More tests are welcome, e.g.
Testing the null argument throws the proper exception
Testing that Equals and GetHashCode are implemented correctly
For me testing a simple constructor, simple accessors and mutators are a bad practice... It will be covered with behavioral (with intention) test. The less you test implementation details, the more your tests will be robust and resist to changes.
Testing constructor with complex behavior can be useful. But I often try to don't have any complex behavior in my constructors ^^
I've come across a problem when writing a unit test where in the method I'm calling it doesn't modify the mock object I've passed in. I'm not sure if there's just something obvious I'm missing?
I've setup the mock as follows:
var mockList = new List<Mock<IDocument>>();
for (int i = 0; i < 4; i++)
{
var mockDocument = new Mock<IDocument>();
mockDocument.Setup(t => t.DocumentNo).Returns(i.ToString());
mockList.Add(mockDocument);
}
mockDocumentRepository.Setup(x => x.GetDocuments(It.IsAny<string>(), It.IsAny<string>()))
.Returns(mockList.Select(m => m.Object).ToList());
In the executed method, if I attempt to modify another property on the mocked class (for example t.DocumentName) the value remains Null. Is there anyway to setup that property to accept a modification?
The reason I'm doing this is to test whether the collection of documents has been modified by another collection in the method. Not sure if there's better way's of doing this?
Moq will leave all methods unimplemented unless instructed to do otherwise, and that includes properties. If you use mockDocument.SetupProperty(doc => doc.DocumentName); it will implement the property as a regular auto-property. You can use mockDocument.SetupAllProperties() if you want all properties to be auto-implemented, but you'll still have to do it for every mock object.
You could also consider making a stub instead of a mock:
public class StubDocument : IDocument
{
public string DocumentNo { get; set; }
public string DocumentName { get; set; }
...
}
In general, I find that stubbing is often preferable to mocking when dealing with very simple interfaces, as seems to be the case with your IDocument.
I have an object that takes plenty of parameters to its constructor (from 9 to 13 depending on use).
I want to avoid the ugliness of new MyObject(param1, param2, param3 ... param13).
My first attempt was to create a class MyObjectParams with properties with public getters and setters, it gives something like that :
var objectParams = new MyObjectParams
{
Param1 = ...,
Param2 = ...,
...
};
I see some big projects like SlimDX for their PresentParameters use this design. It looks better. But the class is not immutable.
I'd like my MyObjectParams to be immutable while still using a clean construction style. This is how it would look like with an immutable class :
var objectParams = new MyObjectParams
(
param1,
param2,
...
);
Note: it's just the long constructor line broken into several, so it's cleaner but still not as readable as initializers.
I was thinking of using named parameters to get both an immutable class and a more or less clean code, but I'm not sure whether this actually is a good idea:
var objectParams = new MyObjectParams
(
param1: ...,
param2: ...,
...
);
Should I use named parameters? Can you think of a better approach to solve this problem?
Edited regarding an answer below: unfortunately, I don't really think the design is bad. The 9 parameters really are required and remain constant throughout the entire life of the object. I cannot provide a default value for them as it is completely usage-dependant.
Have you looked into designing a solution in which you wouldn't need this amount of parameters? Having a lot of parameters makes the code very tightly coupled which reduces maintainability. Maybe you can redesign a small amount of code to a design which better separates the responsibilities of the class?
I really like the way The Zen of Python says a few things:
Simple is better than complex.
Complex is better than complicated.
[...]
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
I believe that having a dedicated Options class of some kind with the exhaustive list of all possible parameters is a good idea. Allow your MyObject constructor to require an Options instance, and then store a reference to the instance as a field on MyObject and refer to its getters/setters. (Storing the reference will be much superior to trying to parse the options and transfer their values to the MyObject instance. Now that would be messy.) With all data access delegated to the Options class, you will have successfully encapsulated the object's configuration, and you've designed a simple API for option access as the same time.
If Options has no reason to be publicly accessible, make it a private class definition and then you're free to maintain changes to Options logic without modifying MyObject. I believe that is a fair solution to you as the developer, and doesn't commit atrocities.
The constructor could have only a small number of parameters, the ones required for proper object initialization. You could then have a number of properties that can be set after the object has been constructed. You can set default values for those properties in the constructor and the client can set the ones he/she requires.
class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
Address = "Unknown";
Email = "Unknown";
}
public string Name {get; private set;}
public int Age {get; private set;}
public string Email {get; set;}
public string Address {get; set;}
}
Person p = new Person("John Doe", 30);
p.Email = "john.doe#example.org";
You could use the builder pattern to construct an immutable object.
public sealed class ComplexObject
{
public int PropA { get; private set; }
public string PropB { get; private set; }
public sealed class Builder
{
int _propA;
string _propB;
public Builder SetPropA(int propA)
{
// validate
_propA = propA;
return this;
}
public Builder SetPropB(string propB)
{
// validate
_propB = propB;
return this;
}
public CustomObject ToCustomObject()
{
return new CustomObject
{
PropA = _propA,
PropB = _propB
};
}
}
}
Usage
var custom =
new CustomObject.Builder()
.SetPropA(1)
.SetPropB("Test")
.ToCustomObject();
Final Thoughts
Despite my previous suggestion I am in no way against using named parameters if they are available.
I have the following code:
public class Parent
{
public string MyField { get; set; }
}
public class Child : Parent
{
protected new int MyField { get; set; }
}
I try and access this with:
static void Main(string[] args)
{
Child child = new Child();
child.MyField = "something";
}
Visual studio 2008 compiles this without comment, but under Mono (2.4.2, Ubuntu) I get the error message
'HideTest.Child.MyField' is inaccessible due to its protection level (CS0122)
Is one implementation or the other more compliant with the standard here?
Edit: Thanks to all the people who have pointed out the bad design. Unfortunately it's a third-party library and changing it significantly isn't practical.
From ECMA-334 (the C# spec) ยง10.7.1.2 :
A declaration of a new member hides an inherited member only within the scope of the new member.
You can see this behavior by running this test on Microsoft's implementation.
using System;
using NUnit.Framework;
namespace ScratchPad
{
[TestFixture]
public class Class1
{
[Test]
public void InheritanceHiding()
{
var b = new Base();
var d = new Derived();
var baseSomeProperty = b.SomeProperty;
var derivedSomeProperty = d.SomeProperty;
b.GetSomeProperty();
d.GetSomeProperty();
}
}
public class Base
{
public string SomeProperty
{
get
{
Console.WriteLine("Getting Base.SomeProperty");
return "Base.SomeProperty";
}
}
public string GetSomeProperty()
{
return SomeProperty;
}
}
public class Derived : Base
{
protected new int SomeProperty
{
get
{
Console.WriteLine("Getting Derived.SomeProperty");
return 3; //Determined by random roll of the dice.
}
}
public new int GetSomeProperty()
{
return SomeProperty;
}
}
}
Which will output:
Getting Base.SomeProperty //(No Controversy)
Getting Base.SomeProperty //(Because you're calling from public scope and the new member is in protected scope, there is no hiding)
Getting Base.SomeProperty //(No Controversy)
Getting Derived.SomeProperty //(Now because you're calling from protected scope, you get the protected member).
So the property you're accessing from your Main() should be the base class property (as it is in MS.NET), not the derived property (as in Mono), because the new derived member only hides the 'old' base member in protected scope.
Mono is doing something wrong here according to the spec.
Jason's answer is correct but he asks for a justification of this behaviour. (Namely that a hiding method is only hiding within the scope of the hiding method.)
There are a number of possible justifications. One in particular is that this is yet another way in which the design of C# mitigates the Brittle Base Class problem.
FooCorp makes Foo.DLL:
public class Foo
{
public object Blah() { ... }
}
BarCorp makes Bar.DLL:
public class Bar : Foo
{
// stuff not having to do with Blah
}
ABCCorp makes ABC.EXE:
public class ABC
{
static void Main()
{
Console.WriteLine((new Bar()).Blah());
}
}
Now BarCorp says "You know, in our internal code we can guarantee that Blah only ever returns string thanks to our knowledge of our derived implementation. Let's take advantage of that fact in our internal code."
public class Bar : Foo
{
internal new string Blah()
{
object r = base.Blah();
Debug.Assert(r is string);
return (string)r;
}
}
ABCCorp picks up a new version of Bar.DLL which has a bunch of bug fixes that are blocking them. Should their build break because they have a call to Blah, an internal method on Bar? Of course not. That would be terrible. This change is a private implementation detail that should be invisible outside of Bar.DLL.
In general, the .NET implementation of C# should probably be considered "canon". From the documentation on the new Modifier:
A constant, field, property, or type introduced in a class or struct hides all base class members with the same name.
... it seems like the Mono implementation is more correct given this definition. It should be hiding the implementation of MyField in the Parent class, and therefore it should only be accessible with the int MyField signature from the Child class.
Prelude: This code is crazy. If you actually have code in your app like this, fix it now. Either make them both protected or both public!
Regarding the error: The CLR has a lot of really strange 'edge case' rules in it for dealing with things like this. The best place to look for this kind of stuff is usually Eric Lippert's blog.
In saying that though, it looks like mono is actually doing the more sensible thing here in my opinion.
On second look, the C# one makes more sense once you factor in the 'behind the scenes' stuff.
Properties are not "first class" in MSIL. A property in C# or VB is just compiled down to a get and set method (the compiler also sticks an attribute somewhere for bookkeeping).
int MyField { get; set; } will actually produce MSIL for two methods:
void set_MyField(int value);
int get_MyField();
Now, given that your new method has a different type, you'll end up with the following 2 setter methods.
void set_MyField(int value);
void set_MyField(string value);
When you call x.MyField = "string" you're just calling one of those methods. This then boils down to a normal method overloading scenario. It's perfectly valid to have two methods with the same name that take different parameters, so the compiler will just select the string one and carry on it's merry way.
So yeah. The C# one makes sense if you know how the internals work, the Mono one makes more sense if you don't.
Which one is "more correct"? Ask Eric Lippert :-)
Just adding my 2 cents) That's a Mono bug, here is the description.
IMHO the difference is that MS.NET recognize the type string for MyField and sets the value of Parent property and in Mono in just tries to access MyField in Child class.
You are making something that's available through the base class unavailable through the child. You can try that, but it won't actually do anything. People can always just do this:
Parent child = new Child();
and call the method. So if you want the field to be hidden, declare a new one and keep the inherited one public.