繁体   English   中英

如何以编程方式退出正在运行的单元测试(使用Visual Studio c#和单元测试框架)

[英]How to exit a running unit test programmatically (with Visual Studio c#, and unit test framework)

如果我当前正在执行一个自动化测试,则在遇到问题(例如网络停止或被测系统(SUT)关闭)时,我需要退出自动化。

如果我尝试Assert.Inconclusive(“ some message”),它不会优雅地处理该异常。 我希望框架将信息记录到记录器中,优雅地退出测试,然后继续下一个测试。

有人处理过这个问题吗? 我需要它执行类似的操作-(驱动程序是Chrome WebDriver(硒))。

// ---- 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的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 ...”更好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM