Marc Vitalis
Marc Vitalis

Reputation: 2249

How to pass a method as parameter without declaring a delegate in .NET

No matter how I try, I cannot mimic the clean syntax of Rhino Mocks, without declaring a delegate.

Example:

Expect.Call(service.HelloWorld("Thanks"))

Do you have any idea on how to do this?

Thanks.

Upvotes: 3

Views: 1618

Answers (3)

justin.m.chase
justin.m.chase

Reputation: 13655

In Rhino Mocks it is actually invoking the method. The object is in setup mode at that time and when you invoke it, it is recording parameters and setting expectations. This is why you can get away from the delegate syntax. Not really possible in many other scenarios unfortunately.

Upvotes: 0

Cameron MacFarland
Cameron MacFarland

Reputation: 71866

Using Lambda syntax in 3.5 you can get a similar syntax.

public void Call(Action action)
{
    action();
}

Expect.Call(() => service.HelloWorld("Thanks"));

Moq is a mocking framework that uses Lambda syntax for it's mocking.

var mock = new Mock<IService>();
mock.Setup(service => service.HelloWorld("Thanks")).Returns(42);

Upvotes: 6

sisve
sisve

Reputation: 19781

You could use the Action delegate provided in newer versions of .NET

void Execute(Action action) {
    action();
}

void Test() {
    Execute(() => Console.WriteLine("Hello World!"));
}

Upvotes: 7

Related Questions