Application.Current is null when calling from a unittest - c#

I have a method that I'm trying to call from a unit test.
This method will in real life be run from a background thread. It uses some code to kick off in the invoke updates to the UI thread (using Application.Current.Dispatcher.BeginInvoke .... ).
However Application.Current is null when being called from the unit tests.
I don't really what to put an if (Application.Current !=null) around everything to fix.
Is there any other way around this?
_statusUpdates is an ObservableCollection
Below is the part of the code in the method I'm looking to test (it is more of an integration test than a unit test to be fair).
Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (EventHandler)delegate
{
_statusUpdates.Add(new StatusUpdate
{
DateTime = DateTime.Now,
Message = "Checking For Messages"
});
}, null, null);

The following code snippet works for me:
if (System.Windows.Application.Current == null)
{ new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; }
IIRC, I had a problem where Application was null using a WPF control embedded in a WinForms application and that code snippet was suggested as a solution to the problem in another question on StackOverflow (sorry, can not find the source). It solves the same problem in unit tests (and I don't believe the ShutdownMode property needs to be explicitly set in that case).

As already stated, you simply won't have an Application class during unit tests.
That said, there's an issue here I think needs addressing - by having code that relies on a defined static property, in your case Application.Current.Dispatch, you are now very tightly coupled to the specific implementation of that class, namely the WPF Application class, where you do not need to be.
Even if you simply wrap the idea of "the current root dispatcher" in a Singleton-style class wrapper, now you have a way of decoupling yourself from the vagaries of the Application class and dealing directly with what you care about, a Dispatcher:
Note, there are MANY MANY ways to write this, I'm just putting up the simplest possible implementation; hence, I will not be doing any multithreaded safety checks, etc.
public class RootDispatcherFetcher
{
private static Dispatcher _rootDispatcher = null;
public static Dispatcher RootDispatcher
{
get
{
_rootDispatcher = _rootDispatcher ??
Application.Current != null
? Application.Current.Dispatcher
: new Dispatcher(...);
return _rootDispatcher;
}
// unit tests can get access to this via InternalsVisibleTo
internal set
{
_rootDispatcher = value;
}
}
}
Ok, now this implementation is only slightly better than before, but at least you now have finer control over access to the type and are no longer strictly dependent on the existence of an Application instance.

Use Dispatcher.CurrentDispatcher instead of Application.Current.Dispatcher
Gets the System.Windows.Threading.Dispatcher for the thread currently
executing and creates a new System.Windows.Threading.Dispatcher if one
is not already associated with the thread.

You will not have an Application object in a unit-test runner. These are usually "console" based applications that simply run and execute non-UI code ("units").
I suggest you don't use a unit test framework to test UI-specific information, I suggest a automated UI testing framework to do that.

So the issue here is that somewhere your Application object has to be created. So you need to find where the System.Windows.Application (or some descendent) class is being instantiated.
If the project was built from a template, then you'll probably find this class in the App.xaml file. You just need to make sure that this gets instantiated somehow. Else, search your entire project for an Application class, and then you'll have to instantiate it manually. Should fix it.

Related

Outside of using subclassing, is there a way to be notified when the application object is instantiated?

Thanks to an advanced initialization scenario (as warned about in the documentation), we're leveraging the ModuleInitializer attribute to run some code at module-initialization time like so...
[ModuleInitializer]
public static void InitModule() {
// Do something with the app here
}
However, we found differences in behavior depending on how the module was loaded. Specifically...
If loaded via a project reference/dependency, Application.Current property is not set.
If dynamically loaded via reflection, Application.Current property is set.
Since we need access to the current application for part of our initialization (it doesn't have to run right then, only when the application exists), our initial approach was during our initializers, test if Application.Current was set. If so, use it as normal. If not, build some sort of 'actions queue' that would queue up all the actions we want to run, then from within the Application class's constructor, process that queue.
As such, the above changed to this...
[ModuleInitializer]
public static void InitModule() {
void appRelatedInitialization(Application application) {
// Do something with the app here
}
if(Application.Current is not null) {
appRelatedInitialization(Application.Current);
}
else {
// Add the method to a queue of actions which take an Application as an argument
Globals.AppInitQueue.Add(appRelatedInitialization);
}
}
But then we ran into an application that doesn't use an Application subclass, instead opting for a main method and doing all the app configuration there.
Of course we could add the queue processing there, just like we could with an initializer and subclassing, but what we really want is to know when the application is instantiated regardless of the type of application it is and have this execute automatically for us so we don't have to add it anywhere.
The issue is Application.Current is a static POCO property that doesn't use INotifyPropertyChanged or similar, so we're not sure how to determine when the Application instance is set. We don't want to use brute-force polling either as that is the worst kind of code-smell.
So, how can we determine when the current Application object is created and assigned to the running process?
Dispatcher.CurrentDispatcher will create a Dispatcher for the current thread if not already created, which will be started by Application.Run(), so you should be able to do
Dispatcher.CurrentDispatcher.BeginInvoke(() => {})
I tried this, and it will run after the App constructor and App_Startup is called, if you leave Dispatcher.Priority as it's default.
(If you want it to run earlier, you can do
Dispatcher.CurrentDispatcher.BeginInvoke(() => {}, DispatcherPriority.Send);
in which case it will run after App construction but before App_Startup, although reading through the source code it seems they explicitly try to run OnStartup first, due to some bug, and this is circumventing that. I don't know the repercussions of doing that.)

C# DataBinding / Update DynamicObject property from another thread

Previously I was working on an implementation of DynamicObject data binding (see Dynamic object two way data binding), and the solution works great. Since then I have run into the need to be able to update the values from different threads it seems to break the bindings. I am able to update the DynamicObject instance from multiple threads however am unable to keep the bindings updated.
I tried to implement the SynchronizedNotifyPropertyChanged solution provided by Cody Barnes in the SO: INotifyPropertyChanged causes cross-thread error with no success.
Any help with binding a DynamicObject implementation that is updated via a non-ui thread would be greatly appreciated. The solution and gist attached work great (values updated on any thread (ui or non-ui) no problem), it is just the DataBinding to a Form Control that is not.
Edit #1 - (Thank you Reza Aghaei)
I see where my question is a bit vague, here is the implementation and goal I am trying to accomplish.
First, I have the Form which handles the creation of a logic 'engine' which can run tasks (based on internal class methods as well as external method calls or events). So somewhere inside the Form class, I generate this logic 'engine' object (will call it GameEngine for this example).
// GameEngine initializes and provides the DynamicData (MyCustomObject)
// --> engine is defined via public or private field of (this) Form class
engine = new GameEngine();
// Create the binding
LabelTestCounter.Databindings.Add("Text", engine.Data, "TestValue", true, DataSourceUpdateMode.OnPropertyChanged);
Now in the GameEngine class, I instantiate the DynamicData (MyCustomObject)
public class GameEngine
{
public dynamic Data;
// Constructor
public GameEngine()
{
Data = new MyCustomObject();
// I would like to initialize the data here as ownership really
// belongs to the 'GameEngine' object, not the Form
engine.Data.TestValue = "Initial test value";
}
public void StartBusinessLogic()
{
// In reality, this would be a long-running loop that updates
// multiple values and performs business logic.
Task.Run(() => {
data.TestValue = "Another Text";
});
}
}
Note in this example above, the MyCustomObject is (currently) an exact copy of what Reza has provided in his gist in his answer below. In the blog post and the gist provided, I lean towards the 'Option 1' provided as I would like the DynamicData object (MyCustomObject), to be self-containing the logic for synchronization for portability purposes.
Another note, the GameEngine, outside of holding the DynamicData object in a property, should not care whether or not the UI thread is using it, the responsibility of synchronization should (in my mind) remain with the UI thread. With that said, the DynamicData object should be aware of cross threaded calls and handle them accordingly as needed.
Edit #2 - Original question reference update
In reference to:
I tried to implement the SynchronizedNotifyPropertyChanged solution
provided by Cody Barnes in the SO: INotifyPropertyChanged causes cross-thread error with no success.
When working with the original SO Dynamic object two way data binding, and the original solution (again thank you Reza), I attempted to implement the referenced 'wrapper' to overcome the problem with cross-threaded updates. However, the only way that I could get the above solution to work was when the properties were hard-coded into the class. When any attempts were made to use a dynamic object, the bindings would either update once and lose the binding or throw some kind of binding exception.
I hope this clarifies the original question a little bit better.
Edit #3 - Symbol not resolved
Not sure if this is a problem, as compilation is working, (and this may be Resharper, not sure as I don't recall the problem previously).
In 'MyCustomObject':
public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
var properties = new List<MyCustomPropertyDescriptor>();
foreach (var e in dictionary)
properties.Add(new MyCustomPropertyDescriptor(e.Key, (e.Value?.GetType()) ?? typeof(object)));
return new PropertyDescriptorCollection(properties.ToArray());
}
(e.Value?.GetType()) <-- GetType is showing 'Cannot resolve symbol 'GetType'.
however the code does compile without errors so I am not sure why/when exactly I started seeing this.
Edit #4 - Resolved Edit #3
No idea what caused the problem in Edit 3, but it grew into showing other errors (mysteriously) such as Cannot apply indexing with to an expression of type 'System.Collections.Generic.Dictionary', however, I did a Build -> Clean Solution and then closed the solution and reopened it in Visual Studio and the problem seemed to go away with that error highlighting in the editor (which I have been seeing a bit of strange behavior like that since I started playing with Resharper (EAP), so possibly early access bugs? but that problem is unrelated to this SO, the original SO has been resolved and the strange behavior in edit 3 will be better handled by JetBrains/Resharper Team rather than here at this point.
Edit #5 - Special Thanks
I hope this is not inappropriate (if it is, admins feel free to delete/edit this), however, I would like to send a special thank you to Reza Aghaei for all your help both here on SO as well as in the background. Reza, your blog, gists and other assistance with this ongoing problem has really helped both in solving the problem and helping me understand the reasons behind the solution.
To raise OnPropertyChanged from a non-UI thread in a way which updates the UI, you need to pass an instance of ISynchronizeInvoke to your implementation of ICustomTypeDescriptor:
ISynchronizeInvoke syncronzeInvoke;
public MyCustomObject(ISynchronizeInvoke value = null)
{
syncronzeInvoke = value;
}
Then on OnPropertyChanged use that ISynchronizeInvoke to Invoke when InvokeRequired:
private void OnPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
{
if (syncronzeInvoke != null && syncronzeInvoke.InvokeRequired)
syncronzeInvoke.Invoke(handler, new object[]
{ this, new PropertyChangedEventArgs(name) });
else
handler(this, new PropertyChangedEventArgs(name));
}
}
This way, the event will raise in UI thread when needed.

Capturing Dialog-Windows with SpecFlow

I am fairly new to testing still, but have been using SpecFlow for a a few months. I am not entirely sure if what I am going to ask is possible, but maybe someone will have a suggestion to go about the problem.
Synopsis: My feature file makes a call to a method that creates a dialog window stored in a variable created in that method. The user would then need to fill out the dialog window (it is basically picking a file, and then clicking ok). The rest of the method relies on the information provided by the dialog window.
Problem: Since the window is created in the method and the result is stored in a variable created at that moment, I can not provide my information into the variable. But in order for my behavior tests to finish, I need to provide this information.
Example code:
Feature File:
Given I initialize the class
And I click on change selected item
Steps File:
[Given(#"I initialize the class")]
public void GivenIInitializeTheClass()
{
DoStuff();
SomeClass testClass = new SomeClasee();
}
[Given(#"IClickOnChangeSelectedItem")]
public void GivenIClickOnChangeSelectItem()
{
testClass.ChangeItem();
}
Method From Class:
public void ChangeItem()
{
var window = new SomeDialogWindow();
var result = window.ShowDialog();
if (result.HasValue && result.Value)
{
NewItem = window.SelectedItem;
}
}
I would know how to go about this if I could change the method in the class, but, in this example, I can make no changes to the class itself. Again I do not know if it is possible to assign anything to the result, or control the window since the variables for both are created within the method.
Depending on what you want to do this is quite a common pattern and fairly easy to solve, but first lets consider what kind of testing you might want to be running.
Unit tests - In a unit test that only wants to test the implementation of SomeClass we don't care about the implementation of other classes including SomeDialogWindow. Alternatively we could be writing tests that care solely about the implementation of SomeDialogWindow, or even just the implementation of SomeClass::ChangeItem and nothing else. How fine do you want to go? These tests are there to pinpoint exactly where some of your code is broken.
Acceptance tests - We build these to test how everything works together. They do care about the interaction between different units and as such will show up things that unit tests don't find. Subtle configuration issues, or more complicated interactions between units. Unfortunately they cover huge swathes of code, so leave you needing something more precise to find out what is wrong.
In a Test driven development project, we might write a single acceptance test so we can see when we are done, then we will write many unit tests one at a time, each unit test used to add a small piece of functionality to the codebase, and confirm it works before moving to the next.
Now for how to do it. As long as you are able to modify SomeClass its not a huge change, in fact all you really need is to add virtual to the ChangeItem method to make
public virtual void ChangeItem()
...
What this now allows you do is to replace the method with a different implementation when you are testing it. In the simplest form you can then declare something like,
namespace xxx.Tests
{
public class TestableSomeClass : SomeClass
{
public Item TestItem {get;set;}
public override void ChangeItem()
{
NewItem = TestItem;
}
}
}
This is a very common pattern and known as a stub. We've reduced the functionality in ChangeItem down to its bare essentials so its just a minimal stub of its original intent. We aren't testing ChangeItem anymore, just the other parts of our code.
In fact this pattern this pattern is so common there are libraries there to help us to Mock the function instead. I tend to use one called Moq and it would now look like this.
//Given
var desiredItem = ...
Mock<SomeClass> myMock = new Mock<SomeClass>();
myMock.Setup(x=>x.ChangeItem).Returns(desiredItem);
var testClass = myMock.Object;
//When
testClass.ChangeItem();
//Then
testClass.NewItem.ShouldEqual(....);
You will notice that in both these examples we have gotten rid of the GUI part of the codebase so that we can concentrate on your functionality. I would personally recommend this approach for getting 90% to get your codebase covered and end up with rapid uncomplicated testing. However sometimes you need Acceptance tests that even test the UI, and then we come to an altogether more complicated beast.
For eaxmple, your UI will include blocking calls when it displays the visual elements, such as SomeDialogWindow.ShowDialog() and these have to occur on what is commonly referred to as the UI thread. Fortunately while only one thread can be the UI thread, any thread can be the UI thread if it gets there first, but you will need to have at least one thread displaying the UI and another running the tests. You can steal a pattern from web based testing and create driver classes that control your UI, and these will end up on the test running thread performing the click operations and polling to see if the operations are complete.
If you need to go to these lengths then don't start with this as you learn how to use the testing frameworks, start with the simple stuff.

How to refactor to avoid using a Shim?

I'm pretty new to Unit Testing and am exploring the Microsoft Fakes framework - primarily because it's free and it allows me to mock SharePoint objects easily with the Emulators package. I've seen various mentions on SO and elsewhere that Shims are evil and I more or less understand why. What I don't get is how to avoid them in one specific case - in other words, "how should I refactor my code to avoid having to use shims?"
For the code in question, I have a JobProcessor object that has properties and methods, some of which are private as they should only be called from the public Execute method. I want to test that when Execute is called and there is a Job available that its Process method is called as I need to do some extra logging.
Here's the relevant code:
//in system under test - JobProcessor.cs
private IJob CurrentJob { get; set; }
public void Execute()
{
GetJobToProcess(); //stores Job in CurrentJob property if found
if (ShouldProcessJob){
CurrentJob.ProcessJob();
}
}
I need to do some extra things if ProcessJob is called from a test, so I set up a Stub in my Test Method to do those extra things:
StubIJob fakeJob = new StubIJob(){
ProcessJob = () =>{
//do my extra things here
}
};
I'm testing the ProcessJob method itself elsewhere so I don't care that it doesn't do anything but my extra stuff here. As I understand things, I now need to set up a Shim to have the private method GetJobsToProcess from JobProcessor (my system under test) return my fake job so that my stubbed method is called:
processor = new JobProcessor();
ShimJobProcessor.AllInstances.GetJobToProcess = (#this) =>{
var privateProcessor = new PrivateObject(processor);
privateProcessor.SetProperty("CurrentJob", fakeJob); //force my test Job to be processed so the Stub is used
};
In this case, how should I avoid using the Shim? Does it matter?
Thanks.
This is a case where rather than using a shim or stub, I'd just make the method return a boolean to notify whether or not the inner call has happened.
The problem with using fakes there is that you're assuming that some method of some object is called, which the test should not know. Tests should be dumb, and only see the outside of the code. Tests, like any other code, should not care how a value was reached, just that it is correct.
However, your code has another issue as well. You're getting some unknown object and using it within the same scope. You should remove the call to GetJobToProccess from Execute.
It's the principle of Dependency Injection: a method should not spin up and hide it's dependencies; if it depends on an object, that object should be possible to change freely or be passed in. The exact implementation of the job should not matter to the execute method, and that, along with the naming, implies that you should not be getting that object and executing it in the same call.

Application Domain switching

I have a situation where I need to create a (arguably dirty) soak test runner. The idea being to use something like Tasks or the ThreadPool to run a massive amount of the tests at one time.
The issue is that it will be using a lot of (poorly developed, by me) helper classes that use statics within them. This has never been an issue as everything was torn down and restarted after it was used. This means that when I start multiple threads in the same app domain, they use the same statics, and things get messy.
Note: it is an assumption based on testing I've been doing, I'm not 100% sure on that being the issue.
I've tried creating a new AppDomain (AppDomain.Create) and then created an instance of a class using it (domain.CreateInstanceFromAndUnwrap), and it creates the instance, and I can call methods on it. The problem is that it doesn't seem to be running in the new AppDomain.
Here's the code I have so far:
static void CallBack(BasePerfTest bpf)
{
Console.WriteLine("CurrentAppDomain (WithinCallback): {0}", Thread.GetDomain().Id);
AppDomain newdomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
//newdomain.ExecuteAssembly(".\\PerformanceTestRunner.exe", new string[] { bpf.ToString() });
ProcessRunner pr = (ProcessRunner)newdomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, "PerformanceTesting.ProcessRunner");
pr.RunProcess(bpf);
}
}
[Serializable]
public class ProcessRunner
{
public void RunProcess(BasePerfTest bpf)
{
Console.WriteLine("CurrentAppDomain (WithinPR): {0}", Thread.GetDomain().Id);
}
}
Now, I would expect that the RunProcess() method is executed in the domain, but the DomainID is still the same, and therefore it's hitting the issue with the statics colliding.
Now, I did created a separate console app, and the commented out line shows the code I used to run it. This DID run in the new domain, but the question is why.
I'm happy to be pointed in the direction of some bedtime reading on how this works, I've 'd for the past day and I think I must just not be using the right terms.
Any help is much appreciated.
Thanks,
Martin
There are two ways to expose objects over AppDomain boundaries:
Serializable - serializes the object, so you get a copy.
MarshalByRefObject - creates a proxy to your object, using remoting.
You need the latter for your ProcessRunner class.
Make your class inherit from MarshalByRefObject:
public class ProcessRunner : MarshalByRefbject
{
public void RunProcess(BasePerfTest bpf)
{
Console.WriteLine("CurrentAppDomain (WithinPR): {0}", Thread.GetDomain().Id);
}
}
When you instantiate your class in the second AppDomain, you get a proxy. The example in the documentation for MarshalByRefObject on MSDN should also help you - it demonstrates almost exactly what you are trying to do.
Your ProcessRunner class must inherit from System.MarshalByRefObject. What is happening is that the object is actually being created in the secondary appdomain, but when you assign it to your local 'pr' variable it is marshalling it by value back to your primary appdomain, in effect creating a second instance of ProcessRunner in the primary appdomain. If you inherit from MarshalByRefObject then pr will instead get a transparent proxy object which forwards calls to the object residing in the secondary appdomain.

Categories

Resources