[英]Creating Mock reference and setup methods for complex operations using MOQ
I have two methods , OpenCertificateStore and FindCertificateBySubjectName and implemented them as following: 我有两个方法,OpenCertificateStore和FindCertificateBySubjectName,并按如下方式实现它们:
public void OpenCertificateStore()
{
if (_certificateStore == default(X509Store))
_certificateStore = new X509Store(StoreLocation.CurrentUser);
_certificateStore.Open(OpenFlags.ReadOnly | OpenFlags.IncludeArchived);
}
public X509Certificate2Collection FindCertificateBySubjectName(string certificateSubjectName)
{
X509Certificate2Collection certificates = new X509Certificate2Collection();
if (_certificateStore != default(X509Store))
{
certificates = _certificateStore.Certificates.Find(X509FindType.FindBySubjectName, certificateSubjectName, true);
}
return certificates;
}
I have my unit test as below: 我的单元测试如下:
[TestClass]
public class MyHealthTests
{
private Mock<Logger> _logger;
private Mock<MYCertificateManager> _certManager;
[TestInitialize]
public void Initialize()
{
_logger = new Mock<Logger>();
_certManager = new Mock<MYCertificateManager>();
}
[TestMethod]
public void PassName_FindCertiFicatebyName_ShouldReturnValid()
{
MyCertificateHelper myCertHelper = new MyCertificateHelper(_logger.Object,_certManager.Object);
myCertHelper.OpenCertificateStore();
var certNameCollection = myCertHelper.FindCertificateBySubjectName("Valid Cert Name");
Assert.IsNotNull(certNameCollection);
Assert.IsTrue(certNameCollection.Count > 0);
}
}
Which works fine , but it would be lot better if I can find a way to mock myCertHelper
. 哪个工作正常,但如果我能找到一种模拟
myCertHelper
的方法会myCertHelper
。
If I do mok them , it returns null as it's not querying actual certificate store. 如果我做了mok,它返回null,因为它不查询实际的证书存储。
How do you mock MyCertificateHelper
? 你如何模仿
MyCertificateHelper
?
You don't. 你没有。
Doing so would have no benefit. 这样做没有任何好处。 If you did, then all of the classes in your test would be mocked out and you would no longer actually be testing any of your code.
如果你这样做了,那么测试中的所有类都将被模拟掉,你将不再真正测试任何代码。 At that point, you might as well delete the test.
此时,您也可以删除测试。 It wouldn't do anything but cost you money to maintain it.
它不会做任何事情,但会花费你的钱来维持它。
My
is useless. My
前缀一切是没用的。 Worse than useless, it's noisy and distracting. Open
or Init
. Open
或Init
等方法。 It's easy to forget to call it or call it too many times.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.