例如,您正在测试 getSomeString
。
public class Class1
{
public Class1() {}
public string getSomeString(string input)
{
//dosomething
OtherClass class = new OtherClass();
return class.getData();
}
}
public class OtherClass
{
public OtherClass() {/*some data*/}
public string getData()
{
//do something
string aString = getAString(Input);
//do something
}
public virtual string getAString(string input);
{
//do something to be mocked
return somethingToBeMocked;
}
}
因此您需要单元测试来模拟 getAString
。你是怎么做到的?
我试过模拟 getAString
并希望测试使用模拟值,但这不起作用。
我已经尝试模拟 Class1
并将单元测试 class1
设置为模拟对象,但我不知道如何制作模拟的 getAString
传递到模拟的 class1
中。
我不知道该怎么办。
最佳答案
您不能只获取任何代码并对其进行单元测试。代码应该是可测试的。什么是可测试代码?这是一个依赖于抽象而不是实现的代码。避免依赖实现的唯一方法是通过依赖注入(inject)提供它们:
public class Class1()
{
private IOtherClass _otherClass; // depend on this abstraction
public Class1(IOtherClass otherClass) // constructor injection
{
_otherClass = otherClass;
}
public string getSomeString(string input)
{
//dosomething
return _otherClass.getData(); // you don't know implementation
}
}
其中IOtherClass
接口(interface)由OtherClass
实现
public interface IOtherClass
{
string getData();
}
现在你的类依赖于抽象,你可以为测试模拟抽象:
string data = "Foo";
Mock<IOtherClass> otherClassMock = new Mock<IOtherClass>();
otherClassMock.Setup(oc => oc.getData()).Returns(data);
var class1 = new Class1(otherClassMock.Object);
// Act
string result = class1.getSomeString("Bar");
// Assert
Assert.That(result, Is.EqualTo(data));
otherClassMock.VerifyAll(); // check dependency was called
关于c# - 模拟由您正在单元测试的函数调用的函数。使用起订量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20402682/