Unit Test validation asp.net mvc

[TestMethod]
public void AddCampaign_Admin_Validation()
{
var enumValue = RequestContentType.Json;
var urlFormat = Utility.BaseUrl + “/LeadSourceService/AddCampaign?username={0}&password=1234”;
var url = string.Format(urlFormat, “admin@mort.demo”);

CampaignInfo info = new CampaignInfo { };

var providers = new ProviderCollection();
providers.Load();
var provider = providers.FirstOrDefault(c => c.SharingEnabled == ProviderSharingEnabled.Enabled && c.Visible == true);
info.Active = false;
info.AdSource = “AdSource1”;
info.AdSourceCost = 15;
info.Title = “Add Campaing Unit Test 2”;
info.Type = CampaignType.Dialer.ToString();
if (provider != null) info.ProviderId = provider.Id;
info.ProviderSharingEnabled = “False”;

AdSourceCostBasisValidation adSourceCostBasic = new AdSourceCostBasisValidation();
var result = adSourceCostBasic.IsValid(info.AdSourceCostBasis);
Assert.AreEqual(result, true);
ProviderSharingEnabledValidation providerSharingEnabled = new ProviderSharingEnabledValidation();
result = providerSharingEnabled.IsValid(info.ProviderSharingEnabled);
Assert.AreEqual(result, false);
CampaignTypeValidation campaignType = new CampaignTypeValidation();
result = campaignType.IsValid(info.Type);
Assert.AreEqual(result, true);

var controller = Mock.CreateController<CampaignController>(System.Net.Http.HttpMethod.Put, url, enumValue);
ValidateViewModel(info, controller);
Assert.AreEqual(controller.ModelState.Values.Count, 1);
}

private static void ValidateViewModel<VM, C>(VM viewModelToValidate, C controller) where C : ApiController
{
var validationContext = new ValidationContext(viewModelToValidate, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(viewModelToValidate, validationContext, validationResults, true);
foreach (var validationResult in validationResults)
{
controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
}
}

About eagle081183

Passionate, Loyal
This entry was posted in ASP.NET MVC, C#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s