我的UnitTest工作,Controller中的相同代码不起作用

时间:2017-05-05 10:32:13

标签: c# asp.net asp.net-mvc unit-testing mstest

这是我在这里的第一篇文章,我是C#的新手。 我正在研究Microsoft Cognitive API(它从图像中提取信息),您发送HTTP请求,从Microsoft服务器获得答案。 - https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/tutorials/csharptutorial

这是我的UnitTest(这个有效)

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;
using fw8.CognitiveServices;

namespace ImageTests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestImagefromURL()
        {
            Debug.WriteLine("Test was loaded");
            Manager instance = new Manager();
            var client = instance.StartMyTask().Result;
            Debug.WriteLine("Caption: " + client.Description.Captions[0].Text);
        }
    }
}

此测试的输出是

Test Name:  TestImagefromURL
Test Outcome:   Passed
Result StandardOutput:  
Trace du débogage :
Test was loaded
Task started
processing
finish
Caption: a man holding a cat

在类库中调用这些方法

using System.Threading.Tasks;
using Microsoft.ProjectOxford.Vision.Contract;
using Microsoft.ProjectOxford.Vision;
using System.IO;
using System.Diagnostics;

namespace fw8.CognitiveServices
{
    public class Manager
    {
        public async Task<AnalysisResult> StartMyTask()
        {
            Debug.WriteLine("Task started");
            return await UploadAndAnalyzeImage(@"C:\Users\danie\Desktop\tot.jpg");//For testing purpose, a file from my computer
        }

        private static async Task<AnalysisResult> UploadAndAnalyzeImage(string imageFilePath)
        {
            Debug.WriteLine("processing");
            VisionServiceClient VisionServiceClient = new VisionServiceClient("APIKEY");

              using (Stream imageFileStream = File.OpenRead(imageFilePath))
            {
                VisualFeature[] visualFeatures = new VisualFeature[] { VisualFeature.Adult, VisualFeature.Categories, VisualFeature.Color, VisualFeature.Description, VisualFeature.Faces, VisualFeature.ImageType, VisualFeature.Tags };
                AnalysisResult analysisResult = await VisionServiceClient.AnalyzeImageAsync(imageFileStream, visualFeatures);
                Debug.WriteLine("finish");
                return analysisResult;
            }

        }
    }
}

现在来自一个空白的MVC项目调用相同的方法

using fw8.CognitiveServices;
using System.Diagnostics;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public void Test()
        {

            Debug.WriteLine("Test was loaded");
            Manager instance = new Manager();
            var client = instance.StartMyTask().Result;
            Debug.WriteLine("Caption: " + client.Description.Captions[0].Text);
        }
    }
}

提前感谢那些可以开导我的人! ;)

编辑:Oups

code:-32000
message:No script for id: 35
'iisexpress.exe' (CLR v4.0.30319: Domain 3): Unloaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'
'iisexpress.exe' (CLR v4.0.30319: AppInsightsDomain-0cd03d5b-6ce4-4019-ae7e-b1df44463c51): Unloaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Web\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Web.dll'
'iisexpress.exe' (CLR v4.0.30319: AppInsightsDomain-0cd03d5b-6ce4-4019-ae7e-b1df44463c51): Unloaded 'C:\Users\danie\AppData\Local\Temp\Temporary ASP.NET Files\vs\2f3c5b55\37cedeaf\assembly\dl3\94ecb1d3\002a8e73_afafd201\Microsoft.AI.WindowsServer.dll'
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Message","time":"2017-05-05T10:08:49.8412130Z","tags":{"ai.internal.sdkVersion":"dotnet:2.3.0-41907","ai.operation.id":"OxulrgX+fP0=","ai.location.ip":"127.0.0.1","ai.operation.syntheticSource":"SDKTelemetry","ai.cloud.roleInstance":"DESKTOP-TE2K4KD","ai.operation.name":"GET /","ai.operation.parentId":"OxulrgX+fP0="},"data":{"baseType":"MessageData","baseData":{"ver":2,"message":"AI: Diagnostic message: Performance counters are unavailable when the application is running under IIS Express. Use EnableIISExpressPerformanceCounters element with a value of 'true' within the Performance Collector Module element to override this behavior."}}}
Test was loaded
Task started
processing
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.RemoteDependency","time":"2017-05-05T10:08:51.1478126Z","tags":{"ai.internal.sdkVersion":"rddf:2.3.0-1223","ai.internal.nodeName":"DESKTOP-TE2K4KD","ai.operation.id":"F5d9uEXsrsw=","ai.location.ip":"::1","ai.cloud.roleInstance":"DESKTOP-TE2K4KD","ai.operation.name":"GET Home/Index","ai.operation.parentId":"F5d9uEXsrsw="},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"/vision/v1.0/analyze","id":"LikCUv5jYNQ=","data":"https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures=Adult,Categories,Color,Description,Faces,ImageType,Tags&subscription-key=d29a6dad583544d385357110f86d0ea4","duration":"00:00:04.4499171","resultCode":"200","success":true,"type":"Http","target":"westus.api.cognitive.microsoft.com","properties":{"DeveloperMode":"true"}}}}
The program '[17736] chrome.exe: WebKit' has exited with code -1 (0xffffffff).
The program '[5428] iisexpress.exe' has exited with code -1 (0xffffffff).

编辑2:

不知道它是否非常微妙,但实际上当你同步而不是异步地执行这些方法时它会起作用。

2 个答案:

答案 0 :(得分:0)

如果您正在调用async方法,则还应该使用控制器方法async。你的方法也应该真正返回某些东西 ......

e.g。

[HttpPost]
public async Task<ActionResult> Test()
{
    Debug.WriteLine("Test was loaded");
    Manager instance = new Manager();
    var client = await instance.StartMyTask();
    return Content("Caption: " + client.Description.Captions[0].Text);
}

答案 1 :(得分:0)

如果使用Task<>,您应该尝试一直使用异步,以避免像.Result.Wait()这样的异步/等待和阻止调用导致死锁的情况。 / p>

测试可以转换为异步。

namespace ImageTests
{
    [TestClass]
    public class UnitTest1 {
        [TestMethod]
        public async Task TestImagefromURL() {
            Debug.WriteLine("Test was loaded");
            var instance = new Manager();
            var client = instance.StartMyTask();
            Debug.WriteLine("Caption: " + client.Description.Captions[0].Text);
        }
    }
}

Asp.Net MVC在其框架内广泛使用async Task。这意味着你要么一直是同步的,要么就是你的行为一直异步。混合它们会产生不良影响。

public class HomeController : Controller {
    public ActionResult Index() {
        return View();
    }

    [HttpPost]
    public async Task<ActionResult> Test() {
        Debug.WriteLine("Test was loaded");
        var instance = new Manager();
        var client = await instance.StartMyTask();
        var msg = "Caption: " + client.Description.Captions[0].Text;
        Debug.WriteLine(msg);
        return Json(msg, JsonRequestBehavior.AllowGet);
    }
}