c# . net Worker服务中的测试用例方法



我是在c#中做单元测试的新手,并试图理解如何在工作服务中使用NUnit做测试用例,我不知道如何复制它,所以它测试与方法相同。这是一个在电脑后台运行和发送短信的服务。

IMessagingInfo.cs—这是我从

检索信息的模型
public interface IMessagingInfo
{
public int? ID { get; set; }
[DataType(DataType.Date)]
DateTime? APPT_DATE { get; set; }
string Location { get; set; }
string TreatmentLocation { get; set; }

string Ward { get; set; }
string APPT_START { get; set; }
Guid? ApptId { get; set; }
string MobilePhone { get; set; }
}

TwilioHandler.cs: -这个方法将检查确保数据库中的值是正确的,并且有值,以便服务不会在文本中发送空白信息。

public bool CheckModelFieldsValid(IMessagingInfo item)
{
if(item == null)
{
return false;
}
//implement this later as the mobile phone numbers have some that are null in DB
// if (string.IsNullOrEmpty(item.MobilePhone))
//{
//   return false;
// }
// 
if (item.APPT_START == null)
{
return false;
}
if (string.IsNullOrEmpty(item.TreatmentLocation))
{
return false;
}
if (string.IsNullOrEmpty(item.Location))
{
return false;
}
if(string.IsNullOrEmpty(item.Ward))
{
return false;
}
if (item.ApptId == null)
{
return false;
}
return true;
}

这是我目前为止在TwilioHandlerTests.cs中所做的,我不理解单元测试的逻辑,关于如何设置框架和测试用例。

public class Tests
{
//dbcontext, TwilioHandler, TwilioAccount
private Mock<DbContextConn> _MockDbContext;
private Mock<IOptions<TwilioAccount>> _mockoptions;
private Mock<ILogger<TwilioHandler>> _mockLogger;
TwilioHandler _twh;
private Mock<IMessagingInfo> _MessagingInfoMock = new Mock<IMessagingInfo>();

[SetUp]
public void Setup()
{
_MockDbContext = new Mock<DbContextConn>();
_mockLogger = new Mock<ILogger<TwilioHandler>>();
_mockoptions = new Mock<IOptions<TwilioAccount>>();
//inmemorydatabase routine to add records 
}
[Test]
public void CheckTwilioAccount_ModelFields_Valid_Test()
{
//want to replicate method here
}

谢谢!

我已经建议使用FluentValidation,但如果你不想这样做,您可以使它更容易测试。

如果你看一下,验证DTO并不是TwilioHandler真正关心的问题(至少不应该是)。那么为什么不把它分解到它自己的类中呢?

然后你可以很容易地测试这个类/方法,而不需要模拟TwilioHandler的任何依赖。

您需要做的就是创建可能导致验证失败的情况(*),并检查它们是否会失败。反之亦然,创建一个应该通过的案例的代表性样本,并检查它们是否通过。

*)对这些情况建模的实例。例如有"item == null"的实例

的例子:

[Test]
void Validation_should_fail_if_item_is_null()
{
bool expected = false;
// Assuming the Validator class is called "IMessagingInfoValidator", and there has been 
// setup a testsubject Instance named "ItemNullInstance".
bool actual = new IMessagingInfoValidator().Validate(ItemNullInstance);
Assert.That(actual, Is.EqualTo(expected));
}

对于其他属性,您将编写各自的测试。

最新更新