[英]How do I unit test an instantiated class that is also retuned by a method?
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.问题是对_converter.ConvertCollection
的调用正在替换在调用上方创建的outDto
。
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>()
.问题是,我认为,我正在返回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?我想我可以返回带有属性集的inDto
,但是我真的在测试代码对象初始化代码吗?
I am using xUnit and Moq.我正在使用 xUnit 和 Moq。
It.*
is only mean to be used in setting up expectations of mocks. It.*
仅用于设置模拟的期望值。 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
});
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.