How to use Class Initialize so that application opens in beginning,run all the tests & closes in the end - coded-ui-tests

My code:
This is initialize method
[TestInitialize()]
public void MyTest Initialize()
{}
This is test 1
[TestMethod]
public void Validate_Create_Command()
{ }
This is test 2
[TestMethod]
public void Validate_Delete_Command()
{}
Right Now test1 opens application & closes the application &
test2 also opens the application & closes.
My question is how to open application once & close application after all tests completes

First I would recommend you always open at the beginning of the test and close at the end. Your recordings should be flexible enough that you can combine them to navigate to different parts of the app. I'll answer how best to do that in a moment first your actual question.
If you want to open at the start and close at the end I use this pattern
[TestClass]
public class Tests
{
[TestMethod]
public void TestMethod1()
{
UIMap.ClickNext();
UIMap.ClickPlusButton();
UIMap.AssertStuff();
}
[TestMethod]
public void TestMethod2()
{
UIMap.ClickNext();
UIMap.ClickMinusButton();
UIMap.AssertStuff();
}
[ClassInitialize()]
public static void ClassInitialize(TestContext testcontext)
{
Utilities.Launch();
}
[ClassCleanup()]
public static void ClassCleanup()
{
Utilities.Close();
}
}
public static class Utilities
{
private static ApplicationUnderTest App;
public static Launch()
{
try
{
App = ApplicationUnderTest.Launch(pathToExe);
}
catch (Microsoft.VisualStudio.TestTools.UITest.Extension.FailedToLaunchApplicationException e) {}
}
public static Close()
{
App.Close();
App = null;
}
}
To do this on a test to test basis you simple use the normal (below)
[TestInitialize()] and [TestCleanup()]

You could copy the method calls to launch and close the application from the test methods into the initialize and cleanup methods, then delete the calls from the test methods.
The way that Coded UI managed applications between test cases changed between Visual Studio 2010 and 2012, also the way that CloseOnPlaybackCleanup worked. For more details see http://blogs.msdn.com/b/visualstudioalm/archive/2012/11/08/using-same-applicationundertest-browserwindow-across-multiple-tests.aspx

You will need to re-record test 1 and test 2 to no longer open/close the application.
In TestInitialize, record the launching of your application.
In TestCleanup, record the closing of your application.
What will happen when you run the CodedUI test is:
Step 1: TestInitialize runs which launches your application
Step 2: Test1 and Test2 run (again, you will have removed
launching/closing of your app)
Step 3: TestCleanup runs which closes your application
#region Additional test attributes
//Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
this.UIMap.OpenMyApplication();
}
//Use TestCleanup to run code after each test has run
[TestCleanup()]
public void MyTestCleanup()
{
this.UIMap.CloseMyApplication();
}
#endregion

Related

how to do something when liferay module stop

i am making cron job like loop to do something using new thread.
when module stop, this thread keeps running, so when i deployed updated module, i'm afraid it will make duplicate thread doing similar task
#Component(immediate = true, service = ExportImportLifecycleListener.class)
public class StaticUtils extends Utils{
private StaticUtils() {}
private static class SingletonHelper{
private static final StaticUtils INSTANCE = new StaticUtils();
}
public static StaticUtils getInstance() {
return SingletonHelper.INSTANCE;
}
}
public class Utils extends BaseExportImportLifecycleListener{
public Utils() {
startTask();
}
protected Boolean CRON_START = true;
private void startTask() {
new Thread(new Runnable() {
public void run() {
while (CRON_START) {
System.out.println("test naon bae lah ");
}
}
}).start();
}
#Deactivate
protected void deactivate() {
CRON_START = false;
System.out.println(
"cron stop lah woooooooooooooooooy");
}
}
i'm using liferay 7
I have populated task that i store from db, so this thread is checking is there a task that it must do, then if it exist execute it.
I'm quite new in osgi and liferay. i've try to use scheduler and failed and also exportimportlifecycle listener but dont really get it yet
think again: Do you really need something to run all the time in the background, or do you just need some asynchronous processing in the background, when triggered? It might be better to start a background task as a one-off, that automatically terminates
Liferay provides an internal MessageBus, that you can utilize to listen to events and implement background processing, without the need for a custom thread
You're in the OSGi world, so you can utilize #Activate, #Modified, #Deactivate (from org.osgi.service.component.annotations) or use a org.osgi.framework.BundleActivator.
But, in general, it's preferable if you don't start your own thread

