I use Assert class to check if some text is on the page, this command stop test executing if text is not present. I want use verification. Could someone tell where I could find documentation on such methods?
I mean WebDriver, junit. For example such code
String text=("Terms");
List<WebElement> list = driver.findElements(By.xpath("//*[contains(text(),'" + text + "')]"));
Assert.assertEquals("Text not found!", "Terms", list);
If there isn't text "Term" on page junit test will interrupt test, but I need just take error message and continue test.
If you want to continue execution of your test cases even if some some result you are expecting fails and get to see the results at the end of complete execution.
You can do something like this -
Declare a variable to store all the test case results which fail during execution and then in the tearDown method you can call Assert.fail(String message)
StringBuffer errors = new StringBuffer();
#Test
public void testSomething(){
if(!"data".equals(text)){
addErrors(text +"not equal to data");
}
// add any number of if statements to check anything else
}
#After()
public void tearDown(){
if(errors.length()!=0){
Assert.fail(errors.toString());
}
}
public String addErrors(String message){
errors = errors.append(message+"\n");
}
Now in the testSomething() method you can check or test any number of WebElements on the webpage and all you have to do is have a simple if statement to check if some thing is correct and if not then call the addErrors() method. Hope this helps you.
Sounds like you just need to catch and handle AssertionError thrown by the various methods of Assert (documented here). Something like this:
try {
Assert.assertEquals("Text not found!", "Terms", list);
} catch (AssertionError e) {
System.err.println("Assertion failed: " + e.getMessage());
}
Related
I want to validate the presence of a text using assertTrue(), but I am getting a StackOverflow error. I am not sure that the code I have written is correct or not. Need your suggestions.
// Checking the posted text
WebElement postedtext= driver.findElement(By.cssSelector("css123"));
assertTrue("The text is verfied",postedtext.getText().equals(enteredText));
private static void assertTrue(String string, boolean equals) {
assertTrue(string,equals);}
You have a method called assertTrue(s, b) which calls itself. This is causing an infinite recursion.
It is a name conflicting that you happened to name you assert method the same name as the library method. Rename your assertTrue can solve the problem.
// Checking the posted text
WebElement postedtext= driver.findElement(By.cssSelector("css123"));
myAssertTrue("The text is verfied",postedtext.getText().equals(enteredText));
private static void myAssertTrue(String string, boolean equals) {
try {
assertTrue(string,equals);
} catch (AssertionError e) {
System.out.println(e.getMessage());
throw e;
}
}
Or you just delete your assertTrue and use the library method instead.
This question already has answers here:
throw checked Exceptions from mocks with Mockito
(5 answers)
Closed 5 years ago.
I have the below class
There is an answer to this in StackOverflow but it deals with List throw checked Exceptions from mocks with Mockito. I like to look into this condition. Not getting where I am missing.
public SimpleClass{
private SimpleClass() {}
public void runMethod(request,String,Map,Object,Object) {
try {
doesSomething()....
}
}
catch(Exception e) {
String message = "" + request.getAttribute(X) + "Some message";
Logger.Log(param1 + param2 + message);
}
}
My Test method looks like below. I trying to run the coverage with the JUnit but the Catch Block is not covered, so Wrote the below test method. It throws the below exception. Not able to get where I am missing.
public class SimpleClassTest{
#Test
public void testCatchBlock() {
SimpleClass instanceObj = PowerMockito.mock(SimpleClass.class);
Mockito.doThrow(new Exception())
.when(instanceObj)
.runMethod(request, anyString(), anyMap(), anyObject(), anyObject());
}
}
Exception Thrown
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: java.lang.Exception
Edit
I am able to run the method by giving NullPointerException. When I try for code coverage with Junit, the catch block is completely shown as red, and the catch phrase is shown yellow. How do I achieve 100% coverage and how to test the String message in the catch block.
You are getting unit testing with mocking wrong. Here:
SimpleClass instanceObj =PowerMockito.mock(SimpleClass.class);
There is no point in mocking the class that is under test!
When you mock that class, you get a stub that has "nothing to do" with your real implementation. A "working setup" would look more like:
public void methodUnderTest(X x, ...) {
try {
x.foo();
} catch (Exception e) {
...
}
and
X mockedX = mock(X.class);
when(x.foo()).thenThrow(new WhateverException());
underTest.methodUnderTest(mockedX); ...
and then you could try to verify for example that the logger saw that expected logging call. In other words: you either use a mock to allow your code under test to do its job (with you being in control!) or to verify that some expected call took place on a mock object.
But as said: it doesn't make any sense to mock that class that you want to test. Because a mocked object doesn't know anything about the "real" implementation!
Manipulate the environment so that doesSomething() throws the Exception you want. Since we do not know what doesSomething() really does, one cannot say more.
I have a void method and I want to test it. How do I do that?
Here's the method:
public void updateCustomerTagCount() {
List<String> fileList = ImportTagJob.fetchData();
try {
for (String tag : fileList) {
Long tagNo = Long.parseLong(tag);
Customer customer = DatabaseInterface.getCustomer(tagNo);
customer.incrementNoOfTimesRecycled();
DatabaseInterface.UpdateCustomer(customer);
}
} catch(IllegalArgumentException ex) {
ex.printStackTrace();
}
}
when the method returns void, you can't test the method output. Instead, you must test what are the expected consequences of that method. For example:
public class Echo {
String x;
public static void main(String[] args){
testVoidMethod();
}
private static void testVoidMethod() {
Echo e = new Echo();
//x == null
e.voidMethod("xyz");
System.out.println("xyz".equals(e.x)); //true expected
}
private void voidMethod(String s) {
x = s;
}
}
It might not be always true, but basic concept of unit test is to check if function works as expected and properly handling errors when unexpected parameters/situation is given.
So basically unit test is against the functions that takes input parameters and return some output so we can write those unit test.
The code like yours, however, includes some other dependency (database call) and that's something you can't execute unless you write integration-test code or real database connection related one and actually that's not recommended for unit test.
So what you need to do might be introducing unit test framework, especially Mockto/Powermock or some other stuff that provides object mocking feature. With those test framework, you can simulate database operation or other function call that is going to be happening outside of your test unit code.
Also, about how do I test void function, there is nothing you can with Assert feature to compare output since it returns nothing as you mentioned.
But still, there is a way for unit test.
Just call updateCustomerTagCount() to make sure function works. Even with just calling the function, those unit test can raise your unit test coverage.
Of course for your case, you need to mock
ImportTagJob.fetchData();
and
DatabaseInterface.getCustomer(tagNo);
and have to.
Let mocked
ImportTagJob.fetchData();
throw empty list as well as non-empty list and check if your code works as you expected. Add exception handling if necessary. In your code, there are two condition depends on whether fieList are null or non-null, you need to test it.
Also, mock those objects and let them throw IllegalArgumentException where you expect it to be thrown, and write an unit test if the function throws a exception. In Junit, it should be like
#Test(expected = IllegalArgumentException.class)
public void updateCustomerTagCountTest(){
// mock the objects
xxxxx.updateCustomerTagCount();
}
That way, you can ensure that function will throw exception properly when it has to.
I'm a relative newbie to custom error handling in Java, and I'm trying to figure out how to use catch statements to deliver specific messages inside of an if statement. I wanted to get some extra sets of eyes to look at what I'm trying to do and offer feedback before I completely overthink this and overdo it too badly.
Consider:
We have a directory of hourly log files and I have an on-demand reporting job creates a concatenation of all today's log files created so far. I want to add a step that checks for the existence of a concatenated log file, deletes it then creates it if present, or just creates it if it's not present. With the code below, I'm returning an exception if, for some reason, the new file cannot be created.
try {
File file = new File (destinationPath + "todayToNowLogFile.csv");
if(file.exists())
{
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Existing file cannot be deleted.")
}
} else {
System.out.println("File will be created.");
}
}
//
catch(Exception e) {
System.err.println("Exception: ");
System.out.println("Exception: "+ e.getMessage().getClass().getName());
e.printStackTrace();
}
Now, in the case where the file cannot be deleted, I would like to display the exception preventing file deletion. First, I would need to catch that error, but then where do I put the try?
Doing something like this...
try
{
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
}
}
else {
catch(Exception eDel) {
System.err.println("Exception: ");
System.out.println("Exception: "+ eDel.getMessage().getClass().getName());
eDel.printStackTrace();
}
}
....interrupts the if...then block. I'm not sure how to insert a try...catch within an if...then. Is there a way to do this? Or does my original code catch EVERY error associated with ANY operation on the file defined in the try block, and I would need to put if...then logic in the catch block, something along the lines of this pseudocode....
catch(Exception e) {
if(exception relates to file deletion) {
"File delete exception " + exceptionMessages;
} else if(exception relates to file creation) {
"File create exception " + exceptionMessages;
} else if(other exception) {
"other exception " + exceptionMessage;
} else {
"no exceptions encountered"
}
}
What's the most appropriate way to handle this type of situation?
You should think of try/catch as any other statement. So you can put it inside any of two branches of if/then/else statement, but it have to be whole inside:
if(statement){
...
try{
...
}catch(...){
...
}
...
}else{
...
try{
...
}catch(...){
...
}
...
}
If you have to catch multiple exceptions you can achieve this by multiple catch parts:
try{
...
}catch(Exception1 e1){
...
}catch(Exception2 e2){
...
}catch(Exception3 e3){
...
}
What you want here is to create your own Exception class.
To create an exception class say you need to extend Exception class. Here's an example.
Lets say my custom exception class should be named as MyFileErrorException
So I create a new class like this -
class MyFileErrorException extends Exception {
private String message = null;
public MyFileErrorException() {
super();
}
public MyFileErrorException(String message) {
super(message);
this.message = message;
}
public MyFileErrorException(Throwable cause) {
super(cause);
}
#Override
public String toString() {
return message;
}
#Override
public String getMessage() {
return message;
}
}
Now I need to throw this exception at will. So in Your case you wantto catch File delete exception so the code will like this -
if(file.delete())
{
System.out.println(file.getName() + " is deleted!");
} else {
try{
System.out.println("Existing file cannot be deleted.")
throw new MyFileErrorException("File Could not be deleted val is null");
}catch(MyFileErrorException ex){
//Do wahtever you want to do
}
}
At first you should check if any method could throw any specific Exceptions. You could do this by looking into the Javadoc or use your favorite IDE.
If you catch Exception as the Exception class, it catches every Exception that is subclass of it.
If you want to have specific Exception handling, e.g. for an IOException like in the delete() method, you can catch every specific Exceptionclass or use multi-catch in Java 7
try {
do regular code that can throw exceptions
} catch(Exception e) {
it catches every Exception that is a subclass of Exception.
You handle every exception raised in the try block above by the same way
}
If you want to handle exceptions in different ways, e.g. print different messages, just do this like the following example:
try {
do sth
} catch (SpecificExceptionclass sec) {
do sth specific for this exception
} catch (AnotherExceptionClass aec) {
do sth else
}
Or just use Multicatch in Java 7, if you want to have same exception handling for some specific exception classes:
try {
do sth
} catch (SpecificExceptionclass | AnotherExceptionClass e) {
do sth specific for this exception
}
To achieve different Exceptions thrown in your code the methods should at least throw different exceptions. In your example with file.exists() and file.delete() there's only an IOException thrown by your code, so there is no use of specific exception handling.
I think it would be a good idea to put your code in a function that returns true or false.
1: True means the file does not exist and was created
2: False means the file exists and was deleted.
3: An exception if the file exists but cant be deleted.
Also provide a separate function to determine if the file exists or not.
Your javadoc at the top of your functions should explain the above so the caller of your functions don't have to look at their content to determine how to use them.
Note an exception is an unusual event and shouldn't be thrown to indicate the state of inserting/deleting. It should be reserved for unusual conditions which the caller normally wouldn't encounter.
A note on exceptions: If you have a large project with 1000 classes each of which has on average 20 functions, that's 20000 functions. Its not practical to pepper each function with excessive exception handling (such as checking for nulls passed in as arguments). A solution to this is to handle checked exceptions in the java language (FileIO) and let (the bulk) of unchecked exceptions ripple up the function call chain until you leave all your business logic and are about to display the results. You only catch them if you want to add additional information to the exception before rethrowing it. Example: adding the primary key value of the record of an SQLExeption being thrown so you know what record is causing problems. Just before you return to the user, log the stack trace and display a simplified message to the user (not the stack trace). The caller of your function should read its javadoc to see how to use it. If he violates your javadoc, the function may or may not throw an exception. Its his reponsibility to follow the javadoc. Last point: your project should have general coding policies for the entire project to prevent some types of exceptions from accidently being introduced by the caller such as: all functions are not epected to recieve nulls as arguments or will return a null unless specified in its javadoc. All functions will accept as arguments (or return) empty lists or empty strings correctly unless specified in their javadoc.
I want to use Mockito to test the (simplified) code below. I don't know how to tell Mockito to fail the first time, then succeed the second time.
for(int i = 1; i < 3; i++) {
String ret = myMock.doTheCall();
if("Success".equals(ret)) {
log.write("success");
} else if ( i < 3 ) {
log.write("failed, but I'll try again. attempt: " + i);
} else {
throw new FailedThreeTimesException();
}
}
I can setup the success test with:
Mockito.when(myMock).doTheCall().thenReturn("Success");
And the failure test with:
Mockito.when(myMock).doTheCall().thenReturn("you failed");
But how can I test that if it fails once (or twice) then succeeds, it's fine?
From the docs:
Sometimes we need to stub with different return value/exception for the same method call. Typical use case could be mocking iterators. Original version of Mockito did not have this feature to promote simple mocking. For example, instead of iterators one could use Iterable or simply collections. Those offer natural ways of stubbing (e.g. using real collections). In rare scenarios stubbing consecutive calls could be useful, though:
when(mock.someMethod("some arg"))
.thenThrow(new RuntimeException())
.thenReturn("foo");
//First call: throws runtime exception:
mock.someMethod("some arg");
//Second call: prints "foo"
System.out.println(mock.someMethod("some arg"));
So in your case, you'd want:
when(myMock.doTheCall())
.thenReturn("You failed")
.thenReturn("Success");
The shortest way to write what you want is
when(myMock.doTheCall()).thenReturn("Success", "you failed");
When you supply mutiple arguments to thenReturn like this, each argument will be used at most once, except for the very last argument, which is used as many times as necessary. For example, in this case, if you make the call 4 times, you'll get "Success", "you failed", "you failed", "you failed".
Since the comment that relates to this is hard to read, I'll add a formatted answer.
If you are trying to do this with a void function that just throws an exception, followed by a no behavior step, then you would do something like this:
Mockito.doThrow(new Exception("MESSAGE"))
.doNothing()
.when(mockService).method(eq());
I have a different situation, I wanted to mock a void function for the first call and run it normally at the second call.
This works for me:
Mockito.doThrow(new RuntimeException("random runtime exception"))
.doCallRealMethod()
.when(spy).someMethod(Mockito.any());
To add on to this and this answer, you can also use a loop to chain the mocked calls. This is useful if you need to mock the same thing several times, or mock in some pattern.
Eg (albeit a farfetched one):
import org.mockito.stubbing.Stubber;
Stubber stubber = doThrow(new Exception("Exception!"));
for (int i=0; i<10; i++) {
if (i%2 == 0) {
stubber.doNothing();
} else {
stubber.doThrow(new Exception("Exception"));
}
}
stubber.when(myMockObject).someMethod(anyString());
The shortest would be
doReturn("Fail", "Success").when(myMock).doTheCall();