5 Replies - 1693 Views - Last Post: 01 March 2013 - 07:09 AM Rate Topic: -----

#1 regex   User is offline

  • New D.I.C Head

Reputation: -4
  • View blog
  • Posts: 33
  • Joined: 25-September 12

Unit Testing MSpec and Rhino

Posted 26 February 2013 - 04:08 PM

I am using MSpec and Rhino for mocking. I can't get some of these tests to pass. Any recommendations on refactoring the tests:

using IDM.CMS3.Service.Models.PageWidgets;
using IDM.CMS3.Service.Services;
using IDM.CMS3.Service.ViewModels;
using Machine.Fakes;
using Machine.Specifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IDM.CMS3.Service.Models;
using IDM.CMS3.Web.Admin.Controllers;
using StructureMap.AutoMocking;
using Rhino.Mocks;
using System.Web.Mvc;

namespace IDM.CMS3.Service.Tests.Services
{
    public class TemplateServiceSpecs : WithSubject<TemplateService> 
    {

    } 

    public class GetAllTemplates : TemplateServiceSpecs
    {
        public static IEnumerable<PageTemplate> _result;

        Because of = () =>
            _result = Subject.GetAll();

        It At_Least_One_Template = () =>
            _result.Count().ShouldNotBeNull();

        It Maps_To_Model = () =>
            _result.ShouldBeOfType<IList<PageTemplate>>();

    }

    public class ControllerSpecs : TemplateServiceSpecs
    {
        protected static TemplateController _controller;
        public static TemplateService _templateService;
        static RhinoAutoMocker<TemplateController> mocker;

        Establish context =
            () =>
            {
                mocker = new RhinoAutoMocker<TemplateController>();
                _controller = mocker.ClassUnderTest; 
                _templateService = mocker.Get<TemplateService>();

            };
    }

    public class When_Invoked_Template : ControllerSpecs
    {
        static List<PageTemplate> _templates;
        static ActionResult _result;

        Establish context =
            () =>
            {
                _templates = new List<PageTemplate>();
                _templateService.Stub(x => x.GetModelBySimpleId("1")); 
            };

        Because of =
            () => { _result = _controller.Edit("test"); };

        It should_retrieve_a_list_of_templates_with_titles_containing_the_simple_id =
            () => _templateService.AssertWasCalled(x => x.ShouldBeLike("1"));

        It should_return_the_list_of_templates_to_the_user =
            () => _result.ShouldBeLike(_templates);

        It should_contain_edit_text_in_save_body =
            () => _result.ShouldBeTheSameAs("test"); 
    }

    public class when_create_invoked : ControllerSpecs
    {
        private static PageTemplate _template;
        private static ActionResult _result;

        private Because of = () => _result = _controller.Create();

        It should_not_be_null =
            () => _result.ShouldNotBeNull(); 

        It should_add_record = 
            () => _templateService.Save(_template); 

        It should_be_of_type = 
            () => _result.ShouldBeOfType<PageTemplate>(); 

        //It should_redirect_to_listView = 
        //    () => 
    }
}



PageTemplates:

using Raven.Imports.Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace IDM.CMS3.Service.Models
{
    public class PageTemplate : ModelBase
    {
        public string Text { get; set; }
        public IEnumerable<TemplateMetaData> TemplateMetaData { get; set; }

        public bool HasMasthead { get; set; }
        public bool HasFooter { get; set; }
    }
}



TemplateController:

using System.Text;
using System.Threading.Tasks;
using Raven.Client.Indexes;
using System.Linq;
using System.Web.Mvc;
using Raven.Abstractions.Indexing;
using IDM.CMS3.Service.Models.PageWidgets;
using System.IO;
using System.Reflection;
using IDM.CMS3.Service.Services;
using IDM.CMS3.Service.Models; 
using IDM.CMS3.Service.App_Start; 

namespace IDM.CMS3.Web.Admin.Controllers
{
    public class TemplateController : Controller
    {
        readonly ITemplateService _templateService;


        public TemplateController(ITemplateService templateService)
        {
            _templateService = templateService;
        }

