我正在尝试对类中的eventHandler进行单元测试,但我并不确定如何将有效数据放入测试中。提前谢谢!
public class BriefAssociation
{
public static event EventHandler<AssociationEventArgs> BriefAssociationChanged;
public static event EventHandler<AssociationEventArgs> BriefAssociationChangedEvent;
public static void OnBriefAssociationChanged(AssociationEventArgs e)
{
BriefAssociationChanged(null, e);
}
public static bool HasListener(EventHandler<AssociationEventArgs> TestCheck)
{
if ((BriefAssociationChangedEvent != null))
if ((BriefAssociationChangedEvent.GetInvocationList().Length > 0))
{
return true;
}
return false;
}
}
public class AssociationEventArgs
{
public int CustomerID;
}
更改以下编辑适用于评论中讨论的错误
public class BriefAssociation
{
public static event EventHandler<AssociationEventArg> BriefAssociationChanged;
public static event EventHandler<AssociationEventArg> BriefAssociationChangedEvent;
public static void OnBriefAssociationChanged(AssociationEventArg e)
{
BriefAssociationChanged(null, e);
}
public static bool HasListener(EventHandler<AssociationEventArg> TestCheck)
{
if ((BriefAssociationChangedEvent != null))
if ((BriefAssociationChangedEvent.GetInvocationList().Length > 0))
{
return true;
}
return false;
}
}
public class AssociationEventArg
{
public int CustomerID;
}
答案 0 :(得分:1)
对于第二种方法&#34; HasListener&#34;我有一个测试,它给它一个空值来测试if语句但我需要给它一个长度大于0的值来测试函数的其余部分。我希望这是有道理的。
这是一个可能有帮助的简单测试
[Test]
public void should_raise_event()
{
BriefAssociation.BriefAssociationChangedEvent += BriefAssociationChanged;
bool result = BriefAssociation.HasListener(null);
Assert.True(result);
}
public void BriefAssociationChanged(Object obj, AssociationEventArgs associationEventArgs)
{ }
答案 1 :(得分:1)
这是第一种方法所需的所有测试:
[Test]
public void OnBriefAssociationCHanged_ShouldRaiseBriefAssociationChangedEvent()
{
// Data
object resultSender = null;
AssociationEventArgs resultArgs = null;
AssociationEventArgs testArgs = new AssociationEventArgs();
// Setup
BriefAssociation.BriefAssociationChanged += (sender, args) =>
{
resultSender = sender;
resultArgs = args;
};
// Test
BriefAssociation.OnBriefAssociationChanged(testArgs);
// Analysis
Assert.IsNull(resultSender);
Assert.AreSame(resultArgs, testArgs);
}