-
Notifications
You must be signed in to change notification settings - Fork 0
Code Snippets
Sandesh Kota edited this page Jun 27, 2019
·
13 revisions
- Thread Sleep v/s SpinWait
Thread.Sleep(500);
Thread.SpinWait(500); // To keep the process in thread active rather than releasing it for another thread to execute
- Time Measurment
var start = System.Environment.TickCount;
// code
var stop = System.Environment.TickCount;
var elapsedTimeInSeconds = (stop - start) / 1000.0;
- For Exceptions
[TestMethod]
[ExpectedException(typeof(ArgumentException), "A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}
- Multiple Data set
[Isolated]
[Test]
[TestCase(5)]
[TestCase(10)]
public void GetPeriodicityTest(int days)
{
// test code
}
- Testing private Method
MyObject objUnderTest = new MyObject();
MethodInfo methodInfo = typeof(MyObject).GetMethod("SomePrivateMethod", BindingFlags.NonPublic | BindingFlags.Instance);
object[] parameters = {"parameters here"};
methodInfo.Invoke(objUnderTest, parameters);
- Testing Private Static Method
int days = 10;
string periodicity = "Invalid";
var privateTypeObject = new PrivateType(typeof(Employee));
object[] parameters = { days };
var actualPeriodicity = (string)privateTypeObject.InvokeStatic("GetPeriodicity", parameters);
actualPeriodicity.Should().Be(periodicity);
- Nuget package Microsoft.CodeAnalysis.CSharp
\\ A code.cs file has class "Greeter" and method "SayHello"
var code = File.readAllText("code.cs");
var tree = SyntaxFactory.ParseSyntaxTree(code);
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var reference = new MetadataFileReference(typeof(object).Assembly.Location)
var compilation = CSharpCompilation.Create("test").WithOptions(options).AddSyntaxTrees(tree).AddReferences(reference);
var diagnostics = compilation.GetDiagnostics();
foreach (var diagnostic in diagnostics )
{
System.Console.WriteLine(diagnostic.ToString());
}
using stream(var stream = new MemoryStream())
{
compilation.Emit(stream);
var assembly = Assembly.Load(stream.GetBuffer());
var type = assembly.GetType("Greeter");
var greeter = Activator.CreateInstance(type);
var method = type.GetMethod("SayHello");
method.Invoke(greeter, null);
}