I m doing unit test for one of my app in WP7. I want to check whether the button_click function works properly. When I try to call the button_click function from my unit testcode
like below
CheckUrVacabolary.MainPage cpage = new CheckUrVacabolary.MainPage();
cpage.txtFind.Text = "home";
cpage.butMeaning_Click(cpage,null);
But the eventhandler(OnDefineInDictCompleted) inside the button_click(OnDefineInDictCompleted)
is not getting called. Here is the code
internal void butMeaning_Click(object sender, RoutedEventArgs e)
{
graphPass.Visibility = Visibility.Collapsed;
graphFail.Visibility = Visibility.Collapsed;
if (txtFind.Text.ToString() != "Enter the word")
{
butNext.IsEnabled = true;
DictServiceSoapClient client = GetDictServiceSoapClient();
String meaningfor;
if (txtRandomWord.Text.Trim().Length != 0)
{
txtRandomWord.Text = "";
meaningfor = wordToGuess;
}
else
{
meaningfor = txtFind.Text.Trim().ToString();
}
if (meaningfor.Length != 0)
{
client.DefineInDictCompleted +=
new EventHandler<DefineInDictCompletedEventArgs
(OnDefineInDictCompleted);
client.DefineInDictAsync("gcide", meaningfor);
}
}
}
I m not using MVVM model in my app. Is there any way I could call the event handler also.
The easy answer would be: do use MVVM nonetheless. One of its benefits is easier unit testing. But if you choose not to, you should make a separate method in a service-like class that is called by the event handler but can also be called from a unit test.
The method should contain only the business logic you want to test and not the UI behaviour. (With a view model you could even test UI behaviour, because it is abstracted). That means it should have arguments for the values you obtain from controls like txtRandomWord.
The event handler that client connects to is a problem.
First, the life cycle of each client instance you create by pressing the button is extended to that of the page, which introduces a potential memory leak.
Second, I assume OnDefineInDictCompleted is a method in your page, so you should extract that from the page as well in a way that it is accessible to unit tests. If that method touches UI elements, this may be a real headache. Again, a strong case for a view model.
Related
When building a Coded UI Map, I specify the application that needs to be launched as shown below.
When I run the following test, the Coded UI Test passes, having been able to locate the controls I'm specifying. In this case, it's a ListViewItem.
[TestMethod]
public void UserOpensAnExistingDiary()
{
this.UIMap.OpenExistingDiary();
}
public void OpenExistingDiary()
{
#region Variable Declarations
WpfListItem uIPenAppsLogicModelsDiListItem = this.UIPENWindow.UIDiariesGroup.UIItemList.UIDiaryGroup.UIPenAppsLogicModelsDiListItem;
WpfWindow uIDiaryEditorWindow = this.UIDiaryEditorWindow;
#endregion
// Launch '%LOCALAPPDATA%\Pen\app-5.0.6018.18517\Pen.Apps.Desktop.exe'
ApplicationUnderTest penAppsDesktopApplication = ApplicationUnderTest.Launch(this.OpenExistingDiaryParams.ExePath, this.OpenExistingDiaryParams.AlternateExePath);
// Double-Click 'Pen.Apps.Logic.Models.DiaryModels.Diary' list item
Mouse.DoubleClick(uIPenAppsLogicModelsDiListItem, new Point(76, 72));
// Wait for 1 seconds for user delay between actions; Click 'Diary' window
Playback.Wait(1000);
Mouse.Click(uIDiaryEditorWindow, new Point(590, 25));
}
If I delete the Launch UI Action, and programmatically launch the app the test is unable to locate the ListViewItem. The only difference is my removing the Launch action, and adding the following code to my tests, so they're initialized with the window launched.
[TestInitialize]
public void Setup()
{
string appPath = ApplicationPath.GetApplicationPath();
var app = ApplicationUnderTest.Launch(appPath);
}
Does anyone know why this would be the case?
The examples you provided are confusing as to what works and what doesn't. Also, using the UI maps makes it extremely difficult to see what is going on. Please add one of the test methods that is failing and include the UI Map code for
this.UIPENWindow.UIDiariesGroup.UIItemList.UIDiaryGroup.UIPenAppsLogicModelsDiListItem
My hunch would be that the application under test is not being used as a search limiting container in the failing case.
What I would do, is change to something like:
[CodedUITest]
public class TestingClass
{
WpfWindow containingWindow;
[TestInitialize]
public void Initialize()
{
this.containingWindow = ApplicationUnderTest.Launch(appPath);
}
[TestMethod]
public void Test1()
{
WpfListItem toClick = new WpfListItem(this.containingWindow);
// look in the UI map to see what it is doing for search properties
// and take the simplest sub-set that makes sense
toClick.SearchProperties.Add("AutomationId", "SomeId");
Mouse.Click(toClick); // do not need point, typically
/*
//You may need to include more levels of searching,
//but you can see what you need from the UI Map
WpfTable table = new WpfTable(this.containingWindow);
table.SearchProperties.Add("AutomationId", "myTableId");
WpfListViewItem itemToClick = new WpfListViewItem(table);
itemToClick.SearchProperties.Add("Name", "Some name");
*/
}
}
The point here is that the list item is getting the launched window as it's container which seems to not be happening in your current case.
I'm working on a custom GUI with SharpDX.
I have user Input from a Form Object and assign Action Methods to the specific events. Below my UI I have a "drawing canvas" and I use Tool Objects that also listen to those Form Events.
But I'm a bit stuck on the matter of how to design my program to only pass those events to a second layer (in this case my canvas) when the first layer did not "hit" anything. In short: Only call "Tool.OnMouseDown" when "Button.OnMouseDown" did return false? Would a Chain Of Responsibility be the/a correct or possible approach?
Or shall I make the current Tool check if "Excecute (Vector2)" is above some gui element but I think this would lead to the kind of coupling I want to prevent.
Hope someone is willing to help/hint (sorry for no code examples, if it's to confusingly descriped please tell me ;))
Thanks!
(Disclaimer: I know I don't have to reinvent the wheel, but I use it partly to learn and improve on my design patterns and coding skills)
thanks to sharp-ninja's answer i did the following:
ok working with it like this now :) thanks again Mister Ninja
using System.Windows.Forms;
public class HandleMouseEventArgs : MouseEventArgs
{
public bool handled { get; protected set; }
public HandleMouseEventArgs(MouseEventArgs args) : base(args.Button, args.Clicks, args.X, args.Y, args.Delta)
{
handled = false;
}
public void SetHandled()
{
handled = true;
}
}
Fortunately in .Net events get called in the order in which they are registered. You can use a handlable event arg so that the first handler of the event can tell subsequent event handlers whether the event was handled.
event EventHandler<MyHandlableEventArg> MultiLevelEvent;
Then in your main program:
// First event handler
MultiLevelEvent += (s, e) => { if(x) e.Handled = true; };
// Subsequent event handler
MultiLevelEvent += (s, e) => { if(!e.Handled) { /* Do Work */ } };
I have a function called ExecuteCommand that does things based on a user's input. These things can range from simply doing a Console.Writeline(), checking a check box on my form, or simulating keystrokes to another process, completely independent from my own. The function runs on a separate thread, so changing the UI will requiring some invoking. I have 2 ways of doing it... one of which I'm not sure is a good way but it's very easy.
Code below, the 3rd line is what I have a question with:
private void ExecuteCommand()
{
this.Invoke((MethodInvoker)delegate()
{
if (current_line_index < command_que.Count)
{
current_line = command_que[current_line_index];
if (current_line.StartsWith(">>Auto Enter"))
{
chkAutoEnter.Checked = false;
}
else if (current_line.StartsWith("+WinWait("))
{
string title_to_wait_for = current_line;
title_to_wait_for = title_to_wait_for.Remove(0, "+WinWait(\"".Length);
title_to_wait_for = title_to_wait_for.Remove(title_to_wait_for.Length - 2, 2);
t_WinWait = new Thread(() => WinWait(title_to_wait_for));
t_WinWait.Name = "WinWait";
t_WinWait.Start();
}
}
});
}
The code works perfectly... but I am not sure if it's good practice.
Alternativly, I know I can do something like this to change the UI:
private delegate void CheckCheckBoxHandler(bool checked);
private void CheckCheckBox(bool checked)
{
if (this.chkAutoEnter.InvokeRequired)
{
this.chkAutoEnter.Invoke(new CheckCheckBoxHandler(this.CheckCheckBox), checked);
}
else
{
chkAutoEnter.Checked = checked;
}
}
But as I have multiple controls on my form that will be changed from another thread, I'd have to add a bunch of functions to do that, versus the simple method in the first example.
Is the first way bad in anyway? Are there any risks involved I haven't come across yet? It seems to good to be true...
Thanks!
No it's not bad. It doesn't matter which control that you call Invoke on since they all have the same effect. Invoke calls the delegate on the thread that owns the control - as long as all your controls are owned by the same thread, then there is no difference.
Problem:
I am working on a application where in for some time consuming operation, i am supposed to show a progress bar on a form (WinForm) with a cancel button. So obviously i am using BackgroundWorker thread for it. Below is the code which simulates roughly of what i am trying to achieve.
namespace WindowsFormsApplication1
{
public delegate void SomeDelegateHandler();
public partial class Form1 : Form
{
public event SomeDelegateHandler DoSomeAction;
BackgroundWorker bgWorker;
public Form1()
{
InitializeComponent();
bgWorker = new BackgroundWorker();
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
}
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Some logic code here.
for (int i = 0; i < 100; i++)
{
DoSomeAction();
}
}
private void Form1_Shown(object sender, EventArgs e)
{
if (DoSomeAction != null)
bgWorker.RunWorkerAsync();
else throw new EventNotSubscribedException();//Is this a valid style??
}
}
public class EventNotSubscribedException : ApplicationException
{
//Some custom code here
}
}
My Solution
As per the above code, as soon as the form is displayed to the user (OnShown event) i am starting the backgroundworker thread. This is because, the user need not to initiate any action for this to happen. So onshown does time consuming operation job. But the issue is, as i have shown above, the main time consuming job is executed on other class/component where it is kind of tight bounded too (legacy code: cant refactor). Hence i have subscribed to the event DoSomeAction in that legacy code class which launches this form.
Doubt/Question:
Is it valid to throw exception as shown above? (Please read my justification below).
Justification:
The OnShown event does check for null on event handler object. This is because, to make this form usable, the event has to be subscribed by the subscriber (usage code), then only it shall work. If not, then the form just displays and does noting at all and usage code may not know why it is happenings so. The usage code may assume that subscribing to the event is option just like button click events per say.
Hope my post is clear and understandable.
Thanks & Happy Coding,
Zen :)
Do you mean that you need to throw an exception to the caller of the form? Is it called using showDialog or Show?
BTW, I dont prefer to generate an exception from an event. Rather it would be rather nice to keep it such that it returns from the place with some status set on the Form class.
for instance, I would prefer using
IsEventSubscribed = false
this.Close()
rather than EventNotSubscribedException
BTW, One problem I can see in the code, when the bgWorker_DoWork is called, you should check DoSomeAction to null, because otherwise it might cause NullReferenceException.
Preferably,
Start the run the RunWorkerAsync from Form_shown
Check Delegate to null in DoWork, if it is null, do not call DoSomeAction otherwise call it.
On RunWorkerCompleted of the BackgroundWorker, close the form.
Let me know if you need anything more.
I would suggest making the consuming code construct the BackgroundWorker and pass it to the form's constructor. You can do a null test in the constructor and side-step this whole issue. Alternatively, take the delegate as a constructor argument instead. I mean, how likely is it that the consuming code will need to change the worker delegate mid-operation?
Another approach is to have the dialog monitor a task, instead of having a dialog control a task (as you have here). For example, you could have an interface like this:
public interface IMonitorableTask {
void Start();
event EventHandler<TData> TaskProgress;
}
Where TData is a type that provides any information you might need to update the dialog (such as percent completed).
The downside to this is that each task needs to be a type of its own. This can lead to very ugly, cluttered code. You could mitigate that issue somewhat by creating a helper class, something like:
public class DelegateTask : IMonitorableTask {
private Action<Action<TData>> taskDelegate;
public event EventHandler<TData> TaskProgress;
public DelegateTask(Action<Action<TData>> taskDelegate) {
if (taskDelegate == null)
throw new ArgumentNullException("taskDelegate");
this.taskDelegate = taskDelegate;
}
protected void FireTaskProgress(TData data) {
var handler = TaskProgress;
if (handler != null)
handler(this, data);
}
public void Start() {
taskDelegate(FireTaskProgress);
}
}
Then your task methods become factories:
public IMonitorableTask CreateFooTask(object argument) {
return new DelegateTask(progress => {
DoStuffWith(argument);
progress(new TData(0.5));
DoMoreStuffWith(argument);
progress(new TData(1));
});
}
And now you can easily(*) support, say, a command-line interface. Just attach a different monitor object to the task's event.
(*) Depending on how clean your UI/logic separation already is, of course.
I have a class, that subscribes to an event via PRISMs event aggregator.
As it is somewhat hard to mock the event aggregator as noted here, I just instantiate a real one and pass it to the system under test.
In my test I then publish the event via that aggregator and then check how my system under test reacts to it. Since the event will be raised by a FileSystemWatcher during production, I want to make use of the automatic dispatch by subscribing on the UIThread, so I can update my UI once the event is raised.
The problem is, that during the test, the event never gets noticed in the system under test unless I don't subscribe on the UIThread.
I am using MSpec for my tests, which I run from inside VS2008 via TDD.Net.
Adding [RequiresSta] to my test class didn't help
Does anyone have a solution, that saves me from changing the ThreadOption during my tests (e.g. via a property - what an ugly hack)???
If you mock both the event and the Event Aggregator, and use moq's Callback, you can do it.
Here's an example:
Mock<IEventAggregator> mockEventAggregator;
Mock<MyEvent> mockEvent;
mockEventAggregator.Setup(e => e.GetEvent<MyEvent>()).Returns(mockEvent.Object);
// Get a copy of the callback so we can "Publish" the data
Action<MyEventArgs> callback = null;
mockEvent.Setup(
p =>
p.Subscribe(
It.IsAny<Action<MyEventArgs>>(),
It.IsAny<ThreadOption>(),
It.IsAny<bool>(),
It.IsAny<Predicate<MyEventArgs>>()))
.Callback<Action<MyEventArgs>, ThreadOption, bool, Predicate<MyEventArgs>>(
(e, t, b, a) => callback = e);
// Do what you need to do to get it to subscribe
// Callback should now contain the callback to your event handler
// Which will allow you to invoke the callback on the test's thread
// instead of the UI thread
callback.Invoke(new MyEventArgs(someObject));
// Assert
I really think you should use mocks for everything and not the EventAggregator. It's not hard to mock at all... I don't think the linked answer proves much of anything about the testability of the EventAggregator.
Here's your test. I don't use MSpec, but here's the test in Moq. You didn't provide any code, so I'm basing it on the linked-to code. Your scenario is a little harder than the linked scenario because the other OP just wanted to know how to verify that Subscribe was being called, but you actually want to call the method that was passed in the subscribe... something more difficult, but not very.
//Arrange!
Mock<IEventAggregator> eventAggregatorMock = new Mock<IEventAggregator>();
Mock<PlantTreeNodeSelectedEvent> eventBeingListenedTo = new Mock<PlantTreeNodeSelectedEvent>();
Action<int> theActionPassed = null;
//When the Subscribe method is called, we are taking the passed in value
//And saving it to the local variable theActionPassed so we can call it.
eventBeingListenedTo.Setup(theEvent => theEvent.Subscribe(It.IsAny<Action<int>>()))
.Callback<Action<int>>(action => theActionPassed = action);
eventAggregatorMock.Setup(e => e.GetEvent<PlantTreeNodeSelectedEvent>())
.Returns(eventBeingListenedTo.Object);
//Initialize the controller to be tested.
PlantTreeController controllerToTest = new PlantTreeController(eventAggregatorMock.Object);
//Act!
theActionPassed(3);
//Assert!
Assert.IsTrue(controllerToTest.MyValue == 3);
You may not like this as it may involve what you feel is an "ugly hack", but my preference IS to use a real EventAggregator rather than mocking everything. While ostensibly an external resource, the EventAggregator runs in memory and so does not require much set-up, clear down, and is not a bottle neck like other external resources such as databases, web-services, etcetera would be and therefore I feel it is appropriate to use in a unit test. On that basis I have used this method to overcome the UI thread issue in NUnit with minimal change or risk to my production code for the sake of the tests.
Firstly I created an extension method like so:
public static class ThreadingExtensions
{
private static ThreadOption? _uiOverride;
public static ThreadOption UiOverride
{
set { _uiOverride = value; }
}
public static ThreadOption MakeSafe(this ThreadOption option)
{
if (option == ThreadOption.UIThread && _uiOverride != null)
return (ThreadOption) _uiOverride;
return option;
}
}
Then, in all my event subscriptions I use the following:
EventAggregator.GetEvent<MyEvent>().Subscribe
(
x => // do stuff,
ThreadOption.UiThread.MakeSafe()
);
In production code, this just works seamlessly. For testing purposes, all I have to do is add this in my set-up with a bit of synchronisation code in my test:
[TestFixture]
public class ExampleTest
{
[SetUp]
public void SetUp()
{
ThreadingExtensions.UiOverride = ThreadOption.Background;
}
[Test]
public void EventTest()
{
// This doesn't actually test anything useful. For a real test
// use something like a view model which subscribes to the event
// and perform your assertion on it after the event is published.
string result = null;
object locker = new object();
EventAggregator aggregator = new EventAggregator();
// For this example, MyEvent inherits from CompositePresentationEvent<string>
MyEvent myEvent = aggregator.GetEvent<MyEvent>();
// Subscribe to the event in the test to cause the monitor to pulse,
// releasing the wait when the event actually is raised in the background
// thread.
aggregator.Subscribe
(
x =>
{
result = x;
lock(locker) { Monitor.Pulse(locker); }
},
ThreadOption.UIThread.MakeSafe()
);
// Publish the event for testing
myEvent.Publish("Testing");
// Cause the monitor to wait for a pulse, but time-out after
// 1000 millisconds.
lock(locker) { Monitor.Wait(locker, 1000); }
// Once pulsed (or timed-out) perform your assertions in the real world
// your assertions would be against the object your are testing is
// subscribed.
Assert.That(result, Is.EqualTo("Testing"));
}
}
To make the waiting and pulsing more succinct I have also added the following extension methods to ThreadingExtensions:
public static void Wait(this object locker, int millisecondTimeout)
{
lock (locker)
{
Monitor.Wait(locker);
}
}
public static void Pulse(this object locker)
{
lock (locker)
{
Monitor.Pulse(locker);
}
}
Then I can do:
// <snip>
aggregator.Subscribe(x => locker.Pulse(), ThreadOption.UIThread.MakeSafe());
myEvent.Publish("Testing");
locker.Wait(1000);
// </snip>
Again, if your sensibilities mean you want to use mocks, go for it. If you'd rather use the real thing, this works.