Moq - Null reference exception when trying to test ActionResult - c#

I'm trying to learn unit testing with Moq but I keep running into the same issue. I am writing unit tests for my controller ActionResults and I don't have a problem with creating an instance of my controller and testing that it works. But I have an ActionResult that gives me a null reference exception because I am missing something with setting up my test before calling the controller.
private PersonController _controller;
private Mock<ICoreRepository> _repoCore;
private Mock<IImageRepository> _repoImage;
[TestInitialize]
public void Setup()
{
_repoCore = new Mock<ICoreRepository>();
_repoImage = new Mock<IImageRepository>();
_controller = new PersonController(_repoImage.Object)
{
CrmCoreRepository = _repoCore.Object,
//ImageRepository = _repoImage.Object
};
}
[TestMethod]
public void UploadImage_NotNull_personImage_Test()
{
var controller = new PersonController(_repoImage.Object);
var model = new GlobalEntityModel
{
PersonModel= new PersonModel()
};
controller.CrmCoreRepository = _repoCore.Object;
var uploadedFile = new Mock<HttpPostedFileBase>();
uploadedFile
.Setup(f => f.ContentLength)
.Returns(10);
uploadedFile
.Setup(f => f.FileName)
.Returns("testimage.jpg");
var imageRepository = new Mock<IImageRepository>();
imageRepository.Setup(x => x.SaveImage(It.IsAny<HttpPostedFileBase>(), It.IsAny<ImagePaths>()));
var res = controller.AddOrUpdatePersonDetail(model, uploadedFile.Object);
Assert.IsNotNull(res);
}
In my test I create a new controller instance, model, a mock of httppostedfilebase and I try to setup the image repository saveImage.
[HttpPost]
public ActionResult AddOrUpdatePersonDetail(GlobalEntityModel model, HttpPostedFileBase personImage)
{
var uploadedImage = string.Empty;
var personImagePath = _imageRepository.RetrieveImageFilePath(ImagePaths.PersonImageFilePath);
if (personImage != null)
{
uploadedImage = _imageRepository.SaveImage(personImage, ImagePaths.PersonImageFilePath);
}
var personModel = model.PersonModel;
var personDto = Mapper.MapTo<PersonDto>(personModel);
//Update Person
personDto.CreatedBy = "Admin";
personDto.UpdatedBy = "Admin";
personDto.UpdatedOn = DateTime.Now;
if (uploadedImage != string.Empty)
{
personDto.PersonImageRef = uploadedImage;
if (personDto.PersonImageRef.Contains(personImagePath))
{
personDto.PersonImageRef = personDto.PersonImageRef.Replace(personImagePath, string.Empty);
}
if (personDto.PersonImageRef.Contains("~/Content"))
{
personDto.PersonImageRef = string.Empty;
}
}
if (personDto.Id == 0)
{
personDto.GlobalEntityGUID = model.GlobalEntityGUID;
personDto = CrmCoreRepository.AddPerson(personDto, null, null, null);
if (personDto != null)
{
personModel.GlobalEntityGUID = personDto.GlobalEntityGUID;
var personDetailModel = model.PersonDetailModel;
personDetailModel.PersonId = personDto.Id;
var personDetailDto = Mapper.MapTo<PersonDetailDto>(personDetailModel);
personDetailDto.CreatedBy = "Admin";
personDetailDto.UpdatedBy = "Admin";
personDetailDto = personDetailModel.Id == 0 ? CrmCoreRepository.AddPersonDetail(personDetailDto) : CrmCoreRepository.UpdatePersonDetail(personDetailDto);
}
}
else if (personDto.Id > 0)
{
personDto = CrmCoreRepository.UpdatePerson(personDto, null, null, null);
if (personDto != null)
{
personModel.GlobalEntityGUID = personDto.GlobalEntityGUID;
var personDetailModel = model.PersonDetailModel;
personDetailModel.PersonId = personDto.Id;
var personDetailDto = Mapper.MapTo<PersonDetailDto>(personDetailModel);
personDetailDto.CreatedBy = "Admin";
personDetailDto.UpdatedBy = "Admin";
personDetailDto = personDetailModel.Id == 0 ? CrmCoreRepository.AddPersonDetail(personDetailDto) : CrmCoreRepository.UpdatePersonDetail(personDetailDto);
}
}
return RedirectToRoute("EditEntity", new { controller = "GlobalEntity", action = "EditEntity", entityGuid = personModel.GlobalEntityGUID, entityType = "P" });
}
personImagePath as shown in the screenshot is null. Because I am not passing a parameter from my test I don't know how to make it contain a value. I am a bit confused with what to do in the unit test to fix this. Any help would be great.

