Mocking SPServer.Local
本文关键字:Local SPServer Mocking | 更新日期: 2023-09-27 18:05:47
我希望能够模拟由SPServer.Local
返回的对象,但我似乎无法在typemock中做到这一点。在调试时,我看到SPServer.Local
返回SPServer类型的空对象。typemmock不应该用我的伪实例替换这个实例吗?我做错了什么吗?该代码在sharepoint服务器上运行良好。
[TestInitialize]
public void Setup()
{
fakeSite = Isolate.Fake.Instance<SPSite>(Members.ReturnRecursiveFakes);
Isolate.Swap.NextInstance<SPSite>().With(fakeSite);
fakeServer = Isolate.Fake.Instance<SPServer>(Members.ReturnRecursiveFakes);
Isolate.Swap.NextInstance<SPServer>().With(fakeServer);
sharePointStorageRepository = new SharePointStorageRepository();
}
[TestMethod]
[Isolated]
public void CreateHRFolderMethodCreatesHRFolder()
{
// arrange
// some arrange logic here
// act
var actual = sharePointStorageRepository.Create();
// assert
Assert.AreEqual(expected, actual);
}
这是正在运行的代码位:
internal static Guid GetSiteGuid(string serverRelativeUrl, string webApplicationName)
{
Guid? guid = null;
SPServer myServer = SPServer.Local;
foreach (var serviceInstance in myServer.ServiceInstances.Where(si => si.Service is SPWebService)){
var service = (SPWebService) serviceInstance.Service;
var webapp = service.WebApplications.SingleOrDefault(wa => wa.DisplayName == webApplicationName);
if (webapp != null){
var site = webapp.Sites.SingleOrDefault(wa => wa.ServerRelativeUrl == serverRelativeUrl);
if (site != null) guid = site.ID;
}
}
if (!guid.HasValue){
throw new FileNotFoundException(
String.Format(
"Cannot find Site Collection with WebApplication '"{1}'" and ServerRelativeUrl '"{2}'" running on '"{0}'"",
myServer.Address, webApplicationName, serverRelativeUrl));
}
return guid.Value;
}
谢谢!
我没有在SharePoint中工作,但是我注意到:您实际上并没有嘲笑SPServer的返回。当地的任何地方。我认为这是缺失的一步。我也不完全确定你需要SwapNextInstance,因为我没有看到实际创建SPServer对象的任何地方。
这将改变你的测试代码为:
[TestInitialize]
public void Setup()
{
// I don't see where you're using SPSite, so I assume it's in code
// not being shown; otherwise you can remove this.
fakeSite = Isolate.Fake.Instance<SPSite>(Members.ReturnRecursiveFakes);
Isolate.Swap.NextInstance<SPSite>().With(fakeSite);
fakeServer = Isolate.Fake.Instance<SPServer>(Members.ReturnRecursiveFakes);
// INSTEAD OF THIS: Isolate.Swap.NextInstance<SPServer>().With(fakeServer);
// DO THIS:
Isolate.WhenCalled(() => SPServer.Local).WillReturn(fakeServer);
sharePointStorageRepository = new SharePointStorageRepository();
}
WhenCalled方法将意味着任何时候任何人请求SPServer。本地的,它会返回你的伪实例。
注意,我在测试的代码中看到您获得了ServerInstances属性。我没有看到设置任何特定的返回值,所以我假设您正在控制省略的"arrange"逻辑中的其余内容。