我一直在试图弄清楚我正在编写的这个特定测试发生了什么,现在再次联系,看看是否有人可能知道发生了什么。
我有一个ModeltoXml方法,当我直接通过另一个测试类进行测试时,它很好。然而,在另一种方法中,我正在测试调用ModeltoXml,我在Rhino Mock中创建的存根总是返回null。
下面是我的代码如何通过构造函数传递存根方法的测试。
[Test]
var newEntry = new Model1{name="test"};
var referrer = "http://example.com";
var stubbedConfigMan = MockRepository.GenerateStub<IConfigurationManager>();
var supportMethods = MockRepository.GenerateStub<ISupportMethods>();
stubbedConfigMan.Stub(x => x.GetAppSetting("confEntry1")).Return("pathhere");
supportMethods.Stub(x => x.ModeltoXml(newEntry)).IgnoreArguments().Return("test"); //this is the line of code which should be setting the return value
var testObject = new MyApi().NewTicket(newEntry, referrer, supportMethods, stubbedConfigMan);
为这个测试调用的具体方法有这样一行:
public MyResponseModel NewTicket(Model1 newTicket, string referrer, ISupportMethods supportMethods,IConfigurationManager configMan)
{
//.. other code here
var getXml = supportMethods.ModeltoXml(newTicket); //This line always returns null
}
ModeltoXml方法的简单条目:
public string ModeltoXml<T>(T item)
{
//Code here to serialize response
return textWriter.ToString();
}
我的界面是:
public interface ISupportMethods
{
string ModeltoXml<T>(T item);
}
我创建了另一个基本方法,该方法将提取并返回一个字符串值。我在同一个类中得到了这个工作,但是在测试中,我不得不在存根上使用. ignorearguments选项。此后,在调试时,我看到了设置的返回值。
然而,当我尝试在我的测试类中的有问题的代码行上做同样的事情时,我仍然看到在调试期间,在我的测试类中没有出现返回值。
所以我有点卡住了!在我的测试中,我在其他存根上得到返回值,这是这个特殊的方法/存根,它只是不会玩球。
谢谢。
在相同的测试中,我发现了一个更简单的例子:
var stubbedConfigMan = MockRepository.GenerateStub<IConfigurationManager>();
var supportMethods = MockRepository.GenerateStub<ISupportMethods>();
supportMethods.Stub(x => x.ModeltoXml(newEntry)).IgnoreArguments().Return("test").Repeat.Any();
//the class under test is successfully returning 'hero' when this method is called.
supportMethods.Stub(x => x.mytest(Arg<string>.Is.Anything)).Return("hero");
//If I use this line and debug test9 is set with my return value of "test".
//However in the same run my class under test the method just returns null.
var test9 = supportMethods.ModeltoXml(newEntry);
var testObject = new MyApi().NewTicket(newEntry, referrer, supportMethods, stubbedConfigMan);
上面的例子表明,将我的模拟/存根对象传递给我的被测试类时,ModeltoXml存根发生了一些变化。
终于把这个排序好了。我有一种感觉,这个问题与我在ModeltoXml方法中使用泛型有关。我只是在我的ModeltoXml存根中使用了Arg属性,它解决了这个问题:
supportMethods.Expect(x => x.ModeltoXml(Arg<Model1>.Is.Anything)).Return("Model XML response");
这次我还使用了. expect,这样我就可以断言该方法被调用了,但它仍然可以与。stub一起工作。