You are using two different instances of IImageRepository. You need to make Setup calls on the same objects that were injected to object you are testing (PersonController - IImageRepository).
To fix it, change
var imageRepository = new Mock<IImageRepository>();
imageRepository.Setup(x => x.SaveImage(It.IsAny<HttpPostedFileBase>(),
It.IsAny<ImagePaths>()));
to (notice Returns)
_repoImage.Setup(x => x.SaveImage(It.IsAny<HttpPostedFileBase>(),
It.IsAny<ImagePaths>())).Returns("~/Content");

Related

system missing method exception. why this happening

I was wondering if some one can help here. I have a project as a general which includes 5 layout. Now I'm trying to write api with dotnet core which use data access and commone Lay out of this general. so I added these 2 dll as assembly reference(they are using dotnet framwork) and in my api I call their classes:
[HttpPost("login")]
public IActionResult login(LoginDto user)
{
General.Common.cLoadUserPermission.stcLoginInfo _LI = new cLoadUserPermission.stcLoginInfo();
if (user.UserName.ToLower() == "adminy" && user.Password.ToLower()== "rddddlad91")
{
_LI.LoginError = enmLoginError.enmLoginError_NoError;
_LI.UserID = "d56d79f4-1f06-4462-9ed7-d4292322555d";
_LI.UserName = "مدير سيستم";
_LI.UserLoginName = "adminy";
_LI.PersonelID = Guid.Empty;
_LI.IsSupervisor = false;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
}
else
{
_LI.LoginError = enmLoginError.enmLoginError_UserNameNotFound;
}
//DateTime _t = General.Common.cPersianDate.GetDateTime("1364/02/03");
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
switch (_LI.LoginError)
{
case General.Common.enmLoginError.enmLoginError_NoError:
break;
case General.Common.enmLoginError.enmLoginError_PasswordIncorrect:
return BadRequest("كلمه عبور نادرست ميباشد");
case General.Common.enmLoginError.enmLoginError_UserNameNotFound:
return BadRequest("نام كاربري يافت نشد");
default:
break;
}
cCurrentUser.CurrentUserID = _LI.UserID;
cCurrentUser.CurrentPersonelID = _LI.PersonelID;
cCurrentUser.CurrentUserLoginName = _LI.UserLoginName;
GlobalItems.CurrentUserID = _LI.UserID;
GlobalItems.CurrentUserPLE = _LI.UserLoginName;
GlobalItems.CurrentUserName = _LI.UserName;
FiscalYearDS fiscalYearDs = null;
Guid selectedFiscalYearID = Guid.Empty;
using (IFiscalYear service = FacadeFactory.Instance.GetFiscalYearService())
{
fiscalYearDs = service.GetFiscalYearByOID(user.FiscalYear.ToString());
selectedFiscalYearID = fiscalYearDs.tblFiscalYear[0].FiscalYearID;
}
Configuration.Instance.CurrentFiscalYear = fiscalYearDs;
this.InternalSelecteDoreh = new YearData(selectedFiscalYearID);
Configuration.Instance.CurrentYear = this.SelectedDoreh;
General.Common.Data.FiscalYearDS generalfiscalyearDS = null;
using (General.Common.IFiscalYear service = General.Common.FacadeFactory.Instance.GetFiscalYearService())
{
generalfiscalyearDS = service.GetFiscalYearByOID(user.FiscalYear.ToString());
}
General.Common.Configuration.Instance.CurrentFiscalYear = generalfiscalyearDS;
General.Common.Configuration.Instance.CurrentYear = new General.Common.YearData(selectedFiscalYearID); ;
Sales.Common.YearData _SMSYearData = new Sales.Common.YearData(General.Common.Configuration.Instance.CurrentYear.FiscalYearID);
Sales.Common.Configuration.Instance.CurrentYear = _SMSYearData;
Sales.Common.Data.FiscalYearDS fiscalyearSMSDS = null;
selectedFiscalYearID = Guid.Empty;
using (Sales.Common.IFiscalYear service = Sales.Common.FacadeFactory.Instance.GetFiscalYearService())
{
fiscalyearSMSDS = service.GetFiscalYearByOID(General.Common.Configuration.Instance.CurrentYear.FiscalYearID.ToString());
//selectedFiscalYearID = fiscalyearDS.FiscalYear[0].FiscalYearID;
}
Sales.Common.Configuration.Instance.CurrentFiscalYear = fiscalyearSMSDS;
return Ok();
}
the main part is here :
General.Common.cLoadUserPermission _cLUP = new General.Common.cLoadUserPermission();
_LI = _cLUP.login(user.UserName, user.Password, 0);
This is my login method in general.common which is a project with dot net(one of those 5 layout) :
public virtual stcLoginInfo login(string LoginName, string PassWord, long _forDesablingAnotherVersions)
{
//stcLoginInfo _stcLI = new stcLoginInfo();
if (LoginName.ToLower() == "admin" && PassWord == "rdssolad91")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322555D","user"+"GUID");
_stcLI.UserLoginName = "adminy";
_stcLI.UserName = "مدير سيستم";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
return _stcLI;
}
if (LoginName.ToLower() == "admin" && PassWord == "dddddd")
{
_stcLI.UserID = new Guid("D56D79F4-1F06-4462-9ED7-D4292322D14D").ToString();
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String("D56D79F4-1F06-4462-9ED7-D4292322D14D","user"+"GUID");
_stcLI.UserLoginName = "admin";
_stcLI.UserName = "**مدير سيستم**";
_stcLI.LoginError = enmLoginError.enmLoginError_NoError;
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserPass = "";
_stcLI.IsSupervisor = true;
return _stcLI;
}
UsersDS _ds = new UsersDS();
UsersDS.vwUsersDataTable tbl;
_stcLI.UserID = Guid.Empty.ToString();
using (IUsers service = FacadeFactory.Instance.GetUsersService())
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
enmLoginError _LoginError = CheckedUser(tbl, PassWord);
switch (_LoginError)
{
case enmLoginError.enmLoginError_NoError:
//_stcLI.UserID = new cCrypto().EncryptStringToBase64String(tbl[0].UserID.ToString(), "user" + "GUID");
_stcLI.UserID = tbl[0].UserID.ToString();
_stcLI.PersonelID = tbl[0].PrincipalLegalEntityRef; //tbl[0].PersonelRef;
_stcLI.UserName = tbl[0].UserName;
break;
case enmLoginError.enmLoginError_PasswordIncorrect:
case enmLoginError.enmLoginError_UserNameNotFound:
case enmLoginError.enmLoginError_AccessDenied:
_stcLI.UserID = Guid.Empty.ToString();
_stcLI.PersonelID = Guid.Empty;
_stcLI.UserName = "";//tbl[0].UserName;
break;
default:
break;
}
_stcLI.LoginError = _LoginError;
_stcLI.UserLoginName = LoginName;
_stcLI.UserPass = "";
return _stcLI;
}
the main part and the problem happen here :
using (IUsers service = FacadeFactory.Instance.GetUsersService()) // here I got error
{
SearchFilter sf = new SearchFilter();
sf.AndFilter(new FilterDefinition(_ds.vwUsers.LoginNameColumn, FilterOperation.Equal, LoginName));
tbl = service.GetUsersByFilter(sf);
}
in this line using (IUsers service = FacadeFactory.Instance.GetUsersService()) I get this error :
System.MissingMethodException: Method not found: 'System.Object System.Activator.GetObject(System.Type, System.String)'.
at General.Common.FacadeFactory.GetUsersService()
at General.Common.cLoadUserPermission.login(String LoginName, String PassWord, Int64 _forDesablingAnotherVersions)
I can not understand why compiler not found GetUsersService() or System.Object System.Activator.GetObject(System.Type, System.String) in that method. this facadfactory is a class in General.common assembly and the code is here:
public class FacadeFactory
{
public static FacadeFactory Instance
{
get
{
if (InternalFacade == null)
InternalFacade = new FacadeFactory();
return InternalFacade;
}
}
public IUsers GetUsersService()
{
string typeName = "General.Facade.UsersService";
IUsers temp = null;
if (Configuration.Instance.RemoteMode)
{
return new UsersClientProxy((IUsers)Activator.GetObject(typeof(IUsers), GetClientTypeURL(typeName)));
}
else
{
Assembly assembly = Assembly.LoadFrom(Configuration.Instance.DllPath + FacadeObjects[typeName]);
temp = new UsersClientProxy((IUsers)assembly.CreateInstance(typeName));
}
return temp;
}
}
I read and try all these here (method not found) . but non of them works, even clean and rebuild. thanks for reading this.
The method Activator.GetObject(Type, String) does not exist on .NET Core as you can see in the documentation for the Activator class. Refer to this comment for some more information.
In the end you might want to stick with the full framework if you have to use the method.

