我声明了以下类和构造函数:
public class StoryProvider : ReportProviderBase<StoryProvider>, IStoryProvider
{
public StoryProvider(ICommonComponents<StoryProvider> common)
: base(common)
{
Common.Logger.LogTrace("Instantiating StoryProvider");
}
public StoryProvider(ICommonComponents<StoryProvider> common, IEvalReports reports)
: base(common)
{
Reports = reports;
Common.Logger.LogTrace("Instantiating StoryProvider");
}……
基类具有以下声明:
public abstract class ReportProviderBase<T> : IDisposable
where T : class
{
public IEvalReports Reports { get; set; }
protected ICommonComponents<T> Common { get; }
protected ReportProviderBase(ICommonComponents<T> common)
{
Common = common;
CreateProfileServerComInstance();
}…..
使用N代替我声明:
ICommonComponents<StoryProvider> common = GetCommonComponents<StoryProvider>();
var reports = Substitute.For<IEvalReports>();
现在,如果我使用以下方法调用我的测试方法:
var provider = await Substitute.For<StoryProvider>(common).HeadlineNewsContentAsync(request);
它在HeadlineNewsContentAsync
中失败,因为尚未实例化报告。
我真的很想使用重载的构造函数来调用它:
var provider = await Substitute.For<StoryProvider>(common, reports).HeadlineNewsContentAsync(request);
这时,它崩溃了,没有找到TestInvoker.cs。显然,我以错误的方式附加了reports
,我该如何更改对此方法的调用,以便它将使用重载的构造函数
这是被测函数:
public HeadlineStoriesResponse HeadlineNewsContent(FrontPageContentRequest request)
{
EnsureConnectedToProfileServer(request.SessionId);
var requestXml = request.XSerialise();
var success = Reports.FrontPageOperation(requestXml, out var responseXml);
if (!success || string.IsNullOrEmpty(responseXml) || responseXml.Contains("<FRONTPAGE_CONTENT/>"))
return new HeadlineStoriesResponse { IsSuccess = false };
var xml = responseXml.GetNodeFromXmlString("FRONTPAGE_CONTENT//HEADLINE_STORIES");
var stories = xml.XDeserialise<HeadlineStoriesResponse>();
stories.IsSuccess = true;
return stories;
}
答案 0 :(得分:1)
通常,在测试时不会嘲笑被测对象。
创建被测对象的实例并注入模拟的依赖项。
//Arrange
//...
ICommonComponents<StoryProvider> common = GetCommonComponents<StoryProvider>();
var reports = Substitute.For<IEvalReports>();
var provider = new StoryProvider(common, reports);
//Act
var actual = await provider.HeadlineNewsContentAsync(request);
//Assert
//...