简体   繁体   中英

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

If I have an automated test that is currently executing, I need the automation to exit if it runs into a problem, such as a network stoppage or when the System Under Test (SUT) is down.

If I try to Assert.Inconclusive("some message"), it doesn't handle the exception gracefully. I want the framework to log the info to the logger, exit the test gracefully, and go on to the next test.

Has anyone dealt with this issue? I need it to do something like this -- (the driver is the Chrome WebDriver (selenium)).

// ---- check for services down warning  -----
        bool isDown = await CheckForServicesWarning(driver);
        if (isDown == true)
        {
            Log("XYZ is currently experiencing technical difficulties.");
            return;
        }

You are right in the sense that you should test for an external resource availability. However, you don't touch this resource directly. Instead, you mock it.

Lets assume that your service reaches out to a database and has a method ReadCustomerNameById(int id) . First, extract it to an interface that we will call IMyService . Your service (lets call it MyService ) should now implement this interface. Both the interface and your service look like:

public interface IMyService
{
    string ReadCustomerNameById(int id);
}

public class MyService : IMyService
{
    public string ReadCustomerNameById(int id)
    {
        return "Gixabel"; //replace this with your actual implementation
    }
}

Now we have to write a class where we can use MyService and have all the business logic we might need. Lets call this class Customer and it looks like:

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;
    }
}

I'm taking advantage of some dependency injection here. Out of scope.

Now we are ready to write some tests. Find and install a Nuget called Moq . I personally like nUnit but you can easily translate this sample to MSTest or any other.

We start declaring our Customer class and a mock of MyService . Then we create an instance of Customer and a mock of IMyService on our setup.

Now we do a normal test where we assume MyService is working properly.

The last test is the interesting one. We force the service to throw an exception and we assert it actually does.

[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));
    }
}

Now you are completely decoupled from the service you are trying to use. Now you can commit to GitHub, Azure Devops, etc. and run tests without any external dependency.

Additionally you could try/catch, handle error messages and test them. But this should get you going.

As a side note, try FluentAssertions . It reads better than 'Assert.AreEqual...'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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