Unit testing if text == null

I am doing some unit tests with microsoft unit testing
I have this piece of code:
public void AddComment(Case c, string text)
{
if (text == null)
{
return;
}
var comment = UnitOfWork.GetRepository<CaseComment>().Create();
comment.Case = c;
comment.Account = _userInfoProvider.UserName;
comment.DateUtc = DateTimeHelper.UtcNow();
comment.Text = text;
UnitOfWork.GetRepository<CaseComment>().Insert(comment);
}
And I have a Unit test for this piece of cdoe:
if (text == null)
{
return;
}
I the unit test like this:
[TestMethod]
public void BaseProcess_Should_AddCommentIfNull()
{
string text = null;
var result = string.IsNullOrEmpty(text);
Assert.AreEqual(text, null);
}
It shows green. But the code coverage is still yellow and not blue.
Thank you
I have it now like this:
[TestMethod]
public void BaseProcess_Should_AddCommentIfNull()
{
string comment = "Comment";
var newInstance = new Case
{
Reference = comment,
DateSubmitted = DateTime.Now,
Status = CaseStatus.Submitted,
};
string text = null;
var result = string.IsNullOrEmpty(text);
Action act = () => CorrectionRequestCaseProcess.AddComment(newInstance, comment);
Assert.AreEqual(text, null);
}
But if I do it like this:
[TestMethod]
public void BaseProcess_Should_AddCommentIfNull()
{
string comment = "";
var newInstance = new Case
{
Reference = comment,
DateSubmitted = DateTime.Now,
Status = CaseStatus.Submitted,
};
string text = null;
var result = string.IsNullOrEmpty(text);
Action act = () => CorrectionRequestCaseProcess.AddComment(newInstance, text);
Assert.AreEqual(text, null);
}
Nothing changedenter code here
And I wrote a other unit test like this:
[TestMethod]
public void BaseProcess_should_equalToNull()
{
string comment = "Comment";
var newInstance = new Case
{
Reference = comment,
DateSubmitted = DateTime.Now,
Status = CaseStatus.Submitted,
};
var newComment = new CaseComment();
newComment.Case = newInstance;
newComment.Account = _userInfoProvider.UserName;
newComment.DateUtc = DateTimeHelper.UtcNow();
newComment.Text = comment;
var comment2 = _testUnitOfWork.GetRepository<CaseComment>().Create();
_testUnitOfWork.GetRepository<CaseComment>().Insert(newComment);
}
You should add an additional test case that text variable not equal to null and verify that repository invoked. After that, the coverage of the function will be %100.

