moq

使用 xUnit 编写 ASP.NET Core 单元测试

五迷三道 提交于 2020-08-13 18:21:46
还记得 .NET Framework 的 ASP.NET WebForm 吗?那个年代如果要在 Web 层做单元测试简直就是灾难啊。.NET Core 吸取教训,在设计上考虑到了可测试性,就连 ASP.NET Core 这种 Web 或 API 应用要做单元测试也是很方便的。其中面向接口和依赖注入在这方面起到了非常重要的作用。 本文就来手把手教你如何用 xUnit 对 ASP.NET Core 应用做单元测试。.NET Core 常用的测试工具还有 NUnit 和 MSTest,我本人习惯用 xUnit 作为测试工具,所以本文用的是 xUnit。 创建示例项目 先用 ASP.NET Core API 模板建一个应用。 模板为我们自动创建了一个 ValuesController,为了方便演示,我们只留其中一个 Get 方法: public class ValuesController : ControllerBase { // GET api/values/5 [HttpGet( "{id}" )] public ActionResult< string > Get ( int id) { return "value" ; } } 然后再添加一个 xUnit 单元测试项目: 模板自动为我们添加好了 xUnit 引用: < ItemGroup > < PackageReference

Setting up returns with generic parameters

独自空忆成欢 提交于 2020-08-09 14:55:26
问题 So using Moq to try and do unit tests, I have something like this method I'm trying to mock: Task<S> UseFooAsync<S>(Func<T, S> func); And I can set it up, for a specific case, like this: data.Setup(r => r.UseFooAsync(It.IsAny<Func<DB, MyBar>>())) .Returns(Func<DB, MyBar> f => Task.FromResult(f(myMockObj.Object)); For the case where I specify all the generic type parameters. And I can confirm it works because in my test I can do: myMockObj.Verify(m => m.SomeFunction(), Times.Once); Which will

非易失性MRAM技术发展

北城以北 提交于 2020-08-08 12:11:58
切换(或场驱动) MRAM 包括大部分的独立MRAM设备。然而切换MRAM的规模不足以取代大多数其他记忆。STT-MRAM产品将扩展到更高的密度,需要更低的能量写比切换MRAM。2019年已发运大部分MRAM内存的Everspin开始向STT-MRAM发运最高1Gb的芯片容量,这种内存密度使这些设备在许多应用中更受关注。Everspin代理商英尚微电子提供产品技术支持及解决方案. 主要的嵌入式半导体制造商为工业和消费应用中使用的嵌入式产品提供MRAM非易失性存储器选项。这些铸造厂包括全球铸造厂、英特尔、三星和TSMC。 STT-MRAM 有很高的性能,但不如最快的静态随机存取存储器快。然而一种被称为自旋轨道转矩(SOT)的MRAM技术有潜力匹配静态随机存储器的性能。 磁性随机存取存储器(场或自旋器件)使用一个选择晶体管作为存储单元,见下图1。MRAM单元可以具有专用晶体管,或者该晶体管可以在两个存储单元之间共享。在用于MRAM生产之前,必须在晶片上创建特定的选择晶体管设计。 图1 MRAM记忆细胞 目前MRAM软件技术正在世界各地的实验室中开发,但是随着STT-MRAM产品成本的降低,无论是嵌入式产品还是独立产品,MRAM软件技术都可能成为MRAM取代最快的静态随机存取存储器应用的手段,提供更高的非易失性存储器密度,从而支持非常低功耗的物联网和人工智能应用。 Everspin代理

泛型方法 —— 动态设置方法所需的特定类型

谁说我不能喝 提交于 2020-08-06 02:09:19
// 已知 Type type // 已知 string file var method = this.GetType().GetMethod(nameof(ImportDatabaseFromCsv), BindingFlags.Instance | BindingFlags.Public); //获取泛型方法 var destMethod = method.MakeGenericMethod(type);//设置泛型对应的特定类型 destMethod.Invoke(this, new object[] { file });//调用泛型方法 & 传参    //泛型方法 public void ImportDatabaseFromCsv<T>(string file) where T : class { //…… }    //moq中对泛型的应用 public class CustomerDefaultValueProvider<T> : DefaultValueProvider where T : class { T _instance; public CustomerDefaultValueProvider(T instance) { _instance = instance; } protected override object GetDefaultValue

Moq is slow to verify dependency after a large number calls

♀尐吖头ヾ 提交于 2020-07-22 21:31:30
问题 I've hit a snag when using Moq to simulate an dependency which is called a large number of times. When I call Verify , Moq takes a long time (several minutes) to respond, and sometimes crashes with a NullReferenceException (I guess this is understandable, given the amount of data that Moq would have to accumulate to do the Verify from a "cold start"). So my question is, is there another strategy that I can use to do this using Moq, or should I revert to a hand-crafted stub for this rather

How to create mock for httpclient getasync method?

三世轮回 提交于 2020-07-21 12:54:25
问题 I am using Moq to create mocks for my unit tests but I am stuck when I have to create mock for getasync method of httpclient. Previously I was using SendAsync method and for that I could use the below code: var mockResponse = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(expectedResponse)}; mockResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var mockHandler = new Mock<DelegatingHandler>(); mockHandler .Protected() .Setup<Task

Moq Verify events triggered

别等时光非礼了梦想. 提交于 2020-07-04 10:59:26
问题 class A { event EventHandler Event1; } var mock = new Mock<A>(); How do I verify Event1 was fired? (without using manual event handlers / triggered flags) 回答1: var mock = new Mock<IInterfaceWithEvent>(); mock.Raise(e => e.MyEvent += null, EventArgs.Empty); mock.VerifyAll(); or if you want to make sure that act raises an event, your setup should look like: mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty); // ... mock.VerifyAll(); 回答2: I'm not sure I really

Testing Polly retry policy with moq

独自空忆成欢 提交于 2020-06-27 14:47:52
问题 I'm trying to write a unit test for polly, but it looks like the return is cached. Method PostAsyncWithRetry: using Polly; using System; using System.Diagnostics; using System.Net.Cache; using System.Net.Http; public class RetryClient { private HttpClient httpClient = new HttpClient(new WebRequestHandler() { CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore) }); public HttpResponseMessage PostAsyncWithRetry( String url, String path, StringContent httpContent) {

How to mock REST API

こ雲淡風輕ζ 提交于 2020-06-27 07:26:21
问题 I have an MVC application that needs to invoke a REST API from a third party vendor. The REST API should return a JSON result, but it won't be ready before we start developing and testing our MVC application, so I would like to mock the REST API (that vendors will be providing). I researched MOQ but it doesn't seem to support mocking of REST API. 回答1: The best approach probably depends what requires the least learning curve and setup for you and what fits in your environment. I have done this

How to mock REST API

随声附和 提交于 2020-06-27 07:26:10
问题 I have an MVC application that needs to invoke a REST API from a third party vendor. The REST API should return a JSON result, but it won't be ready before we start developing and testing our MVC application, so I would like to mock the REST API (that vendors will be providing). I researched MOQ but it doesn't seem to support mocking of REST API. 回答1: The best approach probably depends what requires the least learning curve and setup for you and what fits in your environment. I have done this