I'm going to simplify a bit the problem:
In my tests, I use a mocked object (I mocked it because it calls a bdd) which I give in parameters to a method of another object (not mocked) whose purpose is to modify a property of this mocked object.
ModifyingClass myModifyingClass = new ModifyingClass();
Mock<ToModifyClass> mockedClass = new Mock<ToModifyClass>();
mockedClass.Setup(mc => mc.name).Returns("Test1");
myModifyingClass.modify(mockedClass.Object);
The method modify then try to set the property name of the mocked object, but it won't work, so maybe it's the normal behavior but I really need to test if all of this work and if the method modify set the property as I want.
As mentioned in the comments you need to setup the mocked class differently in order to retain the values passed to properties.
Reference Moq - Quickstart
Stub all properties on a mock (not available on Silverlight):
mock.SetupAllProperties();
The example test provided would then look like...
//Arrange
var myModifyingClass = new ModifyingClass();
var mockedClass = new Mock<ToModifyClass>();
mockedClass.SetupAllProperties(); //<-- this will allow property changes to be retained.
var model = mockedClass.Object;
//set the property now that it can be set
model.name = "Test1";
var expected = "expected value here";
//Act
myModifyingClass.modify(model);
//Assert
var actual = model.name;
Assert.AreEqual(expected, actual);
//... other assertions
In Moq one would need to setup the getter.
mockedClass.SetupGet(mc => mc.name).Returns("Test1");
Related
I am trying to write some unit tests for a piece of logic which uses DbContext.
In my unit tests, I mock the dbContext and set the expectations.
At one place my code looks like this:
var myVar= await dbContext.Set<MyModel>().Where(.. some conditions..).FirstOrDefaultAsync();
I am mocking this dbContext and setting up as follows:
var myModelVar = new MyModel();
myModelVar.Id = Guid.NewGuid();
var myModelDbSet = new TestDbSet<MyModel>();
myModelDbSet .Add(myModelVar );
mockDbContext.Setup(dbContext => dbContext.Set<MyModel>()).Returns(myModelDbSet);
However, in the above location in the code, the unit test returns null.
Earlier in the code, I set another dbContext expectation which returns correct value in the unit test:
var anotherModelVar = new AnotherModel();
mockDbContext.Setup(dbContext => dbContext.Set<AnotherModel>()
.FindAsync(It.IsAny<object>()))
.Returns(Task.FromResult(anotherModelVar ));
I receive null value for the TestDbSet expectation and cannot understand the reason why could this be happening?
I've written a piece of code that is responsible for creating an Issue.It uses a visitor pattern to set the Issue assignee.
Here's the code :
public Issue CreateIssue(IssueType type, string subject, string description, Priority priority, string ownerId)
{
var issue = new Issue
{
...
};
IssueManagerContext.Current.IssueAssignmentMethodResolver(type).Visit(issue);
...
return issue;
}
I would like to test the functionality of this code thus somehow I need to mock the behavior of a visitor. After studying different Mock libraries I decided to use Moq.
But I don't know how should I build a mock object that gets an argument from my code instead of hard coding it as it's shown in the quick start guide.
Here's what I have done so far :
var visitor = new Mock<IIssueVisitor>();
visitor.Setup(x => x.Visit(null));
You can only match a specific instance of an object if the test has the same reference as the SUT. The problem in your scenario is that your SUT creates the instance issue, and returns it at the end of the method. Your test cannot access it while the method is executing, which precludes your mock object from being able to match it.
You can configure your mock object to match any Issue instance with the following syntax:
visitor.Setup(x => x.Visit(It.IsAny<Issue>()));
You can also configure the mock to conditionally match an Issue instance:
// Matches any instance of Issue that has an ID of 42
visitor.Setup(x => x.Visit(It.Is<Issue>(theIssue => theIssue.ID == 42)));
If you want to match the reference of a specific instance of Issue, then you'll have to move the instantiation logic into some kind of abstraction (e.g., a factory) of which your test could provide a fake implementation. For example:
// In SUT
var issue = issueFactory.CreateIssue();
...
// In test
var stubIssue = new Issue{ ... };
var issueFactory = new Mock<IIssueFactory>();
var visitor = new Mock<IIssueVisitor>();
...
issueFactory.Setup(factory => factory.CreateIssue())
.Returns(stubIssue);
visitor.Setup(x => x.Visit(stubIssue));
Use the following syntax:
interface IFoo
{
int Bar(string baz);
}
var mock = new Mock<IFoo>();
mock.Setup(x => x.Bar(It.IsAny<string>()))
.Returns((string baz) => 42 /* Here baz contains the value your code provided */);
I am writing unit tests using Moq. I have created a mock object. Now when i try to mock its property i am getting error "An expression tree may not contain an indexed property"
here is my code.
public Node GetNode(IMyInterface interface, string itemName)
{
return interface.Items[itemName];
}
Here is the unit test
var expected = new Node();
var itemName = "TestName";
var mock = new Mock<IMyInterface>();
mock.Setup(f => f.Items[itemName]).Returns(expected);
var target = new MyClass();
var actual = target.GetNode(mock.Object, itemName);
Assert.AreEqual(expected, actual);
This line is giving me error.
mock.Setup(f => f.Items[itemName]).Returns(expected);
How can i moq this function.
Interface was a COM object and there were get function, so instead of directly accessing property using indexer use get function,
mock.Setup(f => f.get_Items(itemName)).Returns(expected);
Using Moq in ASP.NET Core 2.2, the get_Items setup does not work. But this does:
Mock<IConfiguration> configuration = new Mock<IConfiguration>();
configuration.Setup(x => x[key]).Returns(value);
For some objects I want to create default stubs so that common properties contains values. But in some cases I want to override my default behaviour. My question is, can I somehow overwrite an already stubbed value?
//First I create the default stub with a default value
var foo = MockRepository.GenerateStub<IFoo>();
foo.Stub(x => x.TheValue).Return(1);
//Somewhere else in the code I override the stubbed value
foo.Stub(x => x.TheValue).Return(2);
Assert.AreEqual(2, foo.TheValue); //Fails, since TheValue is 1
Using Expect instead of Stub and GenerateMock instead of GenerateStub will solve this:
//First I create the default stub with a default value
var foo = MockRepository.GenerateMock<IFoo>();
foo.Expect(x => x.TheValue).Return(1);
//Somewhere else in the code I override the stubbed value
foo.Expect(x => x.TheValue).Return(2);
Assert.AreEqual(1, foo.TheValue);
Assert.AreEqual(2, foo.TheValue);
I can't seem to Mock HttpServerUtilityBase using Rhino Mocks.
_mocks = new MockRepository();
_mockHttpContext = _mocks.DynamicMock<HttpContextBase>();
_mockHttpUtilityBase = _mocks.Stub<HttpServerUtilityBase>();
_mockHttpContext.Stub(c => c.Server).Return(_mockHttpUtilityBase);
var Server = _mockHttpContext.Server;
But server is set to Null. What am I doing wrong?
Are you running in an HTTP Context? Otherwise, c.Server makes no sense, and is therefore null.
You need to expose the properties of the mocked object _mockHttpUtilityBase to the Mocked HttpContextBase. To do so, replace line 4 with the following:
_mockHttpContext.Stub(c => c.Server).Return(_mockHttpUtilityBase.object);