WPF CodedUI test: programmatically launching application - wpf

If I record actions to enter in login credentials into a dialog and call this Submit() in say UImap1.uitests. The autogenerated code will look something like this:
public void Launch()
{
#region Variable Declarations
WpfEdit uIUsernameBoxEdit = this.UIOCC600OILoginWindow.UIUsernameBoxEdit;
WpfEdit uIPasswordBoxEdit = this.UIOCC600OILoginWindow.UIPasswordBoxEdit;
WpfButton uIOKButton = this.UIOCC600OILoginWindow.UIOKButton;
#endregion
// Type 'username' in 'usernameBox' text box
uIUsernameBoxEdit.Text = this.LaunchParams.UIUsernameBoxEditText;
// Click 'passwordBox' text box
Mouse.Click(uIPasswordBoxEdit, new Point(63, 13));
// Type '********' in 'passwordBox' text box
Keyboard.SendKeys(uIPasswordBoxEdit, this.LaunchParams.UIPasswordBoxEditSendKeys, true);
// Click 'OK' button
Mouse.Click(uIOKButton, new Point(33, 14));
}
Now, if I manually launch the application under a method decorded with ClassInitialize in my in my CodedUI test class as follows:
[ClassInitialize()]
public static void MyTestInitialize(TestContext context)
{
Process.Start(#"C:\Program Files (x86)\MyCompany\MyApp.exe");
Playback.Wait(2000);
var uimap = new LaunchApplicationMap();
var loginParams = uimap.EnterLoginCredentialsParams;
loginParams.UIUsernameBoxEditText = "username";
loginParams.UIPasswordBoxEditSendKeys = Playback.EncryptText("password
");
uimap.Launch();
Playback.Wait(5000);
}
why do I get the following a null exception as shown below?
This is also the stack trace:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=Microsoft.VisualStudio.TestTools.UITest.Framework
StackTrace:
at Microsoft.VisualStudio.TestTools.UITest.Framework.UITestService.TechnologyManagerByName(String technologyName)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.ValidateSearchProperties()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindInternal()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindControlIfNecessary()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.SetProperty(String propertyName, Object value)
at Microsoft.VisualStudio.TestTools.UITesting.WpfControls.WpfEdit.set_Text(String value)
at UITests.UIMaps.LaunchApplicationMapClasses.LaunchApplicationMap.Launch() in C:\dev\OCC600\Source - Copy\Tests\UITests\UIMaps\LaunchApplicationMap.Designer.cs:line 44
at UITests.LogsViewTests.MyTestInitialize(TestContext context) in C:\dev\OCC600\Source - Copy\Tests\UITests\LogsViewTests.cs:line 70
InnerException:
TIA.

You need to initialize the playback engine to use CodedUI outside of a test method. The framework automatically initializes playback/cleanup in the testinitalize/cleanup methods so you don't see it in there.
ClassInitialize/AssemblyInitialize happen before any tests begin so you have to call Playback.Initialize().

Related

creating items collection in a custom control

I have a Custom control inheriting from Control class in my WinForm. My control contains multiple panels and other UIElements.
This is what my control is supposed to look like
There's a database panel,
database panel contains a single checkbox only.
and there's a Server panel,
server panel contains many database panels and a single label; the header label.
And finally there's the container panel that contains all my Server panels.
I found this Item Collection option for a User Control but I couldn't really understand the accepted answer on it. If someone could help explain it better that would be great.
Also, if someone could just put some links for creating advanced custom controls. I've been reading all day about it and I still can't make any sense of it all. Is there a step-by-step guide for advanced custom controls?
[Edit]
Basically what I need is to create a custom collection within my custom control. Currently my control is built as Winform Control Library which I build and then I use in my main program later.
So in my main program, I can just drag and drop the component on my form and use it.
By default, the custom control will load with one Server that contains one database.
What I want is to be able to add/remove other databases/servers to it if I need to, in my MAIN program
I'm having trouble explaining exactly what I need because I simply do not understand how the whole custom control/items collection thing works really, and i'm sorry for that. I would really appreciate some links that explains this stuff clearly
here's my code for this control:
This code only creates my default control, but I am UNABLE to add to it. The collection property appears in my property windows but when I add items to it and click okay nothing happens.
public class Database : System.Windows.Forms.Panel
{
public CheckBox _ckbDatabase;
public Database()
{
_ckbDatabase = new CheckBox();
this.BackColor = _pnlDatabaseBackColor;
this.Size = _pnlDatabaseSize;
this.AutoSize = false;
this.Height = 40;
this.Width = 200;
this.Location = _pnlDatabaseLocation;
_ckbDatabase.Top = 10;
_ckbDatabase.Left = 15;
_ckbDatabase.TextAlign = _ckbdbTextAlignment;
_ckbDatabase.Font = _ckbdbFont;
_ckbDatabase.ForeColor = Color.White;
this.Controls.Add(_ckbDatabase);
}
#Propterties
}
public class Server : System.Windows.Forms.Panel
{
private Label _lblserver;
private Database database;
public Server()
{
_lblserver = new Label();
database = new Database();
this.BackColor = _pnlServerBackColor;
this.Size = _pnlServerSize;
this.AutoSize = false;
_lblserver.Dock = _lblserverDock;
_lblserver.Font = _lblsrvFont;
_lblserver.BackColor = _lblServerBackColor;
_lblserver.AutoSize = false;
_lblserver.Text = SRV;
database.Top = 35;
database._ckbDatabase.Text = DB;
this.Controls.Add(_lblserver);
this.Controls.Add(database);
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DatabaseCollection DatabaseCollection { get; set; }
#Propterties
}
public class ServersCollection : CollectionBase
{
public Server this[int index]
{
get { return (Server)List[index]; }
}
public void Add(Server server)
{
List.Add(server);
}
public void Remove(Server server)
{
List.Remove(server);
}
}
How about something simple like this:
public class Server {
public string Name { get; set; }
public List<Database> Databases { get; set; }
public Server() {
Databases = new List<Database>();
}
}
public class Database {
public string Name { get; set; }
public bool Enabled { get; set; }
}
Then you can just add it like this:
List<Server> servers = new List<Server>();
Server serverA = new Server { Name = "Server A" };
serverA.Databases.Add(new Database { Name = "Database 1", Enabled = true });
serverA.Databases.Add(new Database { Name = "Database 2", Enabled = false });
Server serverB = new Server { Name = "Server B" };
serverB.Databases.Add(new Database { Name = "Database 1", Enabled = false });
serverB.Databases.Add(new Database { Name = "Database 2", Enabled = false });
servers.Add(serverA);
servers.Add(serverB);
When you link to the Item Collection part it seemed like you wanted to be able to add servers and databases in design mode but then you mention you want to do it by code? If this is not what you want you need to give us more information.
Looks to me like you are mostly there. First off, here's a more complete collection class:
public class ServersCollection : IEnumerable<Server>
{
private List<Server> _servers = new List<Server>();
public Server this[int index]
{
get { return _servers[index]; }
}
public IEnumerator<Server> GetEnumerator()
{
foreach (var server in _servers)
yield return server;
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public void Add(Server server)
{
_servers.Add(server);
}
public void Remove(Server server)
{
//You might consider a deliberate loop to evaluate a proper match
//Don't forget to Dispose() it first!
_servers.Remove(server);
}
public void Clear()
{
for (Int32 i = _servers.Count - 1; i >= 0; i--)
_servers[i].Dispose();
_servers.Clear();
}
}
Add an instance of the ServersCollection class to the container control, the one at the top level that holds server panels:
private ServersCollection _servers = new ServersCollection();
public ServersCollection Servers { get { return _servers; } }
Use that as a way for it to add Server controls to its own collection of controls.
Do a similar thing with the DatabaseCollection in the Server class, again so that it can add Database panels to its controls collection.
Then, wherever you have an instance of a control, you will also have access to the collection of what it holds:
myControl.Servers
//-or-
myServer.Databases
...allowing you to add/remove, as such:
myControl.Servers.Add(new Server());
//-or-
myServer.Databases.Add(new Database());
Points of emphasis
Your classes are controls, but they also own other controls. Proper use of the Dispose pattern will be crucial or you'll have memory issues throughout.
I would remove these lines, they don't matter unless you intend to add servers/DBs at form design time (i.e. fixed entries or defaults):
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public DatabaseCollection DatabaseCollection { get; set; }
Finally, you could (should!) take that collection class further, with overloads for Add() and Remove() that do a better job of deciding when/how/what to do based on more than an instance, e.g. by name? You could also add another indexer to fetch by name, for instance, instead of just index (which you might not readily know).

How to use property file as a object repository in Selenium WebDriver Automation?

How to use property files as a object repository in Selenium WebDriver Automation ?
I am seeking for instructions regarding the setup and the steps that need to be done to achieve this.
Create a framework.properties file and store the variables in this way(below are two locators with sample values)
locator1=username
locator2=password
Create a class for loading the properties file. You can use the snippet below:
Note:Path /src/main/resources/com/framework/properties/ is a sample path and may change as per your framework
public class PropertyManager {
private static final Properties PROPERTY = new Properties();
private static final String FRAMEWORKPROPERTIESPATH = "/src/main/resources/com/framework/properties/";
private static final Logger LOGGER = Logg.createLogger();
public static Properties loadPropertyFile(String propertyToLoad) {
try {
PROPERTY.load(new FileInputStream(System.getProperty("user.dir")
+ FRAMEWORKPROPERTIESPATH + propertyToLoad));
} catch (IOException io) {
LOGGER.info(
"IOException in the loadFrameworkPropertyFile() method of the PropertyManager class",
io);
Runtime.getRuntime().halt(0);
}
return PROPERTY;
}
}
When you want to access the variables from the property class, use the snippet below:
private static final Properties LOCATORPROPERTIES = PropertyManager
.loadPropertyFile("framework.properties");
public void click() {
driver.findElement(By.id(LOCATORPROPERTIES.getProperty("locator1")));
}
Create any file & save it with .properties extension
For example - Add new file in eclipse By right click on project > New > File
Add below data in config.properties file and save
Username = Jhon
Password = Qwerty123
Write Below code to access this file
String filepath = "./config.properties" ; // Path of .properties file
File f = new File(filepath);
FileInputStream fs = new FileInputStream(f);
Properties pro = new Properties();
Pro.Load(fs);
pro.getProperty("Username"); // return value "Jhon" return type string
pro.getProperty("Password"); // retun value "Qwerty123" return type string
Also use like -
driver.findelement(By.id("user")).sendKeys(pro.getProperty("Username"));
driver.findelement(By.id("pass")).sendKeys(pro.getProperty("Password"));

Why doesn't simple test pass using AutoFixture Freeze, SemanticComparison Likeness and CreateProxy?

I'm trying to understand how to use the CreateProxy() feature of Likeness<T>() using two instances of a simple class.
public class Band
{
public string Strings { get; set; }
public string Brass { get; set; }
}
With the following test, I use a Fixture to Create<T> a Band instance with values for the two string properties.
[Fact]
public void Equality_Behaves_As_Expected()
{
// arrange
var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization());
var original = fixture.Create<Band>();
// Brass something like --> "Brass65756b89-d9f3-42f8-88fc-ab6de5ae65cd"
// Strings something like --> "Strings7439fa1b-014d-4544-8428-baea66858940"
// act
var dupe = new Band {Brass = original.Brass,
Strings = original.Strings};
// Brass same as original's like --> "Brass65756b89-d9f3-42f8-88fc-ab6de5ae65cd"
// Strings same as original's like --> "Strings7439fa1b-014d-4544-8428-baea66858940"
I've tried many different assertions, but the crux of the matter seems to be that the CreateProxy method is not populating the properties of Band, so that even when I try to compare two instances of Band with the same property values, the instance from the CreateProxy method always has null values.
// assert
var likeness = dupe.AsSource().OfLikeness<Band>()
.Without(x => x.Brass).CreateProxy();
// Brass & String properties are null using dupe as source of likeness (!)
//var likeness = original.AsSource().OfLikeness<Band>()
// .Without(x => x.Brass).CreateProxy();
// Brass & String properties are null using original as source of likeness (!)
//Assert.True(likeness.Equals(original)); // Fails
//Assert.True(original.Equals(likeness)); // Fails
// below are using FluentAssertions assembly
//likeness.Should().Be(original); // Fails (null properties)
//original.Should().Be(likeness); // Fails (null properties)
//likeness.ShouldBeEquivalentTo(original); // Fails (null properties)
//original.ShouldBeEquivalentTo(likeness); // Fails (null properties)
}
I've gotta be doing something wrong, but I've read everything I can find on the Ploeh blog and SO, and can't find an example suitably simple enough to compare to what I'm doing. Any ideas?
If you assign the values on the proxied instance (after calling the CreateProxy method) the test passes:
[Fact]
public void Equality_Behaves_As_Expected()
{
// AutoMoqCustomization is not necessary.
var original = new Fixture().Create<Band>();
var likeness = original
.AsSource()
.OfLikeness<Band>()
.Without(x => x.Brass)
.CreateProxy();
likeness.Brass = "foo"; // Ignored.
likeness.Strings = original.Strings;
Assert.True(likeness.Equals(original));
likeness.Should().Be(original);
likeness.ShouldBeEquivalentTo(original);
}
Keep in mind that Likeness creates a proxy on the target type and only that type's instance overrides Equals.
Since the source type remains intact, the following assertions will not succeed:
Assert.True(original.Equals(likeness));
original.Should().Be(likeness);
original.ShouldBeEquivalentTo(likeness);
Update
From version 3.0.4 and above the values are automatically copied to the proxy instance (which means, likeness.Strings = original.Strings; is going to happen automatically).

Exception Using Dynamically adding controls to silverlight childwindow?

I have a parameterised constructor in My Application. I want to add controls dynamically to my silverlight Child Control Page. But it gives NullReferenceException.
I can't find out why it returns null.Can any help me with this situation?
public PDFExport(FrameworkElement graphTile1, FrameworkElement graphTile2,FrameworkElement graphTile3)
{
Button btnGraph1 = new Button();
string Name = graphTile1.Name;
btnGraph1.Content = Name;
btnGraph1.Width = Name.Length;
btnGraph1.Height = 25;
btnGraph1.Click += new RoutedEventHandler(btnGraph1_Click);
objStack.Children.Add(btnGraph1);
LayoutRoot.Children.Add(objStack); // Here am getting null Reference Exception
_graphTile1 = graphTile1;
_graphTile2 = graphTile2;
_graphTile3 = graphTile3;
}
Thanks.
I guess objStack is a stackpanel declared in your XAML?
Be aware that the UI component of your xaml are build by the call to InitializeComponent.
Thus objStack will not exist until you call InitializeCOmponent() in your constructor.
Also, you should know that the call to InitializeComponent is asynchronous, so you code should look like something like that:
private readonly FrameworkElement _graphTile1;
private readonly FrameworkElement _graphTile2;
private readonly FrameworkElement _graphTile3;
public PDFExport(FrameworkElement graphTile1, FrameworkElement graphTile2, FrameworkElement graphTile3)
{
_graphTile1 = graphTile1;
_graphTile2 = graphTile2;
_graphTile3 = graphTile3;
}
private void PDFExport_OnLoaded(object sender, RoutedEventArgs e)
{
Button btnGraph1 = new Button();
string Name = _graphTile1.Name;
btnGraph1.Content = Name;
btnGraph1.Width = Name.Length;
btnGraph1.Height = 25;
btnGraph1.Click += new RoutedEventHandler(btnGraph1_Click);
objStack.Children.Add(btnGraph1);
LayoutRoot.Children.Add(objStack);
}
Hope it helps.
As per my research i got that, why it raises an exception: Because there is no
InitializeComponent() in My Constructor and am not calling parent constructor.
That is the reason it raises Exception.
Just Add InitializeComponent() to the code, simple

Retrieving mode (Basic|Advanced) of ADF query component

I want to capture query component mode(Basic | Advanced) in processQuery event listener method for QueryEvent as below:
public void processQuery(QueryEvent queryEvent)
{
// Add event code here...
QueryDescriptor qdesc = queryEvent.getDescriptor();
String searchName = qdesc.getName();
String queryMode =?
I tried to get this value from getUIHints() map using UIHINT_MODE key. but getUIHints() returns empty map.
Try this :
ViewCriteria vc = null;
try
{
Method m =
pQueryDescriptor.getClass().getDeclaredMethod("getViewCriteria",
null);
m.setAccessible(true);
vc = (ViewCriteria) m.invoke(pQueryDescriptor, null);
}
catch (Exception ite)
{
_logger.logp(Level.SEVERE, CLAZZ_NAME, methodName,
"Exception getting ViewCriteria from QueryDescriptor.",
ite);
}
String searchType =
(String) vc .getProperty(ViewCriteriaHints.CRITERIA_MODE);
The idea is to get the ViewCriteria from the QueryDescriptor and to get the mode from the VC. This is becasue the mode is set on the criteria object itself, the VC knows how to display and what to display in each mode, and so it makes the MODE an inherent property of the VC and not just a UI thing....
QueryDescriptor qdesc = queryEvent.getDescriptor();
QueryDescriptor.QueryMode mode = (QueryDescriptor.QueryMode) qdesc.getUIHints().get(qdesc.UIHINT_MODE);
if("BASIC".equals(mode.toString())){
}

Resources