MSTest Unit Test - handling exceptions - c#-4.0

I have a C# unit test using Selenium WebDriver to test to see if a link exists. Here's the code:
[TestMethod()]
public void RegisterLinkExistTest()
{
IWebElement registerLink = genericBrowserDriver.FindElement(By.PartialLinkText ("Register1"));
Assert.AreEqual("Register here", registerLink.Text, "Failed");
}
I wanted to see what happens if I set the PartialLinkText as "Register1" instead of "Register". MSTest failed this test with a exception thrown from Selenium. I wanted the Assert.AreEqual to execute but MSTest throws a exception on the previous line. I know I can use ExpectedException attribute to specify "OpenQA.Selenium.NoSuchElementException" but I don't want to do that way because I'm not expecting that exception. How do I go about handling this?

As #AD.Net already said, your test is working as expected.
You could catch the exception in case the link was not found but I don't see the point to do that. If the link is not found then the registerLink will be null. What's the point of asserting on a null object's property?
Your test works fine, just delete the Assert line.
However, if you also want to test the link's text try the following code:
[TestMethod()]
public void RegisterLinkExistTest()
{
try
{
IWebElement registerLink = genericBrowserDriver.FindElement(By.PartialLinkText ("Register1"));
Assert.AreEqual("Register here", registerLink.Text, "Register's link text mismatch");
}
catch(NoSuchElementException)
{
Assert.Fail("The register link was not found");
}
}
EDIT
You can seperate your test, the first test will check if the link exists and the second will assert it's properties.
[TestMethod()]
public void RegisterLinkExistTest()
{
IWebElement registerLink = genericBrowserDriver.FindElement(By.PartialLinkText ("Register1"));
}
[TestMethod()]
public void RegisterLinkTextTest()
{
IWebElement registerLink = genericBrowserDriver.FindElement(By.PartialLinkText ("Register1"));
Assert.AreEqual("Register here", registerLink.Text, "Register's link text mismatch");
}
Then use an OrderedTest and add them in that order so the RegisterLinkExistTest will be executed first. If it fails then the second test will not run.

Related

MessageRemovedException on mailParsing when setShouldMarkAsDelete flag true in IMAP IDLE Adaptor config

