Our app has MOQ, pronounced "Mock You" in play for mocking. I'm trying to understand it. It doesn't look that tricky.
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using App.Core;
using App.Core.Entities;
using App.UI.Controllers;
using Moq;
using App.Core.Repositories;
using App.Tests;
using System.Web.Mvc;
using App.UI.Tests.Support;
namespace App.UI.Tests
{
[TestClass]
public class ProfileControllerTest
{
IProfileRepository fakeRepo { get; set; }
Mock<IProfileRepository> mockProfileRepository { get; set; }
private static string userWithProfile = @"FOO\ProfileExists";
private static string userWithoutProfile=@"FOO\NoProfile";
private static Guid userIdForUserWithProfile = System.Guid.NewGuid();
Profile existingProfile = TestObjects.BuildProfile(userWithProfile);
Profile newProfile = new Profile() { UserName = userWithoutProfile };
[TestInitialize]
public void TestSetup()
{
existingProfile.Id = userIdForUserWithProfile;
mockProfileRepository = new Mock<IProfileRepository>();
mockProfileRepository.Setup(
repo => repo.GetByUserName(userWithProfile)
).Returns(existingProfile).Verifiable();
mockProfileRepository.Setup(
repo => repo.GetById(userIdForUserWithProfile)
).Returns(existingProfile).Verifiable();
mockProfileRepository.Setup(
repo => repo.GetByUserName(userWithoutProfile)
).Returns(default(Profile)).Verifiable();
mockProfileRepository.Setup(
repo => repo.Save(existingProfile)
).Verifiable();
mockProfileRepository.Setup(
repo => repo.Save(newProfile)
).Verifiable();
fakeRepo = mockProfileRepository.Object;
fakeRepo = mockProfileRepository.Object;
ServiceLocator.LookupSource = () =>
{
var testServices = new Dictionary<string, object>();
testServices[AppCtxIds.PROFILE_REPOSITORY] = fakeRepo;
return testServices;
};
}
[TestMethod]
public void ProfileDetailsTest()
{
//arrange
var controller = new ProfileController();
controller.ProfileRepository = fakeRepo;
//act
var actionResult = controller.Details(userIdForUserWithProfile);
var viewResult = (ViewResult)actionResult;
//assert
mockProfileRepository.Verify(
pr => pr.GetById(userIdForUserWithProfile), Times.Once()
);
Assert.IsNotNull(controller.ProfileRepository);
var viewProfile = ((Profile)viewResult.ViewData.Model);
Assert.IsTrue(viewProfile.UserName == userWithProfile);
}
more code follows...
No comments:
Post a Comment