mardi 29 mars 2016

Moq and Teststack.Fluent.Mvc for a controller without repository

public class ClaimController : BaseController
{
//has no repository member
//base class has UnitOfWork member only with all other elements are static method calls 
//to a session element which fetches all the data from the business layer in a 
//service solution...


public ActionResult Contact()
        {
            return Redirect("http://pluralsight.com");
        }


public JsonResult GetListOfFoos()
        {
            List<FooModel> FooModels = InvokeLoadAllData<FooModel>().ToList();

            List<CoverModel> coverModels = InvokeLoadAllById<CoverModel>(GetLoggedInUserViewModel().CompanyCode, x => x.CompanyID).ToList();

            FooModels.RemoveAll(x => coverModels.All(y => y.CoverId != x.CoverId));

            var results = FooModels.Select(crm => new FooModel
            {
                FooId = crm.FooId,
                FooCode = crm.FooCode,
                CoverCodeDescription = coverModels.First(x => x.CoverId == crm.CoverId).Description,
                IsPostcodeRequired = crm.IsPostcodeRequired,
                EndDateDT = DateTime.Parse(crm.EndDate),
            }).ToList();

            var query = from y in results
                        where y.IsPostcodeRequired
                        select y;

            return Json(new { data = query }, JsonRequestBehavior.AllowGet);
        }


[TestFixture]
    public class FooControllerTests
    {
        [SetUp]
        public void Initialize()
        {
            const string ExceptionHandlingPolicy = "Exception Handling Policy";
            UnityHelper.ConfigureHelper(new HelperConfiguration()
            {
                UnityConfigurationSection =
                    (Microsoft.Practices.Unity.Configuration.UnityConfigurationSection)
                        System.Configuration.ConfigurationManager.GetSection(UnityConfigurationSection.SectionName)
                ,
                ExceptionHandlingPolicyName = ExceptionHandlingPolicy
            });}


        [Test]
        public void FirstTestNotWorkingAsReturnsNull()
        {//played with this with no avail, must be something I need to see in var controller???   see below for other attempts

            List<FooModel> crmMock = new List<FooModel>();
            crmMock.Add(new FooModel { CauseCode = "causecode1", CauseDescription = "Keep", CoverId = 1, SectionId = 1, FooId = 1, FooCode = "crc1", CoverCodeDescription = "ccd1", IsPostcodeRequired = true,EndDate = "01/01/2015"});
            crmMock.Add(new FooModel { CauseCode = "causecode2", CauseDescription = "Keep", CoverId = 2, SectionId = 2, FooId = 2, FooCode = "crc2", CoverCodeDescription = "ccd2", IsPostcodeRequired = false , EndDate = "02/02/2015" });
            crmMock.Add(new FooModel { CauseCode = "causecode3", CauseDescription = "Remove", CoverId = 3, SectionId = 3, FooId = 3, FooCode = "crc3", CoverCodeDescription = "ccd3", IsPostcodeRequired = true , EndDate = "03/03/2015" });
            crmMock.Add(new FooModel { CauseCode = "causecode4", CauseDescription = "Remove", CoverId = 4, SectionId = 4, FooId = 4, FooCode = "crc4", CoverCodeDescription = "ccd4", IsPostcodeRequired = false , EndDate = "04/04/2015" });
            crmMock.Add(new FooModel { CauseCode = "causecode5", CauseDescription = "Remove", CoverId = 5, SectionId = 5, FooId = 5, FooCode = "crc5", CoverCodeDescription = "ccd5", IsPostcodeRequired = true , EndDate = "05/05/2015" });

            List<CoverModel> cmList = new List<CoverModel>();
            cmList.Add(new CoverModel { CoverId = 1, Description = "Cover_1", CompanyID = "99" });
            cmList.Add(new CoverModel { CoverId = 2, Description = "Cover_2", CompanyID = "99" });
            cmList.Add(new CoverModel { CoverId = 3, Description = "Cover_3", CompanyID = "101" });
            cmList.Add(new CoverModel { CoverId = 4, Description = "Cover_4", CompanyID = "101" });
            cmList.Add(new CoverModel { CoverId = 5, Description = "Cover_5", CompanyID = "101" });


            /*Expression<Func<CoverModel, object>> inputFunc = x => x.CompanyID;*/
            /*controller.Setup(x => x.InvokeLoadAllById<CoverModel>(It.IsAny<string>(), inputFunc, false))
                .Returns(cmList);*/


            var controller = new Mock<FooCodePostcodeController>();


            controller.Setup(x => x.InvokeLoadAllData<FooModel>(false))
                .Returns(crmMock);

            controller.Setup(x => x.InvokeLoadAllById<CoverModel>(It.IsAny<string>(), It.IsAny<Expression<Func<CoverModel, object>>>(), false))
                .Returns(cmList);
            controller.Setup(x => x.GetLoggedInUserViewModel())
                .Returns(new LoggedInUserViewModel()
                {
                    Username = "me",
                    Password = "password",
                    CompanyCode = "99"
                });

            var results = controller.Object.WithCallTo(c => c.GetListOfFoos()).ShouldReturnJson(); 
             Assert.That(results.Data, Is.EqualTo(1));


            /*var results = controller.Object.WithCallTo(c => c.GetListOfFoos());

            Assert.That(results, Is.EqualTo(1));

            /*controller.Object.WithCallTo(c => c.GetListOfFoos()).ShouldReturnJson( data =>
            {
                Assert.That(data.FooCode, Is.EqualTo(1));
            });*/
        }

Im using Moq and teststack.Fluent.MVC for the first time and can mock the method calls in GetListOfFoos very well as I have wrapped them in virtual methods (InvokeLoadAllData & InvodeLoadAllById). However all the Moq examples I can find pass Moq'ed repositories to an instance of the controller. However I dont have a repository member, but I found that if I Mock the controller itself the setup's all work and I can Moq the unity container and LoggedInUser session's and I can debug through the entire method fine, it only goes wrong at the end when it returns a null exception. I have tried creating a controllerContext and changing everything around to no avail, please help. Is there a field within the controller which can be set to prevent this or am I barking up the wrong tree. The Contact ActionResult works fine and was left in the confirm that Im using the frameworks correctly. I have literary many dozens of methods like this that need tests so ideally would prefer not to rewrite my controllers, thank you in advance.

Aucun commentaire:

Enregistrer un commentaire