I have a code listed below inside one of my method which I would like to test:
using (var obj1 = provider.GetObj1Instance())
{
/* Do some stuff */
obj1.DoAction();
}
provider is an object which I mocked:
provider = MockRepository.GenerateMock<IProvider>();
but method GetObj1Instance() returns concrete-typed object. Right now after mocking I get NullRefrenceException, because method GetObj1Instance() from mocked provider returns null.
Then I stubbed obj1:
var stubbedObj1 = MockRepository.GenerateStub<Obj1>();
provider.Stub(o => o.GetObj1Instance()).Return(stubbedObj1);
but it's not sufficient, because inside obj1.DoAction(); there is reference to private variable which throws NullReferenceException
During test execution, I would like to not execute obj1.DoAction() or just to register that it was invoked. How to achieve that?
This line below doesn't prevent DoAction method from original execution.
stubbedObj1.Stub(u => u.DoAction()).Do(new Action(() => { }));
Related
I have a section of code that calls a factory, and then uses the returned object.
var myServiceObject = factoryService.GetTheObject(myParam);
myServiceObject.DoSomeWork(someData, moreData); // returns void
I'm writing a test with Automock where I want to verify that I call the factory and that I attempt to use the object.
For mocking the factory I'm assuming I need it to return an instance?
mock.Mock<IFactoryService>().Setup(x => x.GetTheObject(It.IsAny<paramType>()))
.Returns({insertSomething});
I was going to use a mock object, and do something like this:
mock.Mock<IMyService>().Setup(x => x.DoSomeWork(...));
var mockOfMyService = mock.Provide<IMyService>(new MockOfMyService()); // MockOfMyService inherits from IMyService
mock.Mock<IFactoryService>().Setup(x => x.GetTheObject(It.IsAny<paramType>()))
.Returns(mockOfMyService);
...
mock.Mock<IFactoryService>().Verify(...); // This passes
mock.Mock<IMyService>().Verify(x => x.DoSomeWork(...), Times.Once); // This errors
But I'm getting an invalid cast exception on the verify. Any good examples out there? What am I doing wrong?
So, for this one, I received some help outside of SO. Here's what worked for me:
mock.Mock<IMyService>().Setup(x => x.DoSomeWork(...));
var mockOfMyService = mock.Mock<IMyService>().Object; // Slight change here
mock.Mock<IFactoryService>().Setup(x => x.GetTheObject(It.IsAny<paramType>()))
.Returns(mockOfMyService);
...
mock.Mock<IFactoryService>().Verify(...); // This passes
mock.Mock<IMyService>().Verify(x => x.DoSomeWork(...), Times.Once); // And now this passes
I am writing unit tests for the existing Web API 2 project. For which i am using Ploeh Autofixture and Moq.
Test Method :
UPDATED
[Test]
public async Task Service1_TestMethod() {
//some code here
var fakeemail = FakeBuilder.Create<string>("test1234#test.com");
var fakeUserInvite =
FakeBuilder.Build<UserInvite>()
.With(i => i.EmailAddress, fakeemail)
.With(i => i.Username, fakeemail)
.Create();
var fakeUserToken = FakeBuilder.Create<string>();
var fakeHttpResponseMessage =
Fixture.Build<HttpResponseMessage>()
.With(h => h.StatusCode, HttpStatusCode.OK).Create();
//Here i am mocking another service method. Whose response is HttpResponseMessage.
Service2.Setup(i => i.AddUser(fakeUserInvite, fakeUserToken))
.ReturnsAsync(fakeHttpResponseMessage);
var result = await Service1.AddUser( /* */);
}
Service1 Method :
public async Task<bool> AddUser(/* */)
{
var response = await Service2.AddUser(userInvite, userToken); // response is null even after mocking it.
// Add user code follows bassed on the above response.
}
If i comment the Service2.AddUser call then everything works. There is a lot of code in that method apart from this call. I am having problem with only this call. If this call returns the mocked HttpResponseMessage then everything works.
Service2 is an external API. I am just wondering how to mock HttpResponseMessage. Any help is appreciated.
The stub you create with:
service2.Setup(i => i.AddUser(fakeUserInvite, fakeUserToken))
.ReturnsAsync(fakeHttpResponseMessage);
requires the actual call to be made with the exact same objects as the ones referenced by fakeUserInvite and fakeUserToken in order for Moq to return fakeHttpResponseMessage.
This is because Moq's argument matching verifies that the arguments specified in the stub are equal to the ones made in the actual call. If they are not, the stub won't match and Moq will return the default value for the method's return type – in this case null since HttpResponseMessage is a reference type.
To solve this problem, you can either make sure that the fakeUserInvite and fakeUserToken references are being passed to the actual service2.AddUser call or you can use somewhat less specific argument constraints.
Here's an example:
service2.Setup(i => i.AddUser(
It.Is<UserInvite>(u => u.EmailAddress == fakeEmail &&
u.Username == fakeEmail),
fakeUserToken))
.ReturnsAsync(fakeHttpResponseMessage);
Here we're stating that the AddUser method should be called with:
A UserInvite object whose EmailAddress and Username properties have the same value as fakeEmail as the first argument
The same value as fakeUserToken as the second argument
If the actual values of those arguments don't matter to your specific test scenario, you can tell Moq to always return fakeHttpResponseMessage regardless of what arguments AddUser is being called with by saying:
service2.Setup(i => i.AddUser(
It.IsAny<UserInvite>(),
It.IsAny<string>()))
.ReturnsAsync(fakeHttpResponseMessage);
I want to assert that a call on my real object (system under test) was called. Here is my test
// Arrange
var contextFactory = A.Fake<IContextFactory>();
var db = A.Fake<IDatabase>();
A.CallTo(() => contextFactory.GetContext()).Returns(db);
var vm = new MainViewModel(contextFactory);
// Act
vm.Loaded();
// Assert
A.CallTo(() => vm.LoadModels(db)).MustHaveHappened();
I'm getting an ArgumentException that says "The specified object is not recognized as a fake object." How do I test that the LoadModels() method in my MainViewModel gets called from the Loaded() method?
EDIT
The reason I'm doing it this way is because the Loaded() method calls a bunch of other methods when the app starts and I don't want to have to setup all the other stuff for each test, I just want to make sure that all the proper methods get called and then test them individually. I'm open to suggestion for a better way of going about this.
Here are the Loaded and LoadModels methods
internal virtual void Loaded()
{
using (var db = _contextFactory.GetContext())
{
LoadModels(db);
// bunch of other method calls
}
}
internal virtual void LoadModels(IDatabase db)
{
Models = new ObservableCollection<Model>(db.Models);
}
It looks like you're verifying a method (vm.LoadModels) that isn't part of the fake (db). You can only verify methods on a fake, not methods that happen to take the fake as an argument.
I ended up moving the functionality of LoadModels() to another class that implements IStartupDataLoader and then I was able to test it like this
// Arrange
var sdl = A.Fake<IStartupDataLoader>();
var exp = A.Fake<ObservableCollection<Model>>();
A.CallTo(() => sdl.LoadModels()).Returns(exp);
var sut = new MainViewModel(sdl);
// Act
sut.Loaded();
// Assert
Assert.That(exp == sut.Models);
I'm new to C# Moq (used Rhino Mochs in the past) and needing to test a sequence of calls to the same method. I found this cool solution that tests a sequence of return values:
http://haacked.com/archive/2009/09/29/moq-sequences.aspx/
public static class MoqExtensions
{
public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup,
params TResult[] results) where T : class {
setup.Returns(new Queue<TResult>(results).Dequeue);
}
}
What I need to do is to test the values sent as a parameter to the method (rather than the values it returns) in a sequence of calls to the same method.
Rough outline ...
var expression = new MyExpressionThing();
processor.Setup(x => x.Execute(expected1)).Verifiable();
processor.Setup(x => x.Execute(expected2)).Verifiable();
processor.Setup(x => x.Execute(expected3)).Verifiable();
expression.ExecuteWith(processor.Object);
processor.Verify();
Here's what I've attempted but I'm getting the exception:
"System.ArgumentException : Invalid callback. Setup on method with parameters (String,Object[]) cannot invoke callback with parameters (String)."
// Arrange
var processor = new Mock<IMigrationProcessor>();
IList<string> calls = new List<string>();
processor.Setup(p => p.Execute(It.IsAny<string>()))
.Callback<string>(s => calls.Add(s));
// Act
var expr = new ExecuteScriptsInDirectoryExpression { SqlScriptDirectory = #"SQL2\1_Pre" };
expr.ExecuteWith(processor.Object);
// Assert
calls.ToArray().ShouldBe(new[]
{ "DELETE FROM PRE1A", "DELETE FROM PRE1B", "INSERT INTO PRE2\r\nLINE2" });
Looks like I'm using boilerplate code from the Moq "Getting Started" examples:
This link discusses this exception and links to the Moq code that fires it.
http://dailydevscoveries.blogspot.com.au/2011/04/invalid-callback-setup-on-method-with.html
I would use a callback to capture the parameter each time the mock is called, and then assert the result:
var parameters = new List<ParameterType>();
processor.Setup(x => x.Execute(It.IsAny<ParameterType>()))
.Callback<ParameterType>(param => parameters.Add(param));
CallCodeUnderTest(processor.Object);
Assert.That(parameters, Is.EqualTo(new[] { expected1, expected2, expected3 }));
Update: Based on the error message you quoted, it looks like the method you're mocking takes a second parameter that's a params object[]. You don't need to specify that parameter when you call the method (which is why you don't need it in the Setup lambda), but you do need to specify it in the generic type parameters to .Callback. Change your Callback line to:
.Callback<string, object[]>((s, o) => calls.Add(s));
Using Microsoft Test Framework and Moq I'm trying to verify if a log4net method was called.
[TestMethod()]
public void Log_Info_When_Stuff_Is_Done()
{
SampleClass sampleObject = new SampleClass();
Mock<log4net.ILog> logMockObject = new Mock<log4net.ILog>();
sampleObject.Log = logMockObject.Object;
sampleObject.DoStuffAndLogInfo();
logMockObject.Verify(moqLog => moqLog.Info("do stuff got called"), Times.AtLeastOnce());
}
I get an exception on Verify call saying that
Expected invocation on the mock at least once, but was never
performed: moqLog => moqLog.Info("do stuff got called") No setups
configured. No invocations performed.
What am I doing wrong?
update the problem was with a getter for SampleClas.Log property. I was always returning LogManager.GetLogger(...); even when the property was already set to a ILogProxy. I was under impression that the property's get accessor won't be called because I've set up a proxy like so sampleObject.Log = logMockObject.Object;
Right now Moq is verifying that DoStuffAndLogInfo calls Info with the exact string "do stuff got called". If it's actually calling Info with a different argument, and you don't care what the actual argument is, use the following instead:
logMockObject.Verify(moqLog => moqLog.Info(It.IsAny<string>()), Times.AtLeastOnce());
The test is correctly set up.
Check your sut to see if Log.Info actually gets called inside the DoStuffAndLogInfo method.
This doesn't look to be the original poster's problem, but in my case I had a very similar error message. It was due to my .Verify() call before the actual execution. For example, this is wrong:
SampleClass sampleObject = new SampleClass();
Mock<log4net.ILog> logMockObject = new Mock<log4net.ILog>();
logMockObject.Verify(moqLog => moqLog.Info(It.IsAny<string>()), Times.AtLeastOnce());
sampleObject.Log = logMockObject.Object;
sampleObject.DoStuffAndLogInfo();
....but this is right:
SampleClass sampleObject = new SampleClass();
Mock<log4net.ILog> logMockObject = new Mock<log4net.ILog>();
sampleObject.Log = logMockObject.Object;
sampleObject.DoStuffAndLogInfo();
logMockObject.Verify(moqLog => moqLog.Info(It.IsAny<string>()), Times.AtLeastOnce());