NUnit Inconclusive Confusion

I have the following:-
[TestFixture]
class TaskServiceTest
{
public void Implements_ITaskService()
{
var service = CreateService();
Assert.That(service, Is.InstanceOf<ITaskService>());
}
private static ITaskService CreateService()
{
return null;
}
}
When I run that in Visual Studio / Resharper It is reported as 'Inconclusive'. The explanation of which in the NUnit Docs is
The Assert.Inconclusive method indicates that the test could not be completed with the data available. It should be used in situations where another run with different data might run to completion, with either a success or failure outcome.
I don't see that holding here, so can anyone explain what I am doing wrong?
Thanks
I just realised that it is because I missed the [Test] attribute off of the unit test.
[Test]
public void Implements_ITaskService()
{
var service = CreateService();
Assert.That(service, Is.InstanceOf<ITaskService>());
}

BeforeFeature/AfterFeature does not work using SpecFlow and Coded UI

I am not able to define a [BeforeFeature]/[AfterFeature] hook for my feature file. The application under test is WPF standalone desktop applications.
If I use [BeforeScenario]/[AfterScenario] everything works fine, the application starts without any problem, the designed steps are performed correctly and the app is closed.
Once I use the same steps with [BeforeFeature]/[AfterFeature] tags the application starts and the test fails with:
The following error occurred when this process was started: Object reference not set to an instance of an object.
Here is an example:
[Binding]
public class Setup
{
[BeforeScenario("setup_scenario")]
public static void BeforeAppScenario()
{
UILoader.General.StartApplication();
}
[AfterScenario("setup_scenario")]
public static void AfterAppScenario()
{
UILoader.General.CloseApplication();
}
[BeforeFeature("setup_feature")]
public static void BeforeAppFeature()
{
UILoader.General.StartApplication();
}
[AfterFeature("setup_feature")]
public static void AfterAppFeature()
{
UILoader.General.CloseApplication();
}
}
StartApplication/CloseApplication were recorded and auto-generated with Coded UI Test Builder:
public void StartApplication()
{
// Launch '%ProgramFiles%\...
ApplicationUnderTest Application = ApplicationUnderTest.Launch(this.StartApplicationParams.ExePath, this.StartApplicationParams.AlternateExePath);
}
public class StartApplicationParams
{
public string ExePath = "C:\\Program Files..."
public string AlternateExePath = "%ProgramFiles%\\..."
}
Noteworthy: I'm quite new with SpecFlow.
I can't figure it out why my test fails with [BeforeFeature] and works fine with [BeforeScenario].
It would be great if somebody could help me with this issue. Thanks!
I ran into a similar problem recently. Not sure if this can still help you, but it may be of use for people who stumble upon this question.
For BeforeFeature\AfterFeature to work, the feature itself needs to be tagged, tagging just specific scenarios will not work.
Your feature files should start like this:
#setup_feature
Feature: Name Of Your Feature
#setup_scenario
Scenario: ...

Nunit 2.6.2 Suite running twice instead of once

