本文整理汇总了C#中Mock.SetupGet方法的典型用法代码示例。如果您正苦于以下问题:C# Mock.SetupGet方法的具体用法?C# Mock.SetupGet怎么用?C# Mock.SetupGet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mock
的用法示例。
在下文中一共展示了Mock.SetupGet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetConfiguration
private IAppConfiguration GetConfiguration()
{
var mockConfiguration = new Mock<IAppConfiguration>();
mockConfiguration.SetupGet(c => c.ServiceDiscoveryUri).Returns(new Uri("https://api.nuget.org/v3/index.json"));
mockConfiguration.SetupGet(c => c.AutocompleteServiceResourceType).Returns("SearchAutocompleteService/3.0.0-rc");
return mockConfiguration.Object;
}
示例2: Start_WhenInputFormatIsValidAddToShoppingCartCommand_ShouldAddProductToTheShoppingCart
public void Start_WhenInputFormatIsValidAddToShoppingCartCommand_ShouldAddProductToTheShoppingCart()
{
//Arrange
var productName = "Fa Shampoo";
var mockedFactory = new Mock<ICosmeticsFactory>();
var mockedShoppingCart = new Mock<IShoppingCart>();
var mockedCommandParser = new Mock<ICommandParser>();
var mockedCommand = new Mock<ICommand>();
var mockedProduct = new Mock<IProduct>();
mockedCommand.SetupGet(x => x.Name).Returns("AddToShoppingCart");
mockedCommand.SetupGet(x => x.Parameters).Returns(new List<string>() { productName });
mockedCommandParser.Setup(p => p.ReadCommands()).Returns(() => new List<ICommand>() { mockedCommand.Object });
var engine = new MockedCosmeticsEngine(mockedFactory.Object, mockedShoppingCart.Object, mockedCommandParser.Object);
engine.Products.Add(productName, mockedProduct.Object);
//Act
engine.Start();
//Assert
mockedShoppingCart.Verify(x => x.AddProduct(mockedProduct.Object), Times.Once);
}
示例3: TestAddingRecordingDeviceToSelected
public void TestAddingRecordingDeviceToSelected()
{
var configurationMoq = new Mock<ISoundSwitchConfiguration> {Name = "Configuration mock"};
var audioMoqI = new Mock<IAudioDevice> {Name = "first audio dev"};
audioMoqI.SetupGet(a => a.FriendlyName).Returns("Speakers (Test device)");
audioMoqI.SetupGet(a => a.Type).Returns(AudioDeviceType.Recording);
//Setup
configurationMoq.Setup(c => c.SelectedRecordingDeviceList).Returns(new HashSet<string>());
TestHelpers.SetConfigurationMoq(configurationMoq);
//Action
var eventCalled = false;
AppModel.Instance.SelectedDeviceChanged += (sender, changed) => eventCalled = true;
Assert.True(AppModel.Instance.SelectDevice(audioMoqI.Object));
//Asserts
configurationMoq.VerifyGet(c => c.SelectedRecordingDeviceList);
configurationMoq.Verify(c => c.Save());
audioMoqI.VerifyGet(a => a.FriendlyName);
audioMoqI.VerifyGet(a => a.Type);
Assert.That(configurationMoq.Object.SelectedRecordingDeviceList.Count == 1);
Assert.That(configurationMoq.Object.SelectedRecordingDeviceList.Contains("Speakers (Test device)"));
Assert.That(eventCalled, "SelectedDeviceChanged not called");
}
示例4: GetSelectionWithCaretPos
Selection GetSelectionWithCaretPos (int row, int column)
{
var documentMock = new Mock<ICaret>();
documentMock.SetupGet(o => o.Row).Returns(row);
documentMock.SetupGet(o => o.Column).Returns(column);
return new Selection(documentMock.Object);
}
开发者ID:transformersprimeabcxyz,项目名称:_TO-DO-CodeEditor-Unity-Technologies,代码行数:7,代码来源:SelectionTest.cs
示例5: CommandMarginControllerTest
protected CommandMarginControllerTest()
{
_factory = new MockRepository(MockBehavior.Strict);
_marginControl = new CommandMarginControl();
_marginControl.CommandLineTextBox.Text = String.Empty;
_search = _factory.Create<IIncrementalSearch>();
_search.SetupGet(x => x.InSearch).Returns(false);
_search.SetupGet(x => x.InPasteWait).Returns(false);
_vimBuffer = new MockVimBuffer();
_vimBuffer.IncrementalSearchImpl = _search.Object;
_vimBuffer.VimImpl = MockObjectFactory.CreateVim(factory: _factory).Object;
_vimBuffer.CommandModeImpl = _factory.Create<ICommandMode>(MockBehavior.Loose).Object;
var textBuffer = CreateTextBuffer(new []{""});
_vimBuffer.TextViewImpl = TextEditorFactoryService.CreateTextView(textBuffer);
Mock<IVimGlobalSettings> globalSettings = new Mock<IVimGlobalSettings>();
_vimBuffer.GlobalSettingsImpl = globalSettings.Object;
var editorFormatMap = _factory.Create<IEditorFormatMap>(MockBehavior.Loose);
editorFormatMap.Setup(x => x.GetProperties(It.IsAny<string>())).Returns(new ResourceDictionary());
var parentVisualElement = _factory.Create<FrameworkElement>();
_controller = new CommandMarginController(
_vimBuffer,
parentVisualElement.Object,
_marginControl,
VimEditorHost.EditorFormatMapService.GetEditorFormatMap(_vimBuffer.TextView),
VimEditorHost.ClassificationFormatMapService.GetClassificationFormatMap(_vimBuffer.TextView));
}
示例6: TestQueryAsync_ServerReturnsQuery_ReturnsListWithFieldworkOffices
public void TestQueryAsync_ServerReturnsQuery_ReturnsListWithFieldworkOffices()
{
const HttpStatusCode httpStatusCode = HttpStatusCode.NotFound;
var expectedFieldworkOffices = new FieldworkOffice[]
{ new FieldworkOffice{OfficeId = "TestOfficeId"},
new FieldworkOffice{OfficeId = "AnotherTestOfficeId"}
};
var mockedNfieldConnection = new Mock<INfieldConnectionClient>();
var mockedHttpClient = new Mock<INfieldHttpClient>();
mockedHttpClient
.Setup(client => client.GetAsync(ServiceAddress + "offices/"))
.Returns(
Task.Factory.StartNew(
() =>
new HttpResponseMessage(httpStatusCode)
{
Content = new StringContent(JsonConvert.SerializeObject(expectedFieldworkOffices))
}));
mockedNfieldConnection
.SetupGet(connection => connection.Client)
.Returns(mockedHttpClient.Object);
mockedNfieldConnection
.SetupGet(connection => connection.NfieldServerUri)
.Returns(new Uri(ServiceAddress));
var target = new NfieldFieldworkOfficesService();
target.InitializeNfieldConnection(mockedNfieldConnection.Object);
var actualFieldworkOffices = target.QueryAsync().Result;
Assert.Equal(expectedFieldworkOffices[0].OfficeId, actualFieldworkOffices.ToArray()[0].OfficeId);
Assert.Equal(expectedFieldworkOffices[1].OfficeId, actualFieldworkOffices.ToArray()[1].OfficeId);
Assert.Equal(2, actualFieldworkOffices.Count());
}
示例7: BindTest1
public void BindTest1()
{
var bindingToSyntax = new Mock<IBindingToSyntax<object>>(MockBehavior.Loose);
var bindingNamed = new Mock<IBindingWhenInNamedWithOrOnSyntax<object>>(MockBehavior.Loose);
var bInfo = new Mock<IBindInfo>(MockBehavior.Loose);
var scopeBinder = new Mock<IScopeBinder>(MockBehavior.Loose);
var scoped = new Mock<IBindingNamedWithOrOnSyntax<object>>(MockBehavior.Loose);
var typesFrom = new List<Type>();
var typeTo = typeof (string);
var bindingScope = new BindingScope("sdrjklgnlsdjkg");
bindingToSyntax.Name = "bindingToSyntax";
bindingNamed.Name = "bindingNamed";
bInfo.Name = "bInfo";
scopeBinder.Name = "scopeBinder";
scoped.Name = "scoped";
bInfo.SetupGet(x => x.From).Returns(typesFrom).Verifiable();
bInfo.SetupGet(x => x.To).Returns(typeTo).Verifiable();
bInfo.SetupGet(x => x.Scope).Returns(bindingScope).Verifiable();
bInfo.SetupGet(x => x.Name).Returns((string)null).Verifiable();
bindingNamed.Setup(x => x.GetHashCode()).Returns(100.GetHashCode()).Verifiable();
bindingNamed.Setup(x => x.ToString()).Returns("100").Verifiable();
scopeBinder.Setup(x => x.InScope(bindingNamed.Object, bindingScope)).Returns(scoped.Object).Verifiable();
bindingToSyntax.Setup(x => x.To(typeTo)).Returns(bindingNamed.Object).Verifiable();
new NinjectBinder(types => bindingToSyntax.Object, scopeBinder.Object).Bind(new[] {bInfo.Object});
}
示例8: AnErrorIsIssuedIfTheMainMethodIsNotImplementedAsANormalMethod
public void AnErrorIsIssuedIfTheMainMethodIsNotImplementedAsANormalMethod()
{
var type = CreateMockTypeDefinition("MyClass");
var main = new Mock<IMethod>(MockBehavior.Strict);
main.SetupGet(_ => _.DeclaringTypeDefinition).Returns(type);
main.SetupGet(_ => _.Name).Returns("Main");
main.SetupGet(_ => _.FullName).Returns("MyClass.Main");
main.SetupGet(_ => _.Parameters).Returns(EmptyList<IParameter>.Instance);
main.SetupGet(_ => _.Region).Returns(DomRegion.Empty);
var er = new MockErrorReporter();
Process(
new[] {
new JsClass(type, JsClass.ClassTypeEnum.Class, null, null, null) {
StaticMethods = { new JsMethod(main.Object, "$Main", new string[0], JsExpression.FunctionDefinition(new string[0], new JsExpressionStatement(JsExpression.Identifier("X")))) }
}
},
new MockScriptSharpMetadataImporter() { GetMethodSemantics = m => ReferenceEquals(m, main.Object) ? MethodScriptSemantics.InlineCode("X") : MethodScriptSemantics.NormalMethod("$" + m.Name) },
er,
main.Object
);
Assert.That(er.AllMessages, Has.Count.EqualTo(1));
Assert.That(er.AllMessages.Any(m => m.Code == 7801 && (string)m.Args[0] == "MyClass.Main"));
}
示例9: HandleTest
public void HandleTest()
{
string pageName = "search";
byte[] content = Encoding.UTF8.GetBytes("<html><body>Search me</body></html>");
MockResourceRepository resourceRepository = new MockResourceRepository();
resourceRepository.LoadResource(pageName, content);
HtmlPage target = new HtmlPage();
var request = new Mock<IServiceRequest>();
request.SetupGet(x => x.ResourceName).Returns(pageName);
request.SetupGet(x => x.Extension).Returns("");
request.SetupGet(x => x.Query).Returns("");
var response = new Mock<IServiceResponse>();
response.SetupProperty(x => x.ContentType);
response.SetupProperty(x => x.StatusCode);
MemoryStream contentStream = new MemoryStream();
response.SetupGet(x => x.ContentStream).Returns(contentStream);
target.Handle(request.Object, response.Object, resourceRepository);
Assert.AreEqual("text/html", response.Object.ContentType);
Assert.AreEqual(200, response.Object.StatusCode);
byte[] actualContent = contentStream.ToArray();
Assert.AreEqual(content.Length, actualContent.Length);
for (int i = 0; i < content.Length; i++)
{
Assert.AreEqual(content[i], actualContent[i]);
}
}
示例10: should_return_base_eneryg_plus_any_equiped_items_that_affect_energy
public void should_return_base_eneryg_plus_any_equiped_items_that_affect_energy()
{
Guid userId = Guid.NewGuid();
//given user that exists
_userRetriever.Setup(s => s.UserExists(userId)).Returns(true);
//and a base energy of 100
_userRetriever.Setup(s => s.GetCurrentBaseEnergy(userId)).Returns(100);
//and the following equipment, one of which is one time, one of which is not
List<IItem> items = new List<IItem>();
Mock<IItem> item = new Mock<IItem>();
item.SetupGet(s => s.Energy).Returns(20);
item.SetupGet(s => s.IsOneTimeUse).Returns(true);
items.Add(item.Object);
item = new Mock<IItem>();
item.SetupGet(s => s.Energy).Returns(10);
items.Add(item.Object);
_userItemRetriever.Setup(s => s.GetUserItems(userId)).Returns(items);
//should return 110 for base energy which excludes one time use
int energy = _userEnergyProvider.GetUserMaxEnergy(userId);
Assert.AreEqual(110, energy);
}
示例11: RequireHttpsAttributeRedirectsGetRequest
[InlineData(44300, "{0}:44300")] // Non-standard Port, Authenticated, always force SSL for this action
public void RequireHttpsAttributeRedirectsGetRequest(int port, string hostFormatter)
{
// Arrange
var mockAuthContext = new Mock<AuthorizationContext>(MockBehavior.Strict);
var mockConfig = new Mock<IAppConfiguration>();
var mockFormsAuth = new Mock<IFormsAuthenticationService>();
mockAuthContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("get");
mockAuthContext.SetupGet(c => c.HttpContext.Request.Url).Returns(new Uri("http://test.nuget.org/login"));
mockAuthContext.SetupGet(c => c.HttpContext.Request.RawUrl).Returns("/login");
mockAuthContext.SetupGet(c => c.HttpContext.Request.IsSecureConnection).Returns(false);
mockConfig.Setup(cfg => cfg.RequireSSL).Returns(true);
mockConfig.Setup(cfg => cfg.SSLPort).Returns(port);
var attribute = new RequireSslAttribute()
{
Configuration = mockConfig.Object
};
var result = new ViewResult();
var context = mockAuthContext.Object;
// Act
attribute.OnAuthorization(context);
// Assert
Assert.IsType<RedirectResult>(context.Result);
Assert.Equal("https://" + String.Format(hostFormatter, "test.nuget.org") + "/login", ((RedirectResult)context.Result).Url);
}
示例12: CheckUnlockStatus_EveryIAchievementConditionIsUnlocked_ShouldFireAchievementCompletedEvent
public void CheckUnlockStatus_EveryIAchievementConditionIsUnlocked_ShouldFireAchievementCompletedEvent()
{
// Arrange
Mock<IAchievementCondition> achievementConditionMock1 = new Mock<IAchievementCondition>();
achievementConditionMock1.SetupGet(x => x.Unlocked).Returns(true);
achievementConditionMock1.SetupGet(x => x.UniqueId).Returns("ac1");
Mock<IAchievementCondition> achievementConditionMock2 = new Mock<IAchievementCondition>();
achievementConditionMock2.SetupGet(x => x.Unlocked).Returns(true);
achievementConditionMock2.SetupGet(x => x.UniqueId).Returns("ac2");
Mock<IAchievementCondition> achievementConditionMock3 = new Mock<IAchievementCondition>();
achievementConditionMock3.SetupGet(x => x.Unlocked).Returns(true);
achievementConditionMock3.SetupGet(x => x.UniqueId).Returns("ac3");
List<IAchievementCondition> achievementConditions = new List<IAchievementCondition>
{
achievementConditionMock1.Object,
achievementConditionMock2.Object,
achievementConditionMock3.Object
};
Achievement achievement = new Achievement("uniqueId", "titel", "description", achievementConditions);
Achievement reportedAchievement = null;
achievement.AchievementCompleted += delegate(Achievement a) { reportedAchievement = a; };
// Act
achievement.CheckUnlockStatus();
// Assert
Assert.AreEqual(achievement, reportedAchievement);
Assert.IsTrue(achievement.Unlocked);
}
示例13: MiniDumpDeleteOnCloseTests
public void MiniDumpDeleteOnCloseTests()
{
// Arrange
var path = @"x:\temp\minidump.dmp";
var fileSystem = new Mock<IFileSystem>();
var file = new Mock<FileBase>();
var fileInfoFactory = new Mock<IFileInfoFactory>();
var fileInfo = new Mock<FileInfoBase>();
// Setup
fileSystem.SetupGet(fs => fs.File)
.Returns(file.Object);
fileSystem.SetupGet(fs => fs.FileInfo)
.Returns(fileInfoFactory.Object);
file.Setup(f => f.Exists(path))
.Returns(true);
file.Setup(f => f.OpenRead(path))
.Returns(() => new MemoryStream());
fileInfoFactory.Setup(f => f.FromFileName(path))
.Returns(() => fileInfo.Object);
fileInfo.Setup(f => f.Exists)
.Returns(true);
FileSystemHelpers.Instance = fileSystem.Object;
// Test
var stream = ProcessController.FileStreamWrapper.OpenRead(path);
stream.Close();
// Assert
fileInfo.Verify(f => f.Delete(), Times.Once());
}
示例14: SourceFileWithLayoutPageTest
public void SourceFileWithLayoutPageTest()
{
// Arrange
var pagePath = "~/MyApp/index.cshtml";
var layoutPath = "~/MyFiles/Layout.cshtml";
var layoutPage = "~/MyFiles/Layout.cshtml";
var content = "hello world";
var title = "MyPage";
var page = CreatePageWithLayout(
p =>
{
p.PageData["Title"] = title;
p.WriteLiteral(content);
},
p =>
{
p.WriteLiteral(p.PageData["Title"]);
p.Write(p.RenderBody());
}, pagePath, layoutPath, layoutPage);
var request = new Mock<HttpRequestBase>();
request.SetupGet(c => c.Path).Returns("/myapp/index.cshtml");
request.SetupGet(c => c.RawUrl).Returns("http://localhost:8080/index.cshtml");
request.SetupGet(c => c.IsLocal).Returns(true);
request.Setup(c => c.MapPath(It.IsAny<string>())).Returns<string>(c => c);
request.Setup(c => c.Browser.IsMobileDevice).Returns(false);
request.Setup(c => c.Cookies).Returns(new HttpCookieCollection());
var result = Utils.RenderWebPage(page, request: request.Object);
Assert.Equal(2, page.PageContext.SourceFiles.Count);
Assert.True(page.PageContext.SourceFiles.Contains("~/MyApp/index.cshtml"));
Assert.True(page.PageContext.SourceFiles.Contains("~/MyFiles/Layout.cshtml"));
}
示例15: RequireHttpsAttributeDoesNotThrowForInsecureConnectionIfNotAuthenticatedOrForcingSSLAndOnlyWhenAuthenticatedSet
public void RequireHttpsAttributeDoesNotThrowForInsecureConnectionIfNotAuthenticatedOrForcingSSLAndOnlyWhenAuthenticatedSet()
{
// Arrange
var mockAuthContext = new Mock<AuthorizationContext>(MockBehavior.Strict);
var mockConfig = new Mock<IAppConfiguration>();
var mockFormsAuth = new Mock<IFormsAuthenticationService>();
mockConfig.Setup(cfg => cfg.RequireSSL).Returns(true);
mockAuthContext.SetupGet(c => c.HttpContext.Request.IsSecureConnection).Returns(false);
mockAuthContext.SetupGet(c => c.HttpContext.Request.IsAuthenticated).Returns(false);
var context = mockAuthContext.Object;
mockFormsAuth.Setup(fas => fas.ShouldForceSSL(context.HttpContext)).Returns(false);
var attribute = new RequireRemoteHttpsAttribute()
{
Configuration = mockConfig.Object,
OnlyWhenAuthenticated = true,
FormsAuthentication = mockFormsAuth.Object
};
var result = new ViewResult();
context.Result = result;
// Act
attribute.OnAuthorization(context);
// Assert
Assert.Same(result, context.Result);
}