Настройката на Moq Unit Test не работи

Опитвам се да създам прост модулен тест с помощта на рамката Ninject Moq и по някаква причина не мога да накарам метода за настройка да работи правилно. Доколкото разбирам, методът за настройка по-долу трябва да инжектира хранилището в класа на услугата с предварително дефинирания резултат 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;
        }
}

РЕДАКТИРАНЕ: Замених обекта Profile, в който се предава

_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