Home > Mobile >  How do I unit test an instantiated class that is also retuned by a method?
How do I unit test an instantiated class that is also retuned by a method?

Time:06-15

I am trying to unit test a method similar to the below code:

public OutDto ToOutDto(InDto inDto)
{        

    var outDto = new OutDto
    {
        Property1 = inDto.Property2
        //More mapping here
    };

    outDto = _converter.ConvertCollection(outDto, inDto.Collection);


    return outDto;
}

The problem is the call out to _converter.ConvertCollection is replacing the outDto created above the call.

Here is my Unit Test so far:

var inDto = new IntDto()
{
    Property2 = "Property",
    Collection = new Collection()
};

_converter.Setup(t => t.Convert(It.IsAny<outDto>(), intDto.Collection)).Returns(It.IsAny<outDto>());

var result = _sut.ToDto(inDto);

Assert.Equal(inDto.Property2, result.Property1);

_converter.Verify(t => t.Convert(It.IsAny<outDto>(), inDto.Collection), Times.Once());

The problem is, I think, I am returning It.IsAny<outDto>(). Which is cleaning out the values set during the object initialization.

I guess I could return an of inDto with the properties set, but then I am really testing the code object initialization code?

I am using xUnit and Moq.

CodePudding user response:

It.* is only mean to be used in setting up expectations of mocks. It is not to be used as a variable.

You will need to capture the passed argument if it is you want it to be be returned, mimicking the expected behavior

//...

_converter
    .Setup(_ => _.Convert(It.IsAny<OutDto>(), It.IsAny<Collection>()))
    .Returns((OutDto d, Collection c) => {
        //...do what ever modification (if ant) needed to be done to the captured dto
        return d; //then return it
    }); 

//...
  • Related