如何集成测试Azure Web Jobs? [英] How to integration test Azure Web Jobs?

查看:56
本文介绍了如何集成测试Azure Web Jobs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET Web API应用程序,该应用程序支持Azure Web Job,其功能由API控制器添加到存储队列的消息触发.使用OWIN测试Web API非常简单,但是如何测试Web作业?

I have a ASP.NET Web API application with supporting Azure Web Job with functions that are triggered by messages added to a storage queue by the API's controllers. Testing the Web API is simple enough using OWIN but how do I test the web jobs?

我是否在测试运行器的内存中运行控制台应用程序?直接执行功能(虽然那不是适当的集成测试)?这是一项持续的工作,因此该应用程序不会退出.更糟糕的是,Azure Web作业功能无效,因此没有要声明的输出.

Do I run a console app in memory in the test runner? Execute the function directly (that wouldn't be a proper integration test though)? It is a continious job so the app doesn't exit. To make matters worse Azure Web Job-functions are void so there's no output to assert.

推荐答案

@ boris-lipschitz是正确的,但是当您的工作很连续时(如op所说的那样),在调用host.RunAndBlock( ).

While @boris-lipschitz is correct, when your job is continious (as op says it is), you can't do anything after calling host.RunAndBlock().

但是,如果在单独的线程中运行主机,则可以根据需要继续进行测试.不过,您必须在测试结束时进行某种轮询才能知道作业何时运行.

However, if you run the host in a separate thread, you can continue with the test as desired. Although, you have to do some kind of polling in the end of the test to know when the job has run.

示例
要测试的功能(由创建的blob触发的从一个blob到另一个blob的简单副本):

public void CopyBlob(
    [BlobTrigger("input/{name}")] TextReader input,
    [Blob("output/{name}")] out string output)
{
    output = input.ReadToEnd();
}

测试功能:

[Test]
public void CopyBlobTest()
{
    var blobClient = GetBlobClient("UseDevelopmentStorage=true;");

    //Start host in separate thread
    var thread = new Thread(() =>
    {
        Thread.CurrentThread.IsBackground = true;
        var host = new JobHost();
        host.RunAndBlock();
    });

    thread.Start();

    //Trigger job by writing some content to a blob
    using (var stream = new MemoryStream())
    using (var stringWriter = new StreamWriter(stream))
    {
        stringWriter.Write("TestContent");
        stringWriter.Flush();

        stream.Seek(0, SeekOrigin.Begin);

        blobClient.UploadStream("input", "blobName", stream);
    }

    //Check every second for up to 20 seconds, to see if blob have been created in output and assert content if it has
    var maxTries = 20;
    while (maxTries-- > 0)
    {
        if (!blobClient.Exists("output", "blobName"))
        {
            Thread.Sleep(1000);
            continue;
        }

        using (var stream = blobClient.OpenRead("output", "blobName"))
        using (var streamReader = new StreamReader(stream))
        {
            Assert.AreEqual("TestContent", streamReader.ReadToEnd());
        }
        break;
    }
}

这篇关于如何集成测试Azure Web Jobs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