MvcHtmlString类型的单元测试

本文关键字:单元测试 类型 MvcHtmlString | 更新日期: 2023-09-27 18:26:38

我有一个返回MvcHtmlString的方法,所以在我的单元测试中,我试图确保返回正确的类型:

[TestMethod]
public void GetTeamNameByAlignmentTest()
{    
    var target01 = MockEventData().First().GetTeamNameByAlignment("HoMe");    
    Assert.IsInstanceOfType(target01, typeof(MvcHtmlString));
}

但是测试未通过

Assert.IsInstanceOfType failed.  Expected type:<System.Web.Mvc.MvcHtmlString>. Actual type:<System.Web.Mvc.{Dynamic}.DynamicMvcHtmlString>

如何正确测试MvcHtmlString返回类型?

编辑:方法:

 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());
    }

编辑2:

模拟数据:

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;
    }

MvcHtmlString类型的单元测试

查看MvcHtmlString的源代码,DynamicMvcHtmlString看起来是MvcHtmlString的运行时创建的子类。考虑到这一点,不如将您的断言更改为:

Assert.IsTrue(target01 is MvcHtmlString);