I want to write unit test for below class.
If name is other than "MyEntity" then mgr should be blank.
Negative Unit test
Using Manager private accessor I want to change name to "Test" so that mgr should be null. And then will verify the mgr value. To achieve this, I want to explicitly call the static constructor but when I call the static constructor using
Manager_Accessor.name = "Test" typeof(Manager).TypeInitializer.Invoke(null, null);
name is always set to "MyEntity" how to set name to "Test" and invoke the static constructor.
public class Manager { private static string name= "MyEntity"; private static object mgr; static Manager() { try { mgr = CreateMgr(name); } catch (Exception ex) { mgr=null; } } }
A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
yes we can have static constructor inside a non-static class. Yes, it can.
Working of Constructor in C#It is invoked by the 'new' operator immediately after memory gets allocated to the new object. 2. Explicit constructors (constructors defined by the user) can be parameterless or parameterized.
Which among the following is true for static constructor? Explanation: Static constructors can't be parameterized constructors.
As I found out today, the static constructor CAN be called directly:
from another Stackoverflow post
The other answers are excellent, but if you need to force a class constructor to run without having a reference to the type (ie. reflection), you can use:
Type type = ...; System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(type.TypeHandle);
I had to add this code to my application to work around a possible bug in the .net 4.0 CLR.
For anyone finding this thread and wondering... I just did the test. It appears System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor()
will only run the static constructor if it has not already been run for another reason.
For example, if your code isn't positive whether or not previous code may have accessed the class and triggered the static constructor to run, it doesn't matter. That previous access will have triggered the static constructor to run, but then RunClassConstructor() will not run it also. RunClassConstructor() only runs the static constructor if it hasn't already been run.
Accessing the class after RunClassConstructor() also does not result in the static constructor being run a second time.
This is based on testing in a Win10 UWP app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With