while mocking an object using parametrized constructor, if the property being initialized within the constructor is virtual, Moq does not set property value. But if it is non-virtual property, Moq sets the value.
Following is my class I wants to mock.
public class Activity
{
private Activity() {}
public Activity(string code, string description, string option)
{
if(string.IsNullOrEmpty(code)) throw new ArgumentNullException("code");
if (string.IsNullOrEmpty(option)) throw new ArgumentNullException("option");
Code = code;
Description = description;
Option = option;
}
public virtual string Code { get; private set; }
public virtual string Description { get; private set; }
public virtual string Option { get; private set; }
}
This is how I try to mock it:
[TestMethod]
public void It_Creates_Mock_For_A_Class()
{
var mock = new Mock<Activity>("Code 1", null, "Option");
Assert.IsNotNull(mock.Object);
Assert.AreEqual("Code 1", mock.Object.Code);
}
The test method fails saying:
Assert.AreEqual failed. Expected:. Actual:<(null)>.
But if I remove the virtual keyword from all the property, it works and passes the test case.
I have to keep the properties virtual because of Entity Framework.
Any clue? How to get around this problem?
Found out that if "CallBase" property is set to true, it solved the problem.
By looking at the assembly in Object Browser, the summary says:
Summary:
Whether the base member virtual implementation will be called for mocked classes if no setup is matched. Defaults to false.
The code that works:
[TestMethod]
public void It_Creates_Mock_For_A_Class()
{
var mock = new Mock<Activity>("Code 1", null, "Option");
mock.CallBase = true;
Assert.IsNotNull(mock.Object);
Assert.AreEqual("Code 1", mock.Object.Code);
}
Related
I try to create a mock for an existing interface. When I try to read the value, I get a null reference exception
public interface MyInterface<T> : MyInterface
{
new T Value { get; set; }
}
public interface MyInterface : MyReadonlyInterface
{
new object Value { get; set; }
}
public interface MyReadonlyInterface
{
object Value { get; }
}
...
var i = Substitute.For<MyInterface<bool>>();
variable.Value = false;
Just after inititialize I see the value as "false". Later in the test, the value will become NULL. The usualy used
variable.Value.Returns(false)
also shows NULL.
How do I have to use NSubstitute to get the required "false" without changing the interface?
In my NinjectDependencyResolver: IDependencyResolver I have a AddBindings() method that for now I want it to return some hard coded values for me until I connect it to DB later.
The class and interface I want to mock and use in that AddBindings() method are like this:
public class Configuration
{
public string WebSiteNotActiveMessage { get; set; }
public bool IsWebSiteActive { get; set; }
}
public interface IConfigurationManager
{
Models.Configuration.Configuration ConfigFileValues { get; }
}
Now I wanted to mock the interface and return a value in my Ninject method so I started writing something like this but got stuck, not sure how I should do it:
private void AddBindings()
{
var config = Substitute.For<IConfigurationManager>();
config.ConfigFileValues.IsWebSiteActive = true;
config.ConfigFileValues.WebSiteNotActiveMessage = "Website is not active!!!";
// ?
}
In general* NSubstitute will not automatically substitute for members that return classes like Configuration, so you'll need to manually stub it:
var config = Substitute.For<IConfigurationManager>();
config.ConfigFileValues.Returns(new Configuration());
config.ConfigFileValues.IsWebSiteActive = true;
config.ConfigFileValues.WebSiteNotActiveMessage = "Website is not active!!!";
(* the exception being pure virtual classes)
Hope this helps.
The main problem regarding your interface is that your only property, ConfigFileValues, has only a getter. It should have also setter, which would initialize it from the class that would implement the interface. In terms of code that I suggest is this:
public interface IConfigurationManager
{
Models.Configuration.Configuration ConfigFileValues { get; set; }
}
We are creating a C# application using TDD and DI methodologies and NSubstitute.
We are writing a CreateThing method:
name and description strings as parameters
create a new Thing object
set the Name and Description properties of Thing from the method parameters
set the Status to Active
pass the Thing to a method on another class (via constructor injection) for further processing
We know how to write a test for the call to the other class by using Substitute.For and .Received().
How do we write tests for the Thing properties being set?
You can use Argument matchers namely Conditional matcher which looks like Arg.Is<T>(Predicate<T> condition). Your matcher could look like:
anotherClass.Received().Process(Arg.Is<Thing>(thing => !string.IsNullOrEmpty(thing.Name)));
Full listing:
public class Thing
{
public string Name { get; set; }
}
public class AnotherClass
{
public virtual void Process(Thing thing)
{
}
}
public class CreateThingFactory
{
private readonly AnotherClass _anotherClass;
public CreateThingFactory(AnotherClass anotherClass)
{
_anotherClass = anotherClass;
}
public void CreateThing()
{
var thing = new Thing();
thing.Name = "Name";
_anotherClass.Process(thing);
}
}
public class CreateThingFactoryTests
{
[Fact]
public void CreateThingTest()
{
// arrange
var anotherClass = Substitute.For<AnotherClass>();
var sut = new CreateThingFactory(anotherClass);
// act
sut.CreateThing();
// assert
anotherClass.Received().Process(Arg.Is<Thing>(thing => !string.IsNullOrEmpty(thing.Name)));
}
}
I have a situation where I have some DTO classes that should be implemented like:
public class City
{
public string Name { get; set; }
public State State { get; set; }
}
public class State
{
public string Name { get; set; }
}
The problem is, these are actually DTO classes for REST XML resources. And the City resource may include the State resource inline, or it may simply provide the resource ID (a URI). I am handling access to the DTO via the Repository pattern and would like it to be transparent to clients whether State is lazy loaded or not (like how NHibernate does with it's entity classes).
So my current plan is to use Castle DynamicProxy to create a proxy object when the REST Repository detects that the class isn't fully "hydrated" (i.e. not everything is inline). The proxy object will know how to lazy load attributes as needed.
To actually implement this, however, the only thing I've come up with is to have backing attributes for all relationships and put the Xml attributes on those. So the strategy looks like this:
[XmlType]
public class City
{
[XmlElement]
public string Name { get; set; }
[ToOneRestRelationship(BackingPropertyName = "StateBacking")]
public State State { get; set; }
[XmlElement(Name = "state")]
public ResourceBase StateBacking { get; set; }
}
[XmlType]
public class State
{
[XmlElement]
public string Name { get; set; }
}
Then the Repository object knows to set up the proxy object to either get the object from the StateBacking property and use that (inlined resource case) or do a REST request to lazily retrieve the State object (resource URI case, i.e. lazy) from the ID specified in the backing property.
Question
The issue is, this backing field is pretty ugly. What I would like is a way to have Castle generate a class that would have the backing property with the XmlElement attribute applied that I could pass to the XmlSerializer. Then my DTO classes could look more like the first example and wouldn't have to be aware that the actual serialising class has a backing property.
Is something like this possible with Castle or any other Proxy library?
After going an interesting and completely wrong way, i think it is indeed possible to create a backing field that won't be seen by clients. Since proxying works by inheriting from the proxied class, any property on the derived class won't be seen in the scope of the original class. So mixins are the way to go:
Given Foo
public class Foo
{
public virtual string Name { get; set; }
public virtual Bar bar { get; set; }
}
and Bar
public class Bar
{
public virtual string Name { get; set; }
}
We can declare an interface that will let us retrieve the backing field and an implementation
public interface IHasBarBackingField
{
Bar RetrieveBar();
}
public class HasBarBackingField : IHasBarBackingField
{
public HasBarBackingField()
{
// the constructor must contain ways to resolve the bar. Since
// the class is built while proxying you should have all the data
// available at this moment
}
public Bar RetrieveBar()
{
return new Bar(); // example, you could have a backing field somewhere in this class
}
}
Then you just have to mixin both classes when proxying:
var pg = new ProxyGenerator();
var hasBarBackingField = new HasBarBackingField();
var options = new ProxyGenerationOptions();
options.AddMixinInstance(hasBarBackingField);
var test = pg.CreateClassProxy<Foo>(options, new BarInterceptor());
and intercept the call interesting you in order to return the backing Bar
public class BarInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
if (invocation.Method.Name == "get_bar")
{
var hasBarBackingField = invocation.InvocationTarget as IHasBarBackingField;
invocation.ReturnValue = hasBarBackingField.RetrieveBar();
}
else
{
invocation.Proceed();
}
}
}
The HasBarBackingField class should be built to return either the direct object or retrieve the referenced REST object. Hope this helps
Based on what i've seen NSubstitute do i'd say it is possible, as long as your properties are virtual: http://nsubstitute.github.io/help/partial-subs/ .
Creating a City class with virtual property State that is then resolved at runtime using the substitution pattern should be feasable
public class City
{
public string Name { get; set; }
[StateId(10)]
public virtual State State { get; set; }
}
var sCity = Substitute.For<City>();
sCity.State.Returns((core) => {return null; // here you can access informations about the call});
Definitely doable, but it's terra incognita from here on!
I have the following Func method which i need to mock off
Func<Owned<ISomeInterface>> someMethod { get; set; }
but cant figure out how to mock it off using 'Moq' framework.
I have read a similar post on SO but still cant seem to mock it off, it always comes back with
Expression is not a method invocation: x => Invoke(x.someMethod )
or
A matching constructor for the given arguments was not found on the
mocked type. ----> System.MissingMethodException : Constructor on
type 'Owned`1Proxy40a9bf91815d4658ad2453298c903652' not found.
The Funct is defined as a property so you should use SetupSet within Moq
public interface IPersona
{
string nome { get; set; }
string cognome { get; set; }
Func<Owned<ISomeInterface>> somemethod { get; set; }
}
. In your test :
You create a mock for the Func:
Func<Owned<ISomeInterface>> somemethodMock = () => new Mock<Owned<ISomeInterface>>().Object;
THen you setup the mock for the Class containing the Func as a property and you setup the expectation on the Set method :
var obj = new Mock<IMyInterface>();
obj.SetupSet(x => x.somemethod = somemethodMock).Verifiable();
You create the container object for the mock:
//We pass the mocked object to the constructor of the container class
var container = new Container(obj.Object);
container.AnotherMethod(somemethodMock);
obj.VerifyAll();
Here is the definition of Another method of the Container class, if get the func as an input parameter and set it to the property of the contained object
enter public class Container
{
private IPersona _persona;
public Container(IPersona persona)
{
_persona = persona;
}
public void AnotherMethod(Func<MyClass<IMyInterface>> myFunc)
{
_persona.somemethod = myFunc;
}
}