Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass-through parameter values in Moq?

I need to mock HttpResponseBase.ApplyAppPathModifier in such a way that the parameter ApplyAppPathModifier is called with is automatically returned by the mock.

I have the following code:

var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(/*capture this param*/))
                .Returns(/*return it here*/);

Any ideas?

EDIT:

Found a solution on the first page of Moq documentation (http://code.google.com/p/moq/wiki/QuickStart):

var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.IsAny<string>)
                .Returns((string value) => value);

I suddenly feel a lot stupider, but I guess this is what happens when you write code at 23:30

like image 458
Arnold Zokas Avatar asked Nov 01 '11 23:11

Arnold Zokas


People also ask

How do you do mocks with out parameters?

Mocking this using Moq is pretty straightforward: _mockSub = "subword"; _testOrthoepedia = new Mock<IOrthoepedia>(MockBehavior. Strict); _testOrthoepedia .

How do you mock a method in Moq?

First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.

What is verifiable in Moq?

Verifiable is to enlist a Setup into a set of "deferred Verify(...) calls" which can then be triggered via mock. Verify() .

What does Moq setup do?

Moq provides a library that makes it simple to set up, test, and verify mocks. We can start by creating an instance of the class we're testing, along with a mock of an interface we want to use.


2 Answers

Yes, you can echo back the argument passed to the method

httpResponseBase.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
                .Returns((string path) => path);

You can also capture it if you want

string capturedModifier = null;

httpResponseBase.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>()))
                .Callback((string path) => capturedModifier = path);
like image 113
Russ Cam Avatar answered Oct 04 '22 04:10

Russ Cam


Use It:

It.Is<MyClass>(mc=>mc == myValue)

Here you can check the expectation: the value you expect to receive. In terms of return, just return value you need.

var tempS = string.Empty;
var httpResponseBase = new Mock<HttpResponseBase>();
httpResponseBase.Setup(hrb => hrb.ApplyAppPathModifier(It.Is<String>(s=>{
           tempS = s;
           return s == "value I expect";
           })))
                .Returns(tempS);
like image 31
Aliostad Avatar answered Oct 04 '22 03:10

Aliostad