我在单元测试中使用 Moq,但我不知道为什么我的测试失败了。
这是我得到的错误
Moq.MockVerificationException:以下设置不匹配:
IGroupRepository r => r.Delete(It.Is(um => um.Equals()))
这是我要测试的服务。
服务
public GroupService ( IGroupRepository groupRepository )
{
_groupModelToViewModelMapper = new AutoMapper<GroupModel, GroupViewModel>();
_groupViewModelToModelMapper = new AutoMapper<GroupViewModel, GroupModel>();
_groupRepository = groupRepository;
}
public void Delete( GroupViewModel viewModel )
{
_groupRepository.Delete( _groupViewModelToModelMapper.BuildFrom( viewModel ) );
}
测试
[Test]
public void FAILING_TEST ()
{
// Setup the Mock GroupRepository
_groupRepository.Setup( r => r.Delete( It.Is<GroupModel>( um => um.Equals( _groupModel ) ) ) );
var groupService = new GroupService( _groupRepository.Object);
// execute
groupService.Delete( _groupViewModel );
// assert
_groupRepository.VerifyAll();
}
我想不通的是,如果我注入 AutoMapper,测试就会通过。我看不出注入自动映射器的意义,因为它基本上与它所映射的服务模型是一对一的。
服务
public GroupService( IGroupRepository groupRepository,
IAutoMapper<GroupViewModel, GroupModel> groupViewModelToModelMapper,
IAutoMapper<GroupModel, GroupViewModel> groupModelToViewModelMapper )
{
_groupModelToViewModelMapper = groupModelToViewModelMapper;
_groupRepository = groupRepository;
_groupViewModelToModelMapper = groupViewModelToModelMapper;
}
public void Delete( GroupViewModel viewModel )
{
_groupRepository.Delete( _groupViewModelToModelMapper.BuildFrom( viewModel ) );
}
测试
[Test]
public void PASSING_TEST()
{
// Setup the Mock GroupRepository
_groupRepository.Setup(r => r.Delete(It.Is<GroupModel>(um => um.Equals(_groupModel))));
// Setup the Mock ModelMapper
_viewModelToModelMapper.Setup(vmm => vmm.BuildFrom(It.Is<GroupViewModel>(u => u.Equals(_groupViewModel))))
.Returns(_groupModel);
var groupService = new GroupService(_groupRepository.Object, _viewModelToModelMapper.Object, _modelToViewModelMapper.Object);
// execute
groupService.Delete(_groupViewModel);
// assert
_groupRepository.VerifyAll();
_viewModelToModelMapper.VerifyAll();
}
此外,如果它有效,这里是测试设置。
private GroupModel _groupModel;
private List<GroupModel> _groupModels;
private GroupViewModel _groupViewModel;
private List<GroupViewModel> _groupViewModels;
private Mock<IGroupRepository> _groupRepository;
private Mock<IAutoMapper<GroupViewModel, GroupModel>> _viewModelToModelMapper;
private Mock<IAutoMapper<GroupModel, GroupViewModel>> _modelToViewModelMapper;
[SetUp]
public void SetUp()
{
_groupModel = new GroupModel();
_groupModels = new List<GroupModel>();
_groupViewModel = new GroupViewModel();
_groupViewModels = new List<GroupViewModel>();
_groupRepository = new Mock<IGroupRepository>();
_viewModelToModelMapper = new Mock<IAutoMapper<GroupViewModel, GroupModel>>();
_modelToViewModelMapper = new Mock<IAutoMapper<GroupModel, GroupViewModel>>();
}
有人可以帮我掌握这个嘲弄的东西吗?