[英]How to unit test KnockoutUtility in C#?
I have a class that gets knockout messages using the method below: 我有一个使用以下方法获取删除消息的类:
public IEnumerable<Message> GetKnockoutMessages(Data data)
{
if(data.Messages != null)
{
return data.Messages.Where(m => m.UnderWritingRuleId != null);
}
else
{
return new List<Message>();
}
}
So far, i have a unit test that only partially covers the unit test which is below. 到目前为止,我有一个单元测试,仅部分覆盖了下面的单元测试。
[TestMethod]
public void TestGetKnockoutMessages()
{
KnockoutUtility knockUtility = new KnockoutUtility();
IEnumerable<Message> messages = knockUtility.GetKnockoutMessages(MockData.Object);
Assert.IsNotNull(messages);
}
This covers everything but return data.Messages.Where(m => m.UnderWritingRuleId != null);
这将覆盖
return data.Messages.Where(m => m.UnderWritingRuleId != null);
所有内容return data.Messages.Where(m => m.UnderWritingRuleId != null);
I was wondering how I would unit test this method to get 100% coverage. 我想知道如何对该方法进行单元测试以获得100%的覆盖率。
Any help would be appreciated. 任何帮助,将不胜感激。 Thanks
谢谢
This unit test doesn't cover everything because you are not verifying all cases. 该单元测试无法涵盖所有内容,因为您没有验证所有案例。 You have to test two logics:
您必须测试两种逻辑:
if/else
logic if/else
逻辑 Where(m => m.UnderWritingRuleId != null)
logic Where(m => m.UnderWritingRuleId != null)
逻辑 Based on this assumption you have to create cases which proof following: 基于此假设,您必须创建证明以下情况的案例:
data.Messages
are null
then you have to verify that method returns new instance of List<Message>()
because you specified in code like that. data.Messages
为null
则必须验证该方法是否返回List<Message>()
新实例,因为您是在这样的代码中指定的。 IEnumerable<Message>
if data.Messages
are empty (which means this condition data.Messages.Count() == 0
). data.Messages
为空(这意味着此条件data.Messages.Count() == 0
),则验证方法是否返回IEnumerable<Message>
。 Where(m => m.UnderWritingRuleId != null)
. Where(m => m.UnderWritingRuleId != null)
。 In other words only messages which have populated UnderWritingRuleId
. UnderWritingRuleId
消息。 To achieve what I mentioned you have to create Data
objects which satisfied this cases. 为了实现我提到的内容,您必须创建满足这种情况的
Data
对象。 I don't know what is MockData.Object
but I hope that you included you arrangement there. 我不知道什么是
MockData.Object
但我希望您在其中包括您的安排。
Each case should be in separate test method like in following: 每个案例应采用单独的测试方法,如下所示:
[TestMethod]
public void TestGetKnockoutMessages_Case1()
{
// Arrange
// Action
// Assert
}
[TestMethod]
public void TestGetKnockoutMessages_Case2()
{
// Arrange
// Action
// Assert
}
[TestMethod]
public void TestGetKnockoutMessages_Case3()
{
// Arrange
// Action
// Assert
}
Arrange is place where you configuring your mock-ups. 安排是您配置模型的地方。 Action is place where you executing method which you want to test and Assert is place where you doing assertion.
行动是你执行要测试和断言是地方,你做的断言方法的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.