简体   繁体   English

如何为具有内部构造函数的 model 创建测试替身? 使用 c#、xunit 和 nsubstitute

[英]How to create a test double for model that has internal constructor? using c#, xunit and nsubstitute

I have a method that calls azure API to list blobs from a given container.我有一个调用 azure API 的方法来列出给定容器中的 blob。 Then I have some business logic (mostly based on their names) and then this method deletes some of the blobs.然后我有一些业务逻辑(主要基于它们的名称),然后此方法删除了一些 blob。

So there is a call to BlobContainerClient.GetBlobs所以调用了BlobContainerClient.GetBlobs

Now I want to create some unit test, to be sure that my code really do what I want it to do (with xunit and nsubstitute).现在我想创建一些单元测试,以确保我的代码确实按照我的意愿执行(使用 xunit 和 nsubstitute)。

While I can mock the call to GetBlobs without any problems (it is declared virtual), what is the best way to build the fake list of BlobItem's?虽然我可以毫无问题地模拟对 GetBlobs 的调用(它被声明为虚拟的),但构建 BlobItem 的假列表的最佳方法是什么?

BlobItem class has an internal constructor, and its Name property is neither abstract or virtual. BlobItem class 有一个内部构造函数,它的 Name 属性既不是抽象的也不是虚拟的。

So far:迄今为止:

  1. I think this library is not designed for allowing to test easily, I might open a ticket in github我认为这个库不是为了方便测试而设计的,我可能会在 github 开票

  2. I implemented a hacky solution using reflection, but if we start to have this kind of code all around it is going to be messy我使用反射实现了一个 hacky 解决方案,但如果我们开始到处都是这种代码,它就会变得混乱

    private static T CreateBlobItemStub<T>(string name, params object[] args) { var type = typeof(T); var instance = type.Assembly.CreateInstance( type.FullName, false, BindingFlags.Instance | BindingFlags.NonPublic, null, args, null, null); type.GetProperty("Name").SetMethod.Invoke(instance, new object[] { name }); return (T)instance; }
  3. Maybe there is some library that does it better?也许有一些图书馆做得更好? if so please can you advise如果是的话请你建议

  4. Any other advice?还有其他建议吗?

Thanks !谢谢 !

A factory exists to create instances designed for mocking purposes: BlobsModelFactory存在一个工厂来创建为 mocking 目的而设计的实例: BlobsModelFactory

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

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