如果我有一个当前正在执行的自动化测试,如果它遇到问题,比如网络中断或被测系统(SUT)停机,我需要自动化退出。
如果我尝试Assert.Inconclusive(“一些消息”),它不能很好地处理异常。我希望框架将信息记录到记录器中,优雅地退出测试,然后继续下一个测试。
有人处理过这个问题吗?我需要它来做这样的事情-- (驱动程序是Chrome WebDriver (selenium))。
// ---- check for services down warning -----
bool isDown = await CheckForServicesWarning(driver);
if (isDown == true)
{
Log("XYZ is currently experiencing technical difficulties.");
return;
}发布于 2019-05-30 14:41:42
你是对的,你应该测试外部资源的可用性。但是,您不能直接接触此资源。取而代之的是你嘲笑它。
让我们假设您的服务连接到一个数据库,并且有一个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的Nuget。我个人喜欢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...‘更好。
https://stackoverflow.com/questions/56279504
复制相似问题