如果我有一个当前正在执行的自动化测试,我需要自动化在遇到问题时退出,例如网络中断或被测系统 (SUT) 关闭时。
如果我尝试 Assert.Inconclusive("some message"),它不会优雅地处理异常。我希望框架将信息记录到记录器,优雅地退出测试,然后继续下一个测试。
有没有人处理过这个问题?我需要它来做这样的事情——(驱动程序是 Chrome WebDriver (selenium))。
// ---- check for services down warning -----
bool isDown = await CheckForServicesWarning(driver);
if (isDown == true)
{
Log("XYZ is currently experiencing technical difficulties.");
return;
}
在您应该测试外部资源可用性的意义上,您是对的。但是,您不会直接接触此资源。相反,你嘲笑它。
让我们假设您的服务访问数据库并有一个方法ReadCustomerNameById(int id)
。首先,将其提取到我们将调用的接口IMyService
。您的服务(让我们称之为MyService
)现在应该实现这个接口。界面和您的服务都如下所示:
public interface IMyService
{
string ReadCustomerNameById(int id);
}
public class MyService : IMyService
{
public string ReadCustomerNameById(int id)
{
return "Gixabel"; //replace this with your actual implementation
}
}
现在我们必须编写一个类,我们可以在其中使用MyService
并拥有我们可能需要的所有业务逻辑。让我们调用这个类Customer
,它看起来像:
public class Customer
{
private readonly IMyService _service;
public Customer(IMyService service)
{
_service = service;
}
public string CustomerNameById(int id)
{
var result = _service.ReadCustomerNameById(id);
//validate, massage and do whatever you need to do to your response
return result;
}
}
我在这里利用了一些依赖注入。超出范围。
现在我们准备编写一些测试。查找并安装一个名为Moq
. 我个人喜欢,nUnit
但您可以轻松地将此示例翻译为MSTest
或任何其他示例。
我们开始声明我们的Customer
类和一个MyService
. 然后我们在我们的设置上创建一个实例Customer
和一个模拟IMyService
。
现在我们做一个正常的测试,我们假设MyService
它工作正常。
最后一个测试很有趣。我们强制服务抛出异常,我们断言它确实如此。
[TestFixture]
public class CustomerTests
{
private Customer _customer;
private Mock<IMyService> _myService;
[SetUp]
public void Initialize()
{
_myService = new Mock<IMyService>();
_customer = new Customer(_myService.Object);
}
[Test]
public void GivenIdWhenCustomerNameByIdThenCustomerNameReturned()
{
const int id = 10;
const string customerName = "Victoria";
_myService.Setup(s => s.ReadCustomerNameById(id)).Returns(customerName);
var result = _customer.CustomerNameById(id);
Assert.AreEqual(result, customerName);
}
[Test]
public void GivenIdWhenCustomerNameByIdThenException()
{
_myService.Setup(s => s.ReadCustomerNameById(It.IsAny<int>())).Throws<Exception>();
Assert.Throws<Exception>(() => _customer.CustomerNameById(10));
}
}
现在,您已与您尝试使用的服务完全分离。现在您可以提交到 GitHub、Azure Devops 等,并在没有任何外部依赖的情况下运行测试。
此外,您可以尝试/捕获、处理错误消息并对其进行测试。但这应该能让你继续前进。
作为旁注,请尝试FluentAssertions
. 它读起来比“Assert.AreEqual...”好
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句