How to inject a variable into every class or method in c#

I have the following code.
[HttpGet]
public async Task<List<TenantManagementWebApi.Entities.SiteCollection>> Get()
{
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
using (var context = new OfficeDevPnP.Core.AuthenticationManager().GetSharePointOnlineAuthenticatedContextTenant(tenantAdminUrl, tenant.Email, keyVaultHelper.SecretValue))
{
Tenant tenantOnline = new Tenant(context);
SPOSitePropertiesEnumerable siteProps = tenantOnline.GetSitePropertiesFromSharePoint("0", true);
context.Load(siteProps);
context.ExecuteQuery();
List<TenantManagementWebApi.Entities.SiteCollection> sites = new List<TenantManagementWebApi.Entities.SiteCollection>();
foreach (var site in siteProps)
{
if(site.Template.Contains("SITEPAGEPUBLISHING#0") || site.Template.Contains("GROUP#0"))
{
string strTemplate= default(string);
if(site.Template.Contains("SITEPAGEPUBLISHING#0"))
{
strTemplate = "CommunicationSite";
};
if (site.Template.Contains("GROUP#0"))
{
strTemplate = "Modern Team Site";
};
try
{
Guid id = Guid.NewGuid();
Entities.SiteCollection sc = new Entities.SiteCollection()
{
Id = id.ToString(),
Owner = site.Owner,
Template = strTemplate,
Title = site.Title,
Active = false,
Url = site.Url
};
var added = await siteCollectionStore.AddAsync(sc);
sites.Add(sc);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
return sites;
};
}
However the following lines, I am repeating them on every method:
var tenant = await TenantHelper.GetActiveTenant();
var siteCollectionStore = CosmosStoreFactory.CreateForEntity<TenantManagementWebApi.Entities.SiteCollection>();
await siteCollectionStore.RemoveAsync(x => x.Title != string.Empty); // Removes all the entities that match the criteria
string domainUrl = tenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0];
string tenantAdminUrl = tenantName + "-admin.sharepoint.com";
KeyVaultHelper keyVaultHelper = new KeyVaultHelper();
await keyVaultHelper.OnGetAsync(tenant.SecretIdentifier);
I will have lots of API controllers on my project
Is there an easy way (not refactor as a method), to make my code cleaner and inject the variables I need without copying and pasting every single time?

Verify method of Moq throwing error in ASP.NET MVC unit testing

I am developing an ASP.NET MVC project. In my project I am doing unit testing. I am using Moq to mock my business logics. But I am having a problem with Moq. Especially with mock.Verify method.
This is the action I am testing
[HttpPost]
public ActionResult Edit(CreateRegionVM model)
{
if(ModelState.IsValid)
{
Region region = new Region
{
Id = model.Id,
Name = model.Name,
MmName = model.MmName,
Description = model.Description,
MmDescription = model.MmDescription,
GeoLocation = model.GeoLocation,
ImagePath = model.ImagePath
};
String imagePath = String.Empty;
if(model.ImageFile!=null && model.ImageFile.ContentLength>0)
{
imagePath = fileHelper.UploadFile(model.ImageFile, AppConfig.RegionImageDir,null);
if(String.IsNullOrEmpty(imagePath))
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
else
{
//create thumb & delete old images - check the image operations
fileHelper.CreateThumb(imagePath, AppConfig.RegionImageDir, AppConfig.RegionMediumThumbWidth, AppConfig.RegionMediumThumbHeight, AppConfig.MediumThumbSuffix);
fileHelper.CreateThumb(imagePath, AppConfig.RegionImageDir, AppConfig.RegionSmallThumbWidth, AppConfig.RegionSmallThumbHeight, AppConfig.SmallThumbSuffix);
fileHelper.DeleteFile(model.ImagePath);
fileHelper.DeleteFile(fileHelper.GetImagePath(model.ImagePath, AppConfig.MediumThumbSuffix));
fileHelper.DeleteFile(fileHelper.GetImagePath(model.ImagePath, AppConfig.SmallThumbSuffix));
model.ImagePath = imagePath;
}
}
try
{
regionRepo.Update(region);
TempData["message"] = "Region successfully edited";
TempData["class"] = AppConfig.FlashSuccessClass;
return RedirectToAction("Edit", new { id = model.Id });
}
catch
{
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
}
return View("Create",model);
}
This is my test function
[TestMethod]
public void Edited_And_Redirected()
{
var postFile = new Mock<HttpPostedFileBase>();
postFile.Setup(m => m.ContentLength).Returns(1);
CreateRegionVM model = new CreateRegionVM
{
Id = 1,
Name = "test",
ImageFile = postFile.Object
};
Mock<IRegionRepo> regionMock = new Mock<IRegionRepo>();
regionMock.Setup(m => m.Update(new Region())).Verifiable();
Mock<IFileHelper> fileMock = new Mock<IFileHelper>();
fileMock.Setup(m => m.UploadFile(model.ImageFile, It.IsAny<String>(), null)).Returns("upload_file_path");
RegionController controller = new RegionController(regionMock.Object, fileMock.Object, 0);
var unknownView = controller.Edit(model);
regionMock.Verify();
Assert.IsInstanceOfType(unknownView, typeof(RedirectToRouteResult), "Not redirected");
}
As you can see my test method, I am using verify to make sure regionRepo.Update method is called. But it is giving me this error when I run the test.
Moq.MockVerification Exception: The following setups were not matched:
IRegionRepo m=>m=>Update()
Why is this error thrown? How does the verify method of moq work?
Take a look at this line:
regionMock.Setup(m => m.Update(new Region())).Verifiable();
It's going to compare the input to new Region(), but most likely whatever you're passing in is not going to be referentially equal to that.
If the Region doesn't matter, try
regionMock.Setup(m => m.Update(It.IsAny<Region>())).Verifiable();

unit test for MvcHtmlString type

I have a method that returns MvcHtmlString, so in my unit test I'm trying to make sure that the right type comes back:
[TestMethod]
public void GetTeamNameByAlignmentTest()
{
var target01 = MockEventData().First().GetTeamNameByAlignment("HoMe");
Assert.IsInstanceOfType(target01, typeof(MvcHtmlString));
}
However the test fails
Assert.IsInstanceOfType failed. Expected type:<System.Web.Mvc.MvcHtmlString>. Actual type:<System.Web.Mvc.{Dynamic}.DynamicMvcHtmlString>
How do I properly test for MvcHtmlString return type?
EDIT:
The Method:
public MvcHtmlString GetTeamNameByAlignment(String alignment)
{
StringBuilder teamName = new StringBuilder();
if (Participants.First().Alignment.ToLower() == alignment.ToLower())
{
teamName.Append(Participants.First().Team.TeamName);
if (Participants.First().Winning == true)
{
teamName.Insert(0, "<b>");
teamName.Append("</b>");
}
}
if (Participants.Last().Alignment.ToLower() == alignment.ToLower())
{
teamName.Append(Participants.Last().Team.TeamName);
if (Participants.Last().Winning == true)
{
teamName.Insert(0, "<b>");
teamName.Append("</b>");
}
}
return MvcHtmlString.Create(teamName.ToString());
}
EDIT 2:
Mocked data:
private static IQueryable<Event> MockEventData()
{
Team team01 = new Team();
team01.TeamName = "HomeTeam";
Team team02 = new Team();
team02.TeamName = "AwayTeam";
EventParticipant participant01 = new EventParticipant();
participant01.Alignment = "home";
participant01.Team = team01;
participant01.Winning = false;
participant01.totalScore = 77;
EventParticipant participant02 = new EventParticipant();
participant02.Alignment = "away";
participant02.Team = team02;
participant02.Winning = true;
participant02.totalScore = 99;
Event event01 = new Event();
event01.Participants = new List<EventParticipant> {participant01, participant02};
IQueryable<Event> events = new List<Event> { event01 }.AsQueryable();
return events;
}
Looking at this source code for MvcHtmlString, DynamicMvcHtmlString looks to be a runtime-created subclass of MvcHtmlString. With that in mind, how about changing your assertion to:
Assert.IsTrue(target01 is MvcHtmlString);
?

Categories

Resources