我是新手使用Moq而我找不到这样做的方法 . 我有一个generateId私有方法,叫做
/// <summary>
/// Generates a call Id for external interfaces
/// </summary>
/// <returns></returns>
private string GenerateCallId()
{
return "EX" + SharedServicesClientProxy.Instance.GenerateId().ToString();
}
我想对这个方法进行单元测试,因此我需要模拟代理 . SharedServicesClientProxy只是一个实现接口ISharedServices但添加单例的对象 . 我想测试所有字符串是否正确返回以“EX”开头的字符串 . 这是我的单元测试,使用Moq
/// <summary>
/// A test for GenerateCallId
/// A CallId for external systems should always start by "EX"
///</summary>
[TestMethod()]
[DeploymentItem("myDll.dll")]
public void GenerateCallIdTest()
{
myService_Accessor target = new myService_Accessor();
var SharedServicesClientProxy = new Mock<ISharedServices>();
SharedServicesClientProxy.Setup(x => x.GenerateId()).Returns(5396760556432785286);
string actual;
string extCallIdPrefix = "EX";
actual = target.GenerateCallId();
Assert.IsTrue(actual.StartsWith(extCallIdPrefix));
}
我想我在错误的地方做我的模拟?
以更一般的方式,我如何模拟将要通过我正在测试的方法调用的对象?例如:
/// <summary>
/// dummy test
///</summary>
[TestMethod()]
[DeploymentItem("myDll.dll")]
public void Foo()
{
myService_Accessor target = new myService_Accessor();
boolexpected = false;
actual = target.Foo();
Assert.IsTrue(actual,expected);
}
/// <summary>
/// Foo
/// </summary>
/// <returns></returns>
private bool Foo()
{
return this.Bar();
}
我需要moq Bar,但我需要在哪里做呢?谢谢,Seb
1 回答
在继续之前搜索“依赖注入”一词 .
你对
SharedServicesClientProxy.Instance
有依赖,这是一个单身人士 . 这将导致测试隔离问题,因为您将跨测试重用相同的实例,并且容易出现状态遗留问题 .我建议注入像这样的依赖项(和OT-你不应该测试私有方法...通过公共接口测试 . 它在我的系统之外.. :)
重新连接当前代码以创建这样的目标类
在测试中,传入模拟对象而不是Singleton返回的对象