[英]Verify a private method gets call Unit Test
I have an interface with a method like this:我有一个带有这样方法的接口:
public string GetImageSrc(string input);
The implementation of this is below:其实现如下:
public string GetImageSrc(string input)
{
if (input.ContainsImage())
{
DoWork();
}
return input;
}
My string extension for ConatinsImage is:我的 ConatinsImage 字符串扩展名是:
public static bool ContainsImage(this string input)
{
if (!string.IsNullOrEmpty(input))
{
return input.Contains("img");
}
return false;
}
DoWork is a private method in the class. DoWork 是类中的私有方法。 I am writing Unit Tests for the class - I am passing null to the method and doing an assert that null is returned.
我正在为该类编写单元测试 - 我将 null 传递给该方法并断言返回 null。 However is there a way I can Assert the invocation of the DoWork private method is None for a null input?
但是,有没有一种方法可以断言 DoWork 私有方法的调用对于空输入是 None ?
I recommend creating a new interface IWorker with a DoWork() method, then inject it into the constructor of the class that contains the GetImageSrc() method.我建议使用 DoWork() 方法创建一个新接口 IWorker,然后将其注入包含 GetImageSrc() 方法的类的构造函数中。 In your unit test, you could then inject a mock object of the interface, and verify DoWork() was called or not:
在您的单元测试中,您可以注入接口的模拟对象,并验证 DoWork() 是否被调用:
public interface IWorker
{
void DoWork();
}
public class YourClass
{
private readonly IWorker _worker;
public YourClass(IWorker worker)
{
_worker = worker;
}
public string GetImageSrc(string input)
{
if (input.ContainsImage())
{
_worker.DoWork();
}
return input;
}
}
Test using Microsoft.VisualStudio.TestTools.UnitTesting and Moq:使用 Microsoft.VisualStudio.TestTools.UnitTesting 和 Moq 进行测试:
[TestMethod]
public void GetImageSrc_GivenNull_ReturnsNull_And_WorkerNotCalled()
{
var mockWorker = new Mock<IWorker>();
var testSubject = new YourClass(mockWorker.Object);
var response = testSubject.GetImageSrc(null);
Assert.IsNull(response);
mockWorker.Verify(x => x.DoWork(), Times.Never());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.