Can one access TestContext in an AssemblyCleanup method? - c#

In Microsoft's UnitTesting namespace (Microsoft.VisualStudio.TestTools.UnitTesting) there are AssemblyInitialize and AssemblyCleanup attributes you can apply to static methods and they will be called before and after all tests respectively.
[AssemblyInitialize]
static public void AssemblyInitialize(TestContext testCtx)
{
// allocate resources
}
[AssemblyCleanup]
static public void AssemblyCleanup()
{
// free resources
}
My question: is it possible and safe to access the TestContext within AssemblyCleanup()? If not, is storing resource references as static members a reasonable alternative or could that cause problems as well?
Additionally/optionally: what is the reasoning behind not passing a reference to the TestContext to clean-up methods?

I'm accessing a static property on the same class and it seems to be working fine. I'll update this answer if I encounter any problems. I am not, however, accessing the TestContext so I'm curious if that would work too.

You can't pass any paramaters to AssemblyCleanup method. Here's the error if you try to do so:
Result Message: Method
SomeNamespace.TestDatabaseInitializer.AssemblyCleanup has wrong
signature. The method must be static, public, does not return a value
and should not take any parameter.

Related

MSTest invokes contructor everytime

I got a unit test (MStest)
There is a test class that has a lot of test methods.
If I run all methods from TestExplorer, each method will invoke the constructor.
Is there any way to save TestClass instance across all of these methods?
well, there are multiple different attributes that indicate when a method should be invoked. When you want a setup to run only once for all tests, you should use the ClassInitialize -attribute, not the constructor:
[TestClass]
class MyTests
{
[ClassInitialize]
public static void SetupTests(TestContext context) { ... }
}
Performing initializations from within the constructor is merely a bad idea, as every test-framework has its own plan on when and how often to invoke those. Instead you should use the attributes which are deterministic in their use.
If you need initialization to happen before every test, you may use the TestInitialize-attribute.

Use a public attribute in a static method on c#

I created a plugin and I'm trying to use it on a class, the problem is that the method I'm trying to use in this class is a static method.
The struct of the plugin implementation is this:
The problem is in the method called TestMethod, on the TestClass class.
I can't use the attribute TestPlugin because it is not a static property.
I've tried to use it as static, but when I change this the TestPlugin property becomes null.
For this reason I tried to find a way to use it as a normal property, but after a lot of search I had not been able to find a way to do it.
The code is as follows:
TestPlugin declaration:
[ImportMany]
public IEnumerable<ITestPlugin> TestPlugin{ get; private set;}
Use of TestPlugin attribute:
private static void TestMethod(){
...
// Here Visual Studio says that :
//An object reference is required for the nonstatic field, method, or property 'ToastPlugin'
foreach(plugin in TestPlugin){
//Plugin's use
}
...
}
Edit:
Is there a way to use TestPlugin inside of TestMethod without declaring TestPlugin as static, for the reasons said before?
Is there a way to use TestPlugin inside of TestMethod without
declaring TestPlugin as static, for the reasons said before?
Quick answer is no.
Basically you have the following options:
Make TestPlugin static as well.
Make TestMethod not be static.
Make TestMethod take a reference to a TestClass object as a parameter.
Add a static collection of IList<IEnumerable<ITestPlugin>> and in the get/set methods of the TestPlugin add/remove the class from that new collection.
Which of those four you would choose depends upon exactly what you are trying to achieve.

Calling instance method from a constructor in C#

I have a rather lengthy constructor which is performing various initialisation work, and as such I wanted to factor out some of this work into some functions. This led to me wonder whether I should make the said functions instance or static methods. I understand the risk of calling a virtual function from a constructor but I also think there is something not right about calling an instance method on an object which is not 100% instantiated. Surely this is a contradiction in terms.
I'd be interested in peoples opinion on this matter. I also found that by using a static method to return an initialised variable I could make the member target read-only. Here's a simplified illustration of my scenario.
public class A
{
private readonly string _foo;
public A()
{
_foo = InitialiseFoo();
}
private static InitialiseFoo()
{
// Do stuff
return new string ("foo");
}
}
This is pretty normal to call instance method in a constructor, moreover method which doing Initialization. So basically this is a kind of Extract Method refactorig to reduce a constructor method body, so you are extracting part of initialization into a separate method and constructor is aware on saving of the input arguments, etc...
Regarding the static modifier.. sometimes (I believe when no other ways to refactor because this looks not good - from my point of view) you need to call a method to pass results in a base constructor so in this case you have to mark it as static to call in a static context in other cases leave it without the static modifier
public A()
: base(GetLogger())
{
}
private static ILog GetLogger() ...
I can understand the desire to only use static members in a constructor, because it DOES make the code more straightforward to use without having to track what has been initialized and what hasn't, but you're likely making things needlessly complicated for yourself. Calling an instance method in C# is fine as long as you have a good reason to do it. For instance, if you have a number of constructors that all perform some common tasks, creating a single member function to do the work is easier to maintain than copy-and-pasting the code for each constructor. You can also imagine a case where the method can be re-used outside of the constructor for something like reseting the class to the initialized state.
The static method, is fine, but will only work in the case where you are doing some isolated work and putting the result into a member variable. It provides a very clean, functional programming-like feel. If any of the work involves class state, however, it's going to get ugly.