I am getting the MessageRemovedException on parsing the email after receiving the email in the EmailReceiveChannel, if I have configure ShouldMarkAsDelete flag as "true".
Everything works fine if the flag is set as false
#Bean
public ImapMailReceiver imapMailReceiver() {
StringBuilder impaURI = new StringBuilder();
impaURI.append(MAIL_PROTOCOL).append("://").append(MAIL_USERNAME).append(":").append(MAIL_PASSWORD)
.append("#").append(MAIL_HOST).append(":").append(MAIL_PORT).append("/").append(MAIL_FOLDER);
ImapMailReceiver mailReceiver = new ImapMailReceiver(impaURI.toString());
mailReceiver.setShouldDeleteMessages(true);
mailReceiver.setShouldMarkMessagesAsRead(true);
mailReceiver.setJavaMailProperties(javaMailProperties());
mailReceiver.setAutoCloseFolder(false);
return mailReceiver;
}
On debugging the flow, expunged flag for MimeMessage is coming as "true". This stopped working recently.
Any idea why is this issue?
The logic there in the AbstractMailReceiver is like this:
private void postProcessFilteredMessages(Message[] filteredMessages) throws MessagingException {
setMessageFlags(filteredMessages);
if (shouldDeleteMessages()) {
deleteMessages(filteredMessages);
}
where that deleteMessages() does only this:
message.setFlag(Flags.Flag.DELETED, true);
The expunge functionality is performed over here:
protected void closeFolder() {
this.folderReadLock.lock();
try {
MailTransportUtils.closeFolder(this.folder, this.shouldDeleteMessages);
}
finally {
this.folderReadLock.unlock();
}
}
So, since you have that mailReceiver.setAutoCloseFolder(false);, it means you close folder yourself and only after that you try to get access to the message content. Must be opposite: you have to close folder only after you have already parsed the content of the message.

SSJS to call a method in java class (in java library)

I've created a java library (named: invoke) with a java class (Invoke). Its seen when expanding Script libraries under code in the designer navigation pane.
The code is:
package com.kkm.vijay;
public class Invoke {
public static void main(String[] args) {
Runtime r = Runtime.getRuntime();
Process p = r.exec("C://some.exe");
}
}
Used the following ssjs to an onclick event of a button shows Error:500 when previewed in browser.
importPackage(com.kkmsoft.vijay);
var v=new Invoke();
v.main();
Even i used a function inside the class and changed the last line of ssjs to v.fn(). Yet the same problem.
There are a number of things wrong, and as Fredrik mentions you should switch on the standard Error page.
Your first code won't run because it is not correctly capturing the Exception. You are also using a main() method, which is normally used to execute a program. But you are calling it without any arguments. Avoid using that method unless it is for executing an application.
So change it to this:
package com.kkm.vijay;
import java.io.IOException;
public class Invoke {
public void mainCode() {
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec("C://WINDOWS//notepad.exe");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You should put that code in the new Java view in Designer.
Next your button code needs to change.
var v=new com.kkm.vijay.Invoke();
v.mainCode();
Testing that it should work fine. The issue next is, as it is SSJS the application will execute on the server. There may be security implications in this, and it may need you to modify the java.policy file in order to do this.
The related permission will be java.io.FilePermission.

Geb Reporter / Extension to retrieve Test Status

I am attempting to replace some custom java selenium extensions by utilizing geb. I have hit a bit of a brick wall when I attempt to utilize a grid in the cloud (i.e. SauceLabs). When my tests complete, it'd be nice to send an update back to indicate whether or not the test has failed or succeeded. To utilize this, I need the sessionId from the RemoteWebDriver instance. This can be obtained in a custom Reporter, however I can't determine the success with this interface. Since I am extending the GebReportingSpec, I attempted to create my own custom version, which had a custom Junit rule to track success or failure:
public class TestSuccess extends TestWatcher {
boolean success;
String message;
#Override
protected void starting(Description d) {
message = d.getMethodName();
}
#Override
protected void succeeded(final Description description) {
System.out.println("Test Success [succeeded] " + description);
this.success = true;
}
#Override
protected void failed(final Throwable e, final Description description) {
System.out.println("Test Success [failed] " + description);
this.success = false;
}
public boolean isSuccess() {
return success;
}
#Override
public String toString() {
return message + " success: <" + success + ">.";
}
}
I then added that to my CustomReportingSpec:
class CustomReportingSpec extends GebReportingSpec {
/* I also tried creating this as a RuleChain with:
* #Rule TestRule chain = RuleChain.outerRule(
super._gebReportingSpecTestName).around(new TestSuccess());
* however, this results in a NPE. Placing the super rule in the around
* still results in a NPE.
*/
#Rule public TestSuccess _gebTestSuccesswatcher = new TestSuccess();
// I never see this called
void report() {
System.out.println("Custom Reporting Spec: " + _gebTestSuccesswatcher + "\t")
super.report()
}
}
I have also attempted to set this up in a custom reporter:
public CustomReporter extends ScreenshotAndPageSourceReporter implements Reporter {
#Rule
public TestSuccess _gebTestSuccesswatcher = new TestSuccess();
#Override
public void writeReport(Browser browser, String label, File outputDir) {
System.out.println("Custom Reporter: " + _gebTestSuccesswatcher);
super.writeReport(browser, label, outputDir)
}
}
However, regardless of whether or not my test fails, the success method on the watcher seems to be called. Here is my sample test:
class OneOff extends CustomReportingSpec {
def "Check One off"() {
when:
go "http://www.google.com"
then:
1 == 2
}
}
And the output:
Custom Reporter: null success: <false>.
Test Success [succeeded] Check One off(OneOff)
As you can see the success method is called upon completion of this failing test. If I modify the test to pass (i.e. 1 == 1), here is my output:
Custom Reporter: null success: <false>.
Test Success [succeeded] Check One off(OneOff)
Is there any way for me to get this Rule to work properly in the Custom Reporter? Or is there a way to get the browser instance in an extension? I've followed this guide to create a custom annotation and listener, but I can't access the Browser object. I have attempted adding an #Shared onto the declaration of the browser, but it isn't pulling the one in the Geb Configuration.
Your TestSuccess class doesn't work correctly due to a known limitation in Spock's TestRule support. Due to subtle differences between Spock's and JUnit's test execution model, calling base.evaluate() from a TestRule will not throw an exception in Spock, even if the test has failed. In many cases this won't make a difference, but for TestWatcher it will.
This is the only known limitation in Spock's rule support, and hopefully we'll find a way to overcome it at some point. There is no such semantic mismatch when using MethodRule.
If you want to implement your requirement with the help of a JUnit rule (which I think is fine), MethodRule is probably the better choice anyway. In contrary to TestRule, MethodRule provides access to the test instance, which will allow you to grab the session ID with browser.driver.sessionId.

J2ME Uncaught Exception

I plan to start my first lesson in j2me, and I download a simple book and I try my first program.
When I take a second step to add commands, I face an error message which is:
uncaught exception java/lang/noclassdeffounderror: readfile.
So, would you please help me to understand this message? and how to solve it?
Please find my code below.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ReadFile extends MIDlet implements CommandListener
{
private Form form1;
private Command Ok, Quit;
private Display display;
private TextField text1;
public void startApp()
{
form1 = new Form( "TA_Pog" );
Ok = new Command("Ok", Command.OK, 1);
Quit = new Command("Quit", Command.EXIT, 2);
form1.setCommandListener(this);
form1.addCommand(Ok);
form1.addCommand(Quit);
text1 = new TextField("Put Your Name :","His Name : " , 32, TextField.URL );
form1.append(text1);
display = Display.getDisplay(this);
display.setCurrent(form1);
}
public void commandAction(Command c , Displayable d)
{
if (c == Ok)
{
Alert a = new Alert("Alert","This Alert from Ok Button", null, AlertType.ALARM);
a.setTimeout (3000);
display.setCurrent(a,this.form1);
}
else
{
this.notifyDestroyed();
}
}
public void pauseApp() {}
public void destroyApp( boolean bool ) {}
}
Note: the code above is taken exactly from a book.
Thanks in advance
Besr regards
uncaught exception java/lang/noclassdeffounderror: readfile.
I somehow doubt the message is exactly as you describe it. Does it look more like below?
uncaught exception java/lang/NoClassDefFoundError: ReadFile
Please keep in mind in Java it matters much whether you use lower or upper case letters. As long as you don't pay attention to stuff like that, you are likely be getting a lot of problems like that.
Now, take a closer look at your class name:
public class ReadFile //...
The exception you are getting most likely says that Java machine can't find the class you try to use. There is something wrong with your build/compilation.
I run your code. It's running good. I think you have to clean and build your project. Firstly go to project properties and then go to Application Descriptor and click on Midlet tab, and select your midlet and press ok then clean build, run it.

how to test a failed moq

I have used a happy test to create a method and now i am using a null test on it.
I need to change the assert in the test method but i have no clue how to go about it. i did some searches but i can seem to only find happy path tests or returns in the main method. is there a way to do a moq and test for not excecuting or is the only way having the method return a variable (a Boolean in this case)
the method
public void Upload(Data.RPADataEntity RPADataEntity)
{
if (RPADataEntity != null)
{
//Give RPA the first status and then insert it into the database it.
RPADataEntity.RPAStatusID = Convert.ToInt32(Enum.RPAStatusEnum.RPAStatus.FileInputDataUploaded);
_IRPADataLayer.InsertRpaData(RPADataEntity);
}
}
the test method
[TestMethod]
public void TestUploadRPAEntityNull()
{
//Arange
var fileinputtest = new FileInput();
RPADataEntity RPADataEntity = null;
//Act
fileinputtest.Upload(RPADataEntity);
//Assert
_mockRepository.Verify(x => x.InsertRpaData(RPADataEntity));
}
This should do it:
_mockRepository.Verify(x => x.InsertRpaData(RPADataEntity), Times.Never());

Resources