3

I have a mocked DTO class that has properties in it I'm setting via a callback function. This works below for me, but is there a cleaner way to go about it?

            Mock<MyDto> _MyDto = new Mock<MyDto>();

            _MyDto.Setup(dto => dto).Callback<MyDto>(dto => 
            {   
                dto.FirstName = "John";
                dto.LastName = "Doe";
            });

I'd like to set those properties in the Setup call if possible, but it accepts an expression and I can't do a multi-line statement in there. But my Linq knowledge isn't encyclopedic and I was wondering if there was a better to approach what I'm doing.

larryq
  • 15,713
  • 38
  • 121
  • 190
  • Are you asking if lambda expressions may contain [multiple lines?](http://stackoverflow.com/questions/5653703/can-a-c-sharp-lambda-function-be-more-than-one-line) – Daniel Miladinov Dec 01 '12 at 01:24
  • @Danny--I was wondering if it's possible to put a lambda in place of an expression parameter somehow (as Setup() takes above). I know it's possible to have multiple statements in a lambda. Can you convert a lambda to an expression tree somehow? – larryq Dec 01 '12 at 06:37
  • Given that you are talking about a DTO, is there really a need to use a mock for it instead of just a real instance? It should not have any logic that would require mocking. – Pablo Romeo Dec 01 '12 at 15:44
  • @Pablo-- my DTO has a little more to it than just properties. It's not really a DTO but I kept it simple for the example here. – larryq Dec 02 '12 at 06:39

2 Answers2

3

According to the Moq quickstart guide to properties, you could possibly change your code to look like this instead:

_MyDto.SetupProperty(dto => dto.FirstName, "John");
_MyDto.SetupProperty(dto => dto.LastName, "Doe");

I've not yet had the chance to use Moq myself, but this appears to be the way to mock properties in Moq.

Daniel Miladinov
  • 1,582
  • 9
  • 20
2

I think you misunderstand what the Setup() method is for. You're not supposed to call it just once with all of the initialization code. Instead, you call it once for each individual item that you want to setup.

Daniel Miladinov
  • 1,582
  • 9
  • 20
svick
  • 236,525
  • 50
  • 385
  • 514