using System;
using System.Collections;
using NUnit.Framework;
namespace Tests.MyTest
{
public class SpikeSuite
{
[Suite]
public static IEnumerable Suite
{
get
{
var suite = new ArrayList
{
new SpikeTest(),
};
return suite;
}
}
}
[TestFixture]
public class SpikeTest
{
[SetUp]
public void Setup()
{
Console.WriteLine("Test setup");
}
[TestFixtureSetUp]
public void FixtureSetup()
{
Console.WriteLine("Test fixture setup");
}
[Test]
public void TestMethod()
{
Console.WriteLine("Test method");
}
}
}
When I run the above mentioned fixture the output I get is:
Test fixture setup
.Test setup
Test method
Test fixture setup
.Test setup
Test method
How is it that the test setup, fixture setup and test method being executed twice?
Check that your test project is not referenced by another test project. In that case it will appear in two bin folders and be run twice.
Uninstalling the NUnit Test Adapter and re-installing fixed this issue for me.
In Visual Studio > Tools > Extensions and Updates > Remove NUnit Test Adapter then re-install it

Update UI while working on background

I have an update database operation, that has an activity, which keeps updating the percentage and it runs inside an AsyncTask.
Inside doInBackground() I call the controller that updates the database and keep updating the percentage on the activity, however, if I press home button or back button, the operation is cancelled. What u suggest me to do?
I was trying to start a Service inside doInBackground() so it would run in background, but it looks like its not working.
My code looks like this:
public class UpdateDatabaseAsyncTask extends AsyncTask<Void, Integer, Integer>
{
#Override
public void onPreExecute()
{
mCustomProgressBar.startAnimation();
}
#Override
public Integer doInBackground(Void... params)
{
return mController.updateDatabase();
}
#Override
public void onPostExecute(Integer result)
{
mCustomProgressBar.stopAnimation();
// finish the activity
}
#Override
public void onProgressUpdate(Integer... value)
{
updatePercentageValue(value[0]);
}
public void callPublishProgress(Integer value)
{
publishProgress(value);
}
}
And inside the controller I call the method callPublishProgress(value) passing the current percentage value, so it will publishProgress(value) in the UI.
I was debugging, and I pressed the home/back button, and it just stopped running the worker thread.
Another solution I tried, was starting a Service to run in background no matter the user press home/back button or not, so I thought, and the Service would make a call to the controller method that does the work, and it would call the callPublishProgress(value) to update the percentage value on the UI anyways.
However, what was happening is, the code reach doInBackground() and start the service, but it goes to onPostExecute() immediately, it just didn't wait the service to finish(of course!). So it gives a NullPointerException. I thought of making a loop inside doInBackground() with a flag set in the Service, so it would leave this loop while the service hasn't been finished (I was using an IntentService), but it didn't work anyways.
I thought of using a Timer too. But I don't know.
I was reading the articles in documentation about Threads, etc. And it suggests using AsyncTask, just as I was trying to do. It also talks about runOnUiThread(Runnable).
Anyways what I need is to make an operation in background(probably using an IntentService), so no matter if the user press the home button, it will keep running, but it must update the percentage on the UI, and when the user leave the screen and back to it, it shows the current percentage value updated in the screen.
What is the best solution for my case?
Thanks.
public class MyServce extends Service{
public static final String BROADCAST_ACTION = "com.myapp";
Intent intent;
private final Handler handler = new Handler();
#Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DoYourWorking();
handler.postDelayed(this, 1000); // 1 seconds
}
private void DoYourWorking() {
........
........
intent.putExtra("key", progress);
sendBroadcast(intent);
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendUpdatesToUI);
}
Now in your Activity register broadcast to service
private BroadcastReceiver brodcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//intent.getWhatever
// update your progress
//progressbar.setProgress
}
register broadcast
registerReceiver(brodcast, new IntentFilter(MyService.BROADCAST_ACTION));
This worked for me. I started a background service on a thread that just fetches the values and updates an object in a singleton.
In the view controller, I start a timer that keeps updating the view by fetching data from the object in singleton.
I had a little problem understanding your entire question text, so I'm not sure if you have tried this. But this is what worked. Also, the service was started with START_STICKY
Use an IntentService (which is a Service on a thread of its own), and Handler to pass the data back to the Activity.

Resources