【发布时间】:2016-11-23 15:57:08
【问题描述】:
我有一个失败的测试用例,它依赖于一个外部模块。 我想使用 Rhino Mock 生成调用函数的报告。
我创建了一个最小示例来说明我的问题:
using NUnit.Framework;
using Rhino.Mocks;
using System;
namespace StackOverflow_namespace
{
public interface IUsefulService
{
object HiddenAmongManyCalls();
}
public class ThirdPartyBase
{
private int a = 42;
public ThirdPartyBase(IUsefulService service)
{
object liveFastDieYoung = service.HiddenAmongManyCalls();
liveFastDieYoung.Equals(a);
}
}
public class MyParty : ThirdPartyBase
{
public MyParty(IUsefulService service) : base(service)
{
}
}
[TestFixture]
class StackOverflow
{
[Test]
public void Hypothetical()
{
IUsefulService service = MockRepository.GenerateMock<IUsefulService>();
try
{
var party = new MyParty(service);
}
catch(Exception e)
{
string[] calls = MagicallyGetTheCallsThatWereMadeToTheMock();
foreach(var call in calls)
{
//with my visual studio testrunner for nunit 3 I can investigate stored console output
Console.WriteLine(call);
}
Assert.Fail("Excpexted no exception but was '" + e.GetType().Name + "': " + e.Message);
}
}
private string[] MagicallyGetTheCallsThatWereMadeToTheMock()
{
return new[]
{
"This is where I am lost, I do not know how to get the calls from the repository."
};
}
}
}
我试图在网上找到一些东西,但没有成功。
Rhino Mocks 会记录所有通话吗?我可以访问该列表吗?
编辑:
由于我正在寻找我没想到的电话,因此验证期望的尝试没有奏效。
我可以使用GetArgumentsForCallsMadeOn 建立一个呼叫列表。我可以反思一下界面。我为此开始了一种方法,但我目前看不到如何将MethodInfo 转换为Action<T>。
private IEnumerable<string> GetCallsList<Interface>(Interface rhinomock)
{
Type interfaceType = typeof(Interface);
List<MethodInfo> interfaceMethodInfos = new List<MethodInfo>();
List<string> returnInfos = new List<string>();
StringBuilder callbuilder = new StringBuilder();
foreach (var property in interfaceType.GetProperties())
{
interfaceMethodInfos.Add(property.GetGetMethod());
interfaceMethodInfos.Add(property.GetSetMethod());
}
foreach (var method in interfaceType.GetMethods())
{
interfaceMethodInfos.Add(method);
}
foreach (var methodinfo in interfaceMethodInfos)
{
Action<Interface> magic = null; //convert methodinfo into action - still missing
var calls = rhinomock.GetArgumentsForCallsMadeOn(magic); //magic is currently null, here be crash
foreach (var call in calls)
{
bool more = false;
callbuilder.Clear().Append(interfaceType.Name).Append('.').Append(methodinfo.Name).Append('(');
foreach (var parameter in call)
{
if (more){ callbuilder.Append(", "); }
if (null == parameter) { callbuilder.Append("<null>"); }
else { callbuilder.Append(parameter.ToString()); }
more = true;
}
callbuilder.Append(')');
string callInfo = callbuilder.ToString();
returnInfos.Add(callInfo);
}
}
return returnInfos;
}
【问题讨论】:
-
是的 rhinomocks 记录所有方法调用。您可以使用 AssertWasCalled 验证它们的执行情况。
-
@OldFox 我可以验证我期望的一切,但是通过像上面这样的调用,我不希望创建一个报告来显示发生了什么。我认为 VerifyAllExpectations 不会为我做到这一点。
-
在 UT 中,您必须验证预期的行为。监视所有呼叫是一种不好的做法。
VerifyAllExpectations不会解决你的问题。当您不想允许意外调用时,您必须使用严格模拟(今天使用这种模拟被认为是一种不好的做法......)。如果您仍想访问记录:使用反射或下载 rhinomocks 源代码并进行一些更改....
标签: c# rhino-mocks