调用其他方法的方法的nunit测试

时间:2014-05-29 08:05:59

标签: c# .net unit-testing nunit

非常新的nunit.below是业务单位代码

public enum HighlightType
{
    IP,
    Item,
    Address
}

public class UniformGridHighlighting
{
    public static event HighlightingChangedDelegate HighlightingChanged;

    private static List<string> _highlightedIPs = new List<string>();
    private static List<long> _highlightedItems = new List<long>();
    private static ContactInfoType _highlightedAddress;

    public static void ClearIPHighlighting()
    {
        _highlightedIPs.Clear();
        OnHighlightingChanged(HighlightType.IP);
    }

    private static void OnHighlightingChanged(HighlightType type)
    {
        if (HighlightingChanged != null)
        {
            HighlightingChanged(type);
        }
    }
}

我需要为ClearIPHighlighting编写单元测试用例。我该怎么办?

  [Test(Description = "to ")] 
  public void ClearIPHighlightingTets()
  {
       UniformGridHighlighting.ClearIPHighlighting();
       //How to call method
  }

1 个答案:

答案 0 :(得分:0)

鉴于当前设置,您只能测试事件是否被触发。

 [Test()] 
 public void ThatTheEventIsTriggeredWhenTheListIsCleared()
 {
    // Arrange
    bool eventTriggered = false;
    UniformGridHighlighting.HighlightingChanged += _ => { eventTriggered= true; };

    //Act
    UniformGridHighlighting.ClearIPHighlighting();

    //Assert:
    Assert.IsTrue(eventTriggered);
 }

它的类型正确

 [Test(Description = "to ")] 
 public void ThatTheEventIsTriggeredWithTheIPArgumentWhenTheIPListIsCleared()
 {
    // Arrange
    HighlightType? type = null;
    UniformGridHighlighting.HighlightingChanged += x => { type = x; };

    //Act
    UniformGridHighlighting.ClearIPHighlighting();

    //Assert:
    Assert.AreEqual(s, HighlightType.IP);
 }

要测试您之前的高光被删除会更难:

 [Test] 
 public void ThatTheIpIsNotHighlightedIfTheListWasCleared()
 {
    UniformGridHighlighting.HighlightIP("1.1.1.1");

    //Act
    UniformGridHighlighting.ClearIPHighlighting();
    UniformGridHighlighting.Highlihst(Grid);

    //Assert:
    //Go through the grid to figure out that the IP was not highlighted. The below is a total guess:
    bool wasHighlighted = Grid.Rows.Any(row => row.Cells.Any(Cell.Highlighted));
    Assert.Isfalse(wasHighlighted);
 }