Установка модульного теста Moq не работает

Я пытаюсь создать простой модульный тест с использованием фреймворка Ninject Moq, и по какой-то причине я не могу заставить метод установки работать правильно. Насколько я понимаю, приведенный ниже метод установки должен внедрить репозиторий в класс Service с предопределенным результатом true.

 [TestFixture]
public class ProfileService : ServiceTest
{
    private readonly Mock<IRepository<Profile>> _profileRepoMock;

    public ProfileService()
    {
        MockingKernel.Bind<IProfileService>().To<Data.Services.Profiles.ProfileService>();
        _profileRepoMock = MockingKernel.GetMock<IRepository<Profile>>();
    }


    [Test]
    public void CreateProfile()
    {
        var profile = new Profile()
            {
                Domain = "www.tog.us.com",
                ProfileName = "Tog",
            };

        _profileRepoMock.Setup(x => x.SaveOrUpdate(profile)).Returns(true);
        var profileService = MockingKernel.Get<IProfileService>();
        bool verify = profileService.CreateProfile(Profile);

        _profileRepoMock.Verify(repository => repository.SaveOrUpdate(profile), Times.AtLeastOnce());

        Assert.AreEqual(true, verify);
    }
}

Когда я пытаюсь это проверить, я получаю такую ​​ошибку:

Ожидается вызов макета хотя бы один раз, но так и не был выполнен: repository => repository.SaveOrUpdate (.profile)

Настроенные настройки: x => x.SaveOrUpdate (.profile), Times.Never

Выполненные вызовы: IRepository`1.SaveOrUpdate (DynamicCms.Data.DataModels.Profile)

Вот метод CreateProfile в классе ProfileService:

public class ProfileService : IProfileService
    {
        private readonly IRepository<Profile> _profileRepo;

        public ProfileService(IRepository<Profile> profileRepo)
        {
            _profileRepo = profileRepo;
        }
            public bool CreateProfile(ProfileViewModel profile)
        {
            Profile profileToCreate = new Profile
                {
                    Domain = profile.Domain,
                    ProfileName = profile.Name
                };

            bool verify = _profileRepo.SaveOrUpdate(profileToCreate);

            if (verify)
            {
                return true;
            }

            return false;
        }
}

РЕДАКТИРОВАТЬ: я заменил объект профиля, передаваемый в

_profileRepoMock.Setup(x => x.SaveOrUpdate(profile)).Returns(true); 

с участием

_profileRepoMock.Setup(x => x.SaveOrUpdate(It.IsAny<Profile>())).Returns(true); 

Этот метод работает сейчас, но почему именно он не работал раньше, когда я передавал один и тот же объект в методы Verify и Setup.

Оглядываясь назад, можно сказать, что, поскольку этот метод настроен на возврат определенного значения, на самом деле не имеет значения, что в него передается, но было бы неплохо узнать.


person The Pax Bisonica    schedule 02.06.2013    source источник
comment
Вы можете опубликовать свой ProfileService.CreateProfile метод?   -  person nemesv    schedule 02.06.2013
comment
Все готово, я только что добавил метод.   -  person The Pax Bisonica    schedule 02.06.2013


Ответы (1)


Вам не нужно использовать NInject для модульного тестирования:

[TestFixture]
public class ProfileServiceTest : ServiceTest
{
    private readonly Mock<IRepository<Profile>> _profileRepoMock;
}
[SetUp]
public void Setup()
{
    _profileRepoMock = new Mock<IRepository<Profile>>();
}

[Test]
public void CreateProfile()
{
    var profile = new Profile()
        {
            Domain = "www.tog.us.com",
            ProfileName = "Tog",
        };

    _profileRepoMock.Setup(x => x.SaveOrUpdate(profile)).Returns(true);
    var profileService = new ProfileService(_profileRepoMock.Object);
    bool verify = profileService.CreateProfile(Profile);

    _profileRepoMock.Verify(repository => repository.SaveOrUpdate(profile), Times.AtLeastOnce());

    Assert.AreEqual(true, verify);
}

}

Изменить: этот класс нужно будет немного изменить

public class ProfileService : IProfileService
{
    private readonly IRepository<Profile> _profileRepo;

    public ProfileService(IRepository<Profile> profileRepo)
    {
        _profileRepo = profileRepo;
    }
        public bool CreateProfile(ProfileViewModel profile)
    {

        bool verify = _profileRepo.SaveOrUpdate(profile);

        if (verify)
        {
            return true;
        }

        return false;
    }
 }
person rivarolle    schedule 04.06.2013
comment
Спасибо за предложение, но я все еще получаю то же сообщение об ошибке, что и выше, и с этим методом. - person The Pax Bisonica; 05.06.2013
comment
Это потому, что объект профиля, переданный в CreateProfile, не совпадает с переданным в SaveOrUpdate. Они оба относятся к одному типу, поэтому использование It.IsAny, конечно, будет работать. Я обновил свой ответ, чтобы отразить правильное решение. - person rivarolle; 06.06.2013