        public ActionResult Index()
        {
            return View(_templateService.GetAll());
        }

        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(PageTemplate model)
        {
            if (ModelState.IsValid)
            {
                _templateService.Save(model);
                return RedirectToAction("Index");
            }
            return View(model);

        }

        [HttpGet]
        public ActionResult Edit(string id)
        {
            return View(_templateService.GetModelBySimpleId(id));
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(PageTemplate model)
        {
            _templateService.Save(model);
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult Delete(string id)
        {
           
            _templateService.Delete(id);
            return RedirectToAction("Index");
        }

    }
}



TemplateService:

using HtmlAgilityPack;
using IDM.CMS3.Service.Models;
using Raven.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Raven.Client.Linq;
using System.Reflection;

namespace IDM.CMS3.Service.Services
{
    public interface ITemplateService
    {
        IEnumerable<PageTemplate> GetAll();
        void Save(PageTemplate template);
        void Delete(string id); 
        PageTemplate GetModelBySimpleId(string id);
    }

    public class TemplateService : ITemplateService
    {
        IDocumentSession _documentSession;

        public TemplateService(IDocumentSession documentSession)
        {
            _documentSession = documentSession;
        }

        public static IList<T> GetInstances<T>()
        {
            return Assembly.GetExecutingAssembly().GetTypes()
                .Where(x => x.BaseType == typeof(T) && x.GetConstructor(Type.EmptyTypes) != null)
                .Select(x => (T)Activator.CreateInstance(x))
                .ToList();
        }

        public IEnumerable<PageTemplate> GetAll()
        {
            var models = _documentSession.Query<PageTemplate>().ToList();
            return models;
        }

        public void Save(PageTemplate template)
        {
            PageTemplate model;

            if (String.IsNullOrEmpty(template.Id))
            {
                model = new PageTemplate { Id = "pagetemplate/" };
                _documentSession.Store(model);
            }
            else
            {
                model = GetModelBySimpleId(template.SimpleId);
            }
            
            model.Text = template.Text; 
            _documentSession.SaveChanges(); 
        }


        public PageTemplate GetModelBySimpleId(string id)
        {
            var model = _documentSession.Load<PageTemplate>("pagetemplate/" + id);
            return model;
        }

        public void Delete(string id)
        {
            PageTemplate model = GetModelBySimpleId(id);
            _documentSession.Delete(model);
            _documentSession.SaveChanges(); 

            //var model = _documentSession.Delete<PageTemplate>(template);
            //return model;
        }


    }
}


Is This A Good Question/Topic? 0
  • +

Replies To: Unit Testing MSpec and Rhino

#2 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7054
  • View blog
  • Posts: 23,983
  • Joined: 05-May 12

Re: Unit Testing MSpec and Rhino

Posted 26 February 2013 - 07:39 PM

<rant>
WTF?!?! Refactor the tests so that they pass? So what is the point of writing the tests if you are going to change the test to make the code pass? I was under the mistaken belief that the point of writing tests is to make the code work so that the tests to pass. I didn't know that the "no child left behind" mindset was also starting to extend to unit tests. If the code isn't passing the test, change the test. Sheez! If you are going to refactor the tests, you might as well just delete the bodies of the test functions so that your tests pass.
</rant>

Seriously, though, you can't just dump all that code on us and say that you need the tests to pass. Can't you at least tell us which test(s) are failing, and why they are failing?
Was This Post Helpful? 2
  • +
  • -

#3 regex   User is offline

  • New D.I.C Head

Reputation: -4
  • View blog
  • Posts: 33
  • Joined: 25-September 12

Re: Unit Testing MSpec and Rhino

Posted 28 February 2013 - 02:45 PM

How about this. I just want to test GetCurrentConditions.

 public class WeatherService : IWeatherService
    {
        readonly IWeatherRepository _weatherRepository;
        readonly ISiteSettingsService _siteSettingsService;
        readonly ICurrentSiteModel _current;
        readonly ICacheProvider<CurrentConditionsDTO> _currentConditionsCacheProvider;
        readonly ICacheProvider<DailyForecastDTO> _dailyForecastCacheProvider;
        readonly ICacheProvider<HourlyForecastDTO> _hourlyForecastCacheProvider;

        readonly int _siteId;
        readonly SiteSettingsDTO _siteSettings;

        public WeatherService(IWeatherRepository weatherRepository,
                                ISiteSettingsService siteSettingsService,
                                ICurrentSiteModel current,
                                ICacheProvider<CurrentConditionsDTO> currentConditionsCacheProvider,
                                ICacheProvider<DailyForecastDTO> dailyForecastCacheProvider,
                                ICacheProvider<HourlyForecastDTO> hourlyForecastCacheProvider)
        {
            _weatherRepository = weatherRepository;
            _siteSettingsService = siteSettingsService;

            _currentConditionsCacheProvider = currentConditionsCacheProvider;
            _dailyForecastCacheProvider = dailyForecastCacheProvider;
            _hourlyForecastCacheProvider = hourlyForecastCacheProvider;

            _current = current;

            _siteId = _current.Site.OldSiteId;
            _siteSettings = _siteSettingsService.LoadSiteSettings();
        }

        private static readonly Regex caZipRegex = new Regex(@"^([AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d[A-Za-z]\s?\d[A-Za-z]\d)$", RegexOptions.Compiled);
        private static readonly Regex usaZipRegex = new Regex(@"(\d{5}|\d{5}\-\d{4})$", RegexOptions.Compiled);
        private static readonly Regex cityStateRegex = new Regex(@"^(?<city>[\.A-Za-z\s]*)(?:,\s?(?<state>[\sA-Za-z]+)|\s(?<state>[A-Za-z]{2}))", RegexOptions.Compiled);

        #region Current Conditions

        public CurrentConditionsViewModel GetCurrentConditions(bool canUseAPI)
        {
            int groupID;
            Int32.TryParse(_siteSettings.SiteSettingsDictionary.GetValueSafe(string.Format("{0}-{1}", SiteSettingsCategory.Weather.ToString(), "WeatherGroupID")), out groupID);

            return GetCurrentConditions(GetGroupLocation(groupID, null), canUseAPI);
        }


Test:

public class GetCurrentConditions : WeatherServiceSpecs
    {
        public static CurrentConditionsViewModel _currentConditionsViewModel;
        public static bool canUseAPI;

        Establish that = () =>
        {
            _currentConditionsViewModel = new CurrentConditionsViewModel
            {
                ConditionID = 1
            };
        };

        Because of = () =>
            _currentConditionsViewModel = Subject.GetCurrentConditions(canUseAPI);

        It Can_Use_API_To_Access = () =>
            _currentConditionsViewModel.ShouldBeOfType<CurrentConditionsViewModel>(); 


I get Unable to create an instance of type WeatheService. The constructor threw an exception. I'm using Ninject. I still have to pass in all the fields into the constructor?
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7054
  • View blog
  • Posts: 23,983
  • Joined: 05-May 12

Re: Unit Testing MSpec and Rhino

Posted 28 February 2013 - 07:46 PM

What was the exception thrown?
Was This Post Helpful? 0
  • +
  • -

#5 regex   User is offline

  • New D.I.C Head

Reputation: -4
  • View blog
  • Posts: 33
  • Joined: 25-September 12

Re: Unit Testing MSpec and Rhino

Posted 01 March 2013 - 12:31 AM

View PostSkydiver, on 28 February 2013 - 07:46 PM, said:

What was the exception thrown?

Unable to create an instance of type WeatheService.

That was the actual exception.
Was This Post Helpful? 0
  • +
  • -

#6 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7054
  • View blog
  • Posts: 23,983
  • Joined: 05-May 12

Re: Unit Testing MSpec and Rhino

Posted 01 March 2013 - 07:09 AM

And if you set the debugger to catch first chance exceptions, is it the WeatherService itself that is throwing the exception, or is it Ninject because it doesn't have enough information to instantiate the object?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1