本文整理汇总了C#中PrivateObject.SetFieldOrProperty方法的典型用法代码示例。如果您正苦于以下问题:C# PrivateObject.SetFieldOrProperty方法的具体用法?C# PrivateObject.SetFieldOrProperty怎么用?C# PrivateObject.SetFieldOrProperty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PrivateObject
的用法示例。
在下文中一共展示了PrivateObject.SetFieldOrProperty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: test
static void test()
{
Class1.Item a = new Class1.Item();
Type t = typeof(Class1);
Type tinner = t.GetNestedType("Item", BindingFlags.NonPublic);
PrivateObject o = new PrivateObject(tinner);
o.SetFieldOrProperty("ID", "12345");
PrivateObject class1 = new PrivateObject(typeof(Class1));
dynamic list = (List<dynamic>)class1.GetFieldOrProperty("itemList");
list.Add(o.Target);
Console.WriteLine(class1.GetFieldOrProperty("GetFromListID"));
}
示例2: FreshenMailBoxTest
public void FreshenMailBoxTest()
{
//setup private object
var pvt = new PrivateObject(_imapMailBox);
pvt.SetFieldOrProperty("_imapWorker", _worker.Object);
//* start the freshen *//
var result = (Task<bool>)pvt.Invoke("FreshenMailBox");
_worker.Verify(x => x.FreshenMailBox(It.IsAny<string>()));
Assert.IsTrue(result.Result);
Assert.IsFalse((bool) pvt.GetFieldOrProperty("Freshening"));
}
示例3: TestMethod2
public void TestMethod2()
{
var t1 = DateTime.Now;
var t2 = DateTime.Now.AddDays(-1);
var emptyBook = new BookOrganizer.Book();
var model = new AddBookViewModel(emptyBook);
Book resBookManual = new Book()
{
Annotation = "Аннотация",
Comment = "Комментарий",
FinishTime = t1,
StartTime = t2,
Title = "Название",
Pages = 100,
Mark = 10,
Year = 2016
};
model.Annotation = "Аннотация";
model.Comment = "Комментарий";
model.FinishTime = t1;
model.StartTime = t2;
model.Title = "Название";
model.Pages = 100;
model.Mark = 10;
model.Year = 2016;
var privateModel = new PrivateObject(model);
var t = (privateModel.GetFieldOrProperty("book")) as Book;
Assert.AreEqual(resBookManual, t);
model.Author = "Пушкин А.С.";
model.Genre = "Классика";
resBookManual.Author = new Author() { Name = "Пушкин А.С." };
resBookManual.Genre = new Genre() { Name = "Классика" };
model.BookOut += (a) => { Assert.AreNotEqual(a, resBookManual); Assert.AreNotEqual(((Book)a).Author.Id, resBookManual.Author.Id); Assert.AreNotEqual(((Book)a).Genre.Id, resBookManual.Genre.Id); };
model.SubmitCommand.Execute(null);
var bookAutoCreatedButWithManualAuthorAndGenre = (privateModel.GetFieldOrProperty("book")) as Book;
bookAutoCreatedButWithManualAuthorAndGenre.Author = new Author() { Name = "Пушкин А.С.", Id = 0 };
bookAutoCreatedButWithManualAuthorAndGenre.Genre = new Genre() { Name = "Классика", Id = 0 };
privateModel.SetFieldOrProperty("book", bookAutoCreatedButWithManualAuthorAndGenre);
t = privateModel.GetFieldOrProperty("book") as Book;
Assert.AreEqual(resBookManual, t);
}
示例4: DisposeTest
public void DisposeTest()
{
var serviceProvider = new MockServiceProvider();
var mockSolutionEvents = new Mock<IVsSolutionEvents>();
uint cookie = 0;
((IVsSolution)serviceProvider.GetService(typeof(SVsSolution))).AdviseSolutionEvents(mockSolutionEvents.Instance as IVsSolutionEvents, out cookie);
Debug.Assert(cookie == 1);
SolutionListener target = new SolutionListener(serviceProvider);
PrivateObject solutionListner = new PrivateObject(target, new PrivateType(typeof(SolutionListener)));
solutionListner.SetFieldOrProperty("eventsCookie", cookie);
target.Dispose();
uint expected = 0;
Assert.AreEqual(expected, solutionListner.GetFieldOrProperty("eventsCookie"), "Dispose does not remove the event sink");
}
示例5: FreshenMailBoxTestWithException
public void FreshenMailBoxTestWithException()
{
//setup fake imapworker
var _configuration = new Mock<ImapClientConfiguration>();
//mock client
var client = new Mock<IImapClient>();
//mock inbox folder
var inbox = new Mock<IMailFolder>();
//client returns mock inbox
client.Setup(x => x.Inbox).Returns(inbox.Object);
//mock factory
factory = new Mock<IImapFactory>();
factory.Setup(x => x.GetClient()).ReturnsAsync(client.Object);
//create the idler and start setup
var _imapWorker = new ImapWorker(factory.Object);
//setup private object
var pvt = new PrivateObject(_imapMailBox);
pvt.SetFieldOrProperty("_imapWorker", _imapWorker);
var r = new ImapCommandResponse();
//first fetch throws exception - after closing and opening folders now messages are returned
//this mirrors how the client has been functioning in real world tests
inbox.Setup(x => x.FetchAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<MessageSummaryItems>(),
It.IsAny<CancellationToken>()))
.ThrowsAsync(new ImapCommandException(r,
"The IMAP server replied to the 'FETCH' command with a 'NO' response."));
//* start the freshen *//
var result = (Task<bool>)pvt.Invoke("FreshenMailBox");
Assert.IsFalse(result.Result);
factory.Verify(x => x.GetClient(), Times.Exactly(2));
}
示例6: InitializeTest
public void InitializeTest()
{
var serviceProvider = new MockServiceProvider();
SolutionListener target = new SolutionListener(serviceProvider);
uint expected = 0;
PrivateObject solutionListner = new PrivateObject(target, new PrivateType(typeof(SolutionListener)));
Assert.AreEqual(expected, solutionListner.GetFieldOrProperty("eventsCookie"));
expected = 1;
solutionListner.SetFieldOrProperty("eventsCookie", expected);
target.Initialize();
Assert.AreEqual(expected, solutionListner.GetFieldOrProperty("eventsCookie"));
}
示例7: DisposeTest
public void DisposeTest()
{
try
{
var serviceProvider = new MockServiceProvider();
var mockUpdateSolutionEvents = new Mock<IVsUpdateSolutionEvents>();
UpdateSolutionListener target = new UpdateSolutionListener(serviceProvider);
uint cookie = 0;
((IVsSolutionBuildManager)serviceProvider.GetService(typeof(SVsSolutionBuildManager))).AdviseUpdateSolutionEvents(mockUpdateSolutionEvents.Instance as IVsUpdateSolutionEvents, out cookie);
Debug.Assert(cookie == 1);
bool disposing = true;
PrivateObject updateSolutionListner = new PrivateObject(target, new PrivateType(typeof(UpdateSolutionListener)));
updateSolutionListner.SetFieldOrProperty("eventsCookie", cookie);
updateSolutionListner.Invoke("Dispose", disposing);
}
catch (Exception ex)
{
// Use try catch to test a workaround on CI build (AppVeyor)
Console.WriteLine(ex.Message);
}
}
示例8: DisposeTest
public void DisposeTest()
{
var serviceProvider = new MockServiceProvider();
var mockUpdateSolutionEvents = new Mock<IVsUpdateSolutionEvents>();
UpdateSolutionListener target = new UpdateSolutionListener(serviceProvider);
uint cookie = 0;
((IVsSolutionBuildManager)serviceProvider.GetService(typeof(SVsSolutionBuildManager))).AdviseUpdateSolutionEvents(mockUpdateSolutionEvents.Instance as IVsUpdateSolutionEvents, out cookie);
Debug.Assert(cookie == 1);
bool disposing = true;
PrivateObject updateSolutionListner = new PrivateObject(target, new PrivateType(typeof(UpdateSolutionListener)));
updateSolutionListner.SetFieldOrProperty("eventsCookie", cookie);
updateSolutionListner.Invoke("Dispose", disposing);
}
示例9: GivenHasAScheduleOf
public void GivenHasAScheduleOf(string scheduleName, Table table)
{
AppSettings.LocalHost = "http://localhost:3142";
SchedulerViewModel scheduler = new SchedulerViewModel(EventPublishers.Aggregator, new DirectoryObjectPickerDialog(), new PopupController(), new AsyncWorker(), new Mock<IConnectControlViewModel>().Object);
IEnvironmentModel environmentModel = EnvironmentRepository.Instance.Source;
environmentModel.Connect();
scheduler.ScheduledResourceModel = new ClientScheduledResourceModel(environmentModel);
scheduler.CurrentEnvironment = environmentModel;
scheduler.CreateNewTask();
scheduler.SelectedTask.Name = ScenarioContext.Current["ScheduleName"].ToString();
scheduler.SelectedTask.OldName = "bob";
scheduler.SelectedTask.UserName = ScenarioContext.Current["UserName"].ToString();
scheduler.SelectedTask.Password = ScenarioContext.Current["Password"].ToString();
scheduler.SelectedTask.WorkflowName = ScenarioContext.Current["WorkFlow"].ToString();
scheduler.SelectedTask.NumberOfHistoryToKeep = (int)ScenarioContext.Current["HistoryCount"];
scheduler.SelectedTask.Status = (SchedulerStatus)ScenarioContext.Current["TaskStatus"];
scheduler.Errors.ClearErrors();
var task = scheduler.SelectedTask;
UpdateTrigger(task, table);
PrivateObject po = new PrivateObject(scheduler.CurrentEnvironment);
var mockAuth = new Mock<IAuthorizationService>();
mockAuth.Setup(a => a.IsAuthorized(It.IsAny<AuthorizationContext>(), null)).Returns(true);
po.SetFieldOrProperty("AuthorizationService", mockAuth.Object);
ScenarioContext.Current["Scheduler"] = scheduler;
try
{
scheduler.SaveCommand.Execute("");
}
catch(Exception e)
{
ScenarioContext.Current["Error"] = e.Message;
}
}
示例10: FieldValidation_PasswordHistory
public void FieldValidation_PasswordHistory()
{
var userCt = ContentType.GetByName("User");
var passwordFieldSetting = userCt.FieldSettings.Where(f => f.Name == "Password").First() as PasswordFieldSetting;
var passwordFieldSettingAcc = new PrivateObject(passwordFieldSetting);
var originalPasswordHistoryLength = passwordFieldSettingAcc.GetFieldOrProperty("_passwordHistoryLength") as int?;
var userName = "FieldValidation_PasswordHistory_User";
var domainPath = "/Root/IMS/BuiltIn";
var userPath = RepositoryPath.Combine(domainPath, userName);
var domainNode = Node.LoadNode(domainPath);
var user = Content.Load(userPath);
if (user == null)
{
user = Content.CreateNew("User", domainNode, userName);
user["Password"] = "asdf";
user.Save();
}
try
{
passwordFieldSetting.PasswordHistoryLength = 0;
user = Content.Load(userPath);
user["Password"] = "asdf";
user.Save();
user = Content.Load(userPath);
user["Password"] = "asdf";
user.Save();
passwordFieldSetting.PasswordHistoryLength = 1;
user = Content.Load(userPath);
user["Password"] = "asdf1";
user.Save();
user = Content.Load(userPath);
user["Password"] = "asdf";
user.Save();
var thrown = false;
try
{
user = Content.Load(userPath);
user["Password"] = "asdf";
user.Save();
}
catch (Exception e)
{
thrown = true;
}
Assert.IsTrue(thrown, "#1");
}
catch (Exception e)
{
throw;
}
finally
{
passwordFieldSettingAcc.SetFieldOrProperty("_passwordHistoryLength", originalPasswordHistoryLength);
}
}
示例11: ExplicitCastTest
public void ExplicitCastTest()
{
try {
// Create the Kinect Object
JointCollection kinectCollection = (JointCollection)FormatterServices.GetSafeUninitializedObject(typeof(JointCollection));
PrivateObject po = new PrivateObject(kinectCollection);
po.SetFieldOrProperty("_skeletonData", new Joint[20]);
// Set some Joints
// JointType is readonly hence the FUBAR way of doing this...
po = new PrivateObject(new Joint());
po.SetFieldOrProperty("JointType", JointType.AnkleLeft);
po.SetFieldOrProperty("TrackingState", JointTrackingState.Inferred);
kinectCollection[JointType.AnkleLeft] = (Joint)po.Target;
po = new PrivateObject(new Joint());
po.SetFieldOrProperty("JointType", JointType.AnkleRight);
po.SetFieldOrProperty("TrackingState", JointTrackingState.NotTracked);
kinectCollection[JointType.AnkleRight] = (Joint)po.Target;
po = new PrivateObject(new Joint());
po.SetFieldOrProperty("JointType", JointType.ElbowLeft);
po.SetFieldOrProperty("TrackingState", JointTrackingState.Tracked);
kinectCollection[JointType.ElbowLeft] = (Joint)po.Target;
po = new PrivateObject(new Joint());
po.SetFieldOrProperty("JointType", JointType.ElbowRight);
po.SetFieldOrProperty("TrackingState", JointTrackingState.NotTracked);
kinectCollection[JointType.ElbowRight] = (Joint)po.Target;
// Create the Iava equivalent
IavaJointCollection iavaCollection = new IavaJointCollection();
iavaCollection[IavaJointType.AnkleLeft] = new IavaJoint() { JointType = IavaJointType.AnkleLeft, TrackingState = IavaJointTrackingState.Inferred };
iavaCollection[IavaJointType.AnkleRight] = new IavaJoint() { JointType = IavaJointType.AnkleRight, TrackingState = IavaJointTrackingState.NotTracked };
iavaCollection[IavaJointType.ElbowLeft] = new IavaJoint() { JointType = IavaJointType.ElbowLeft, TrackingState = IavaJointTrackingState.Tracked };
iavaCollection[IavaJointType.ElbowRight] = new IavaJoint() { JointType = IavaJointType.ElbowRight, TrackingState = IavaJointTrackingState.NotTracked };
// Test object as a whole
Assert.AreEqual(iavaCollection, (IavaJointCollection)kinectCollection);
// Set the Kinect Object to null
kinectCollection = null;
// Make sure we don't attempt to cast nulls
Assert.IsNull((IavaJointCollection)kinectCollection);
}
catch (Exception ex) {
Assert.Fail(ex.Message);
}
}
示例12: OnNavigateToDocNotInProjectTest
public void OnNavigateToDocNotInProjectTest()
{
var mockDocumentEnumerator = new SequenceMock<IEnumerator>();
var mockDte = new Mock<DTE>();
var mockDocuments = new Mock<Documents>();
var mockDocument = new SequenceMock<Document>();
var mockActiveDocument = new Mock<Document>();
var mockTextSelection = new SequenceMock<TextSelection>();
var mockVirtualPoint = new SequenceMock<VirtualPoint>();
this.SetupProjectUtilities(mockDocumentEnumerator, mockDte, mockDocuments, mockDocument, mockActiveDocument, "DummyFile.txt");
var mockSecondDocument = new SequenceMock<Document>();
mockDocumentEnumerator.AddExpectationExpr(docs => docs.MoveNext(), true);
mockDocumentEnumerator.AddExpectationExpr(docs => docs.Current, mockSecondDocument.Instance);
mockDocumentEnumerator.AddExpectationExpr(docs => docs.MoveNext(), false);
mockSecondDocument.AddExpectationExpr(doc => doc.FullName, "DummyFile.txt");
AnalysisHelper analysisHelper = this.SetCoreNoUI();
bool eventFired = false;
PrivateObject actual = new PrivateObject(this.package, new PrivateType(typeof(StyleCopVSPackage)));
actual.SetFieldOrProperty("core", this.package.Core);
// Register output generated event to test event fired
this.package.Core.OutputGenerated += (sender, args) => { eventFired = true; };
mockActiveDocument.ImplementExpr(doc => doc.Selection, mockTextSelection.Instance);
mockTextSelection.ImplementExpr(sel => sel.GotoLine(this.violation.LineNumber, true));
mockTextSelection.ImplementExpr(sel => sel.ActivePoint, mockVirtualPoint.Instance);
mockVirtualPoint.ImplementExpr(vp => vp.TryToShow(EnvDTE.vsPaneShowHow.vsPaneShowCentered, 0));
this.mockServiceProvider.ImplementExpr(sp => sp.GetService(typeof(EnvDTE.DTE)), mockDte.Instance);
// Use private type to set static private field
PrivateType privateProjectUtilities = new PrivateType(typeof(ProjectUtilities));
privateProjectUtilities.SetStaticFieldOrProperty("serviceProvider", this.mockServiceProvider.Instance);
// Execute
PrivateObject taskUnderTestPrivateObject = new PrivateObject(this.taskUnderTest, new PrivateType(typeof(ViolationTask)));
taskUnderTestPrivateObject.Invoke("OnNavigate", EventArgs.Empty);
// Verify the required methods are called to show the violation
mockTextSelection.Verify();
mockVirtualPoint.Verify();
mockDocument.Verify();
Assert.IsTrue(eventFired, "Core did not fire output event");
}
示例13: OnNavigateNoDocumentTest
public void OnNavigateNoDocumentTest()
{
bool eventFired = false;
Mock<DTE> mockDte = new Mock<DTE>();
// No UI for test
AnalysisHelper analysisHelper = this.SetCoreNoUI();
PrivateObject actual = new PrivateObject(this.package, new PrivateType(typeof(StyleCopVSPackage)));
actual.SetFieldOrProperty("core", this.package.Core);
// Register output generated event to test event fired
this.package.Core.OutputGenerated += (sender, args) => { eventFired = true; };
// Does nothing - included for code coverage and to catch it if it starts doing something unexpectedly
Assert.IsNotNull(this.taskUnderTestShell, "this.taskUnderTestShell is null.");
this.taskUnderTestShell.Document = null;
// Use private type to set static private field
PrivateType privateProjectUtilities = new PrivateType(typeof(ProjectUtilities));
privateProjectUtilities.SetStaticFieldOrProperty("serviceProvider", this.mockServiceProvider.Instance);
PrivateObject taskUnderTestPrivateObject = new PrivateObject(this.taskUnderTest, new PrivateType(typeof(ViolationTask)));
taskUnderTestPrivateObject.Invoke("OnNavigate", EventArgs.Empty);
Assert.IsTrue(eventFired, "Core did not fire output event");
}
示例14: ExplicitCastTest
public void ExplicitCastTest()
{
try {
// Create the Kinect object
Joint kinectJoint = new Joint();
PrivateObject po = new PrivateObject(kinectJoint);
// Set the read only fields
po.SetFieldOrProperty("JointType", JointType.ElbowLeft);
po.SetFieldOrProperty("TrackingState", JointTrackingState.Inferred);
// Cast the PrivateObject back to its Kinect equivalent
kinectJoint = (Joint)po.Target;
// Create the Iava Equivalent
IavaJoint iavaJoint = new IavaJoint();
iavaJoint.JointType = IavaJointType.ElbowLeft;
iavaJoint.TrackingState = IavaJointTrackingState.Inferred;
// Test object as a whole
Assert.AreEqual(iavaJoint, (IavaJoint)kinectJoint);
}
catch (Exception ex) {
Assert.Fail(ex.Message);
}
}
示例15: CreateSkeletonFrame
/// <summary>
/// Handles the job of initializing a SkeletonFrame that can be used by the Unit Tests
/// </summary>
/// <returns></returns>
SkeletonFrame CreateSkeletonFrame()
{
// Get an uninitialized version of the SkeletonFrame
SkeletonFrame kinectFrame = (SkeletonFrame)FormatterServices.GetSafeUninitializedObject(typeof(SkeletonFrame));
// Find the Assembly containing the EntryPrivate object
Assembly kinect = Assembly.Load("Microsoft.Kinect, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
Type entryType = kinect.GetType("Microsoft.Kinect.DataPool`4+EntryPrivate");
// Set the generic types to the actual types needed by the SkeletonFrame
entryType = entryType.MakeGenericType(typeof(int), typeof(Tuple<float, float, float, float>), typeof(object), typeof(Skeleton[]));
// Create an EntryPrivate object
object entry = entryType.GetConstructor(new Type[] { }).Invoke(new object[] { });
// Create an Array of skeletons so we can set it as one of the Entry properties
Skeleton[] skeletons = new Skeleton[] { new Skeleton(), new Skeleton(), new Skeleton(),
new Skeleton(), new Skeleton(), new Skeleton() };
// Set the EntryPrivate properties
PropertyInfo[] prop = entry.GetType().GetProperties();
prop[3].SetValue(entry, 0, null); // Key
prop[4].SetValue(entry, new Tuple<float, float, float, float>(0, 0, 0, 0), null); // Value1
prop[5].SetValue(entry, null, null); // Value2
prop[6].SetValue(entry, skeletons, null); // Value3
// Set the kinectFrame properties
prop = kinectFrame.GetType().GetProperties();
prop[0].SetValue(kinectFrame, 123456789, null); // Timestamp
prop[1].SetValue(kinectFrame, 31, null); // FrameNumber
prop[2].SetValue(kinectFrame, Tuple.Create(1.0f, 2.0f, 3.0f, 4.0f), null); // FloorClipPlane
//prop[3].SetValue(kinectFrame, 0, null); // SkeletonArrayLength
// Set the private fields on the kinectFrame
PrivateObject po = new PrivateObject(kinectFrame);
po.SetFieldOrProperty("_skeletonData", entry);
po.SetFieldOrProperty("_dataAccessLock", new object());
// Return the SkeletonFrame
return(SkeletonFrame)po.Target;
}