How do I explicitly run the static constructor of an unknown type? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do I invoke a static constructor with reflection?
I've got some initialization code in the static constructor of various classes. I can't create instances, nor do I know the types in advance. I would like to ensure the classes are loaded.
I tried this:
fooType.TypeInitializer.Invoke (new object[0]);
But got a MemberAccessException: Type initializer was not callable.
I'm assuming this is because the cctor is private? Is there a way to fix this without changing the architecture?
Edit: I found a workaround using RuntimeHelpers.RunClassConstructor, but this way seems to be barely documented in the MSDN and I'm not sure if it is a hack or a reasonable, prod system like way.
I'm not sure why this works, but as far as I reason (with help from Skeet) if i have a static class
public static class Statics1
{
public static string Value1 { get; set; }
static Statics1()
{
Console.WriteLine("Statics1 cctor");
Value1 = "Initialized 1";
}
}
The code:
Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null);
or
staticType.TypeInitializer.Invoke(new object[0]);
will throw with an exception, because somehow this resolves to the .ctor, instead of the .cctor of the class.
If I use an explicitly static class, it is treated like an abstract sealed class, so the exception is that an abstract class cannot be instantiated, and if I use a regular class with a static constructor, the exception is that the type initializer is not callable.
But if I use the Invoke overload with two parameters (instance, params), like this:
Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null, null);
explicitly stating that I am invoking a static method (that's the meaning of the first null - no instance == static), this works and initializes the class.
That said, static constructors are strange beasts. Invoking one in this way will call the static constructor even if it was already executed, i.e., this code:
Console.WriteLine(Statics1.Value1);
Type staticType = typeof (Statics1);
staticType.TypeInitializer.Invoke(null, null);
will call the static constructor twice. So if your cctors have potentially important sideeffects, such as creating files, opening databases, etc, you might want to rethink this approach.
Also, even though I prefer static constructors for reasons of readability, from a performance perspective, field initializers are a bit faster than static constructors
EDIT: explicitly won't work as-is, as poster states can't know the types in advance. Leaving here as might help clarification for future readers ...
If I understand your needs correctly -- in similar circumstances I create a wrapper that references the static class but remains part of the test suite. You can then instantiate the wrapper and have the static initialized on demand. It'd mean you can leave the architecture unchanged, and keep the wrapper as part of the test framework.
public static class MyStatic
{
public static string SomeToolMethod()
{
return "Hello";
}
}
public class MyStaticWrapper // or proxy, technically?
{
public static string SomeToolMethod()
{
return MyStatic.SomeToolMethod();
}
}
fooType.TypeInitializer.Invoke(new MyStaticWrapper()); /// untested, not sure of syntax here

How to mock with static methods?

I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.
The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface.
What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?
Yes, you use instance methods. Static methods basically say, "There is one way to accomplish this functionality - it's not polymorphic." Mocking relies on polymorphism.
Now, if your static methods logically don't care about what implementation you're using, they might be able to take the interfaces as parameters, or perhaps work without interacting with state at all - but otherwise you should be using instances (and probably dependency injection to wire everything together).
I found a blog via google with some great examples on how to do this:
Refactor class to be an instance class and implement an interface.
You have already stated that you don't want to do this.
Use a wrapper instance class with delegates for static classes members
Doing this you can simulate a static interface via delegates.
Use a wrapper instance class with protected members which call the static class
This is probably the easiest to mock/manage without refactoring as it can just be inherited from and extended.
I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.
i.e. in your class with the static method have:
private static final MethodObject methodObject = new MethodObject();
public static void doSomething(){
methodObject.doSomething();
}
and your method object can be a very simple, easily-tested:
public class MethodObject {
public void doSomething() {
// do your thang
}
}
You might be trying to test at too deep a starting point. A test does not need to be created to test each and every method individually; private and static methods should be tested by calling the public methods that then call the private and static ones in turn.
So lets say your code is like this:
public object GetData()
{
object obj1 = GetDataFromWherever();
object obj2 = TransformData(obj1);
return obj2;
}
private static object TransformData(object obj)
{
//Do whatever
}
You do not need to write a test against the TransformData method (and you can't). Instead write a test for the GetData method that tests the work done in TransformData.
Use instance methods where possible.
Use public static Func[T, U] (static function references that can be substituted for mock functions) where instance methods are not possible.
A simple solution is to allow to change the static class's implementation via a setter:
class ClassWithStatics {
private IClassWithStaticsImpl implementation = new DefaultClassWithStaticsImpl();
// Should only be invoked for testing purposes
public static void overrideImplementation(IClassWithStaticsImpl implementation) {
ClassWithStatics.implementation = implementation;
}
public static Foo someMethod() {
return implementation.someMethod();
}
}
So in the setup of your tests, you call overrideImplementation with some mocked interface. The benefit is that you don't need to change clients of your static class. The downside is that you probably will have a little duplicated code, because you'll have to repeat the methods of the static class and it's implementation. But some times the static methods can use a ligther interface which provide base funcionality.
The problem you have is when you're using 3rd party code and it's called from one of your methods. What we ended up doing is wrapping it in an object, and calling passing it in with dep inj, and then your unit test can mock 3rd party static method call the setter with it.

Categories

Resources