Robotium Assertion Failing - java

When I run a test with Robotium, I use an assertion to verify that there is specific text on the page, but it fails. However, when I run the test without the assertion, the test passes. Why would this be?
Here is my code:
import com.jayway.android.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.Smoke;
#SuppressWarnings("unchecked")
public class ODPRobotiumTest extends ActivityInstrumentationTestCase2 {
private static final String TARGET_PACKAGE_ID = "com.gravitymobile.app.hornbill";
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.vzw.odp.LaunchActivity";
private static Class<?>launcherActivityClass;
static{
try{
launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e){
throw new RuntimeException(e);
}
}
#SuppressWarnings({ "unchecked", "deprecation" })
public ODPRobotiumTest() throws ClassNotFoundException{
super(TARGET_PACKAGE_ID, launcherActivityClass);
}
private Solo solo;
#Override
protected void setUp() throws Exception{
solo = new Solo(getInstrumentation(), getActivity());
}
#Smoke
public void testLine1(){
try {
assertTrue(solo.searchText("Easy to Find")) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Smoke
public void testLine2(){
try{
solo.searchText("Hassle-Free");
}catch(Exception e){
e.printStackTrace();
}
}
#Smoke
public void testLine3(){
solo.searchText("Trust");
}
public void testLine4(){
solo.searchText("Verizon Curated Wallpaper");
}
public void testLine5(){
solo.searchText("Taco's");
}
#Override
public void tearDown() throws Exception{
try{
solo.finalize();
}catch(Throwable e){
e.printStackTrace();
}
getActivity().finish();
super.tearDown();
}
}
The test in testLine1 is the test that fails. But like I said before, when I don't use the assertTrue, and just solo.searchTest("Easy to find"), the test will pass. I don't understand.
Thanks for any help!

If you don't assert anything then your test will pass cause nothing can fail.
Obviously the text you are searching is either missing from the screen, your configuration of the test runner is wrong or you are not even using the correct mechanisms for searching.

I just found out the content that I am trying to verify is HTML. So since Robotium doesn't work with HTML, or any other web component, it won't verify the text I'm looking for.
Thank you to all who offered help!

Related

Java try catch block not catching an exception

I was making a command to clear messages using JDA.
I made this code
public class Main {
public static JDA jda;
public static void main(String[] args) throws LoginException {
jda = JDABuilder.createDefault("OTM0ODA4NTY1ODYzMDM5MDA3.Ye1eUg.JExQxPx8UUli8YQfN7TfdbzLHqI").build();
jda.addEventListener(new CommandExecutor());
} }
public class CommandExecutor extends ListenerAdapter {
public static final String prefix = "!-";
public void onMessageReceived(MessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split(" ");
if (args[0].equalsIgnoreCase(prefix + "clear"))
new Clear(event, args);
} }
public class Clear {
public Clear(MessageReceivedEvent event, String[] args) {
try {
int numberOfMessages = Integer.parseInt(args[1]);
List<Message> messages = event.getChannel().getHistory().retrievePast(numberOfMessages + 1).complete();
event.getChannel().purgeMessages(messages);
event.getChannel().sendMessage("Messages have been deleted!").queue(m -> m.delete().queueAfter(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
} } }
The code inside the try block will clear the messages if a valid argument is passed. In case an invalid argument is passed, like a string, it should go to the catch block and print the details of the exception. However, this does not happen, and the error gets generated.
Here is the error generated
java.lang.NumberFormatException: For input string: "de"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at JDA.TelevisionBot.Commands.Clear.<init>(Clear.java:24)
at JDA.TelevisionBot.CommandExecutor.onMessageReceived(CommandExecutor.java:26)
at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:359)
at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:88)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:70)
at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:164)
at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:121)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:952)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:839)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:817)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:991)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
Thanks in advance
it is normal that you get everything you indicated since e.printStackTrace(),It's a method on Exception instances that prints the stack trace of the instance to System.err.
It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.
try {
throw new NullPointerException();
}
catch (NullPointerException e) {
System.out.println(e);
}
try {
throw new IOException();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
Calling println(e):
java.lang.NullPointerException
Calling e.printStackTrace():
java.io.IOException
at package.Test.main(Test.java:74)

Mockito to test the catch block of private method

I need to write a test to verify that when an IOException is thrown by the private method_C, Method_B returns True.
But
public final class A{
public static Boolean Method_B(){
try{
//call a private method C which throws IOException
Method_C
}
catch(final IOException e) {
return Boolean.True
}
}
private static Method_C() throws IOException {
return something;
}
What I tried:
#Test
public void testSomeExceptionOccured() throws IOException {
A Amock = mock(A.class);
doThrow(IOException.class).when(Amock.Method_C(any(),any(),any(),any()));
Boolean x = A.Method_B(some_inputs);
Assert.assertEquals(Boolean.TRUE, x);
}
I am getting compilation errors :
1.Cannot mock a final class
2. Method_C has private access in A
Any suggestions on how this can be rectified?
you are required to use finally in try catch
import java.io.*;
public class Test {
public static Boolean Method_B() {
try {
System.out.println("Main working going..");
File file = new File("./nofile.txt");
FileInputStream fis = new FileInputStream(file);
} catch (IOException e) {
// Exceptiona handling
System.out.println("No file found ");
} catch (Exception e) {
// Exceptiona handling
System.out.println(e);
} finally {
return true;
}
}
public static void main(String args[]) {
if (Test.Method_B()) {
System.out.println("Show true ans");
} else {
System.out.println("Sorry error occure");
}
}
}

Store error in excel file while performing Selenium test case with Junit

I want to store errors in excel file while performing Selenium test case over HTML fields with Junit.
My code is:
public class ExceptionHandler {
public ErrorCollector errors = new ErrorCollector();
public ErrorCollector getErrors() {
return errors;
}
public void setErrors(ErrorCollector errors) {
this.errors = errors;
}
public void execute(ExceptionHandlerTemplate template) {
System.out.println("Inside execute");
try {
System.out.println("Inside try");
template.execute();
} catch (Exception exc) {
System.out.println("Inside catch: " + exc);
errors.addError(exc);
}
}
}
This code is working fine.
But how to retrieve all the errors in variable or datatype. I am using below code:
ErrorCollector errCollector = executor.getErrors();

How do you override Play framework controller in a unit testing context?

I am creating a basic POST JSON api endoint. I would like to unit test it, and want to make sure I am doing it appropriately in the Play framework. So far I am using Guice for dependency injection and JUnit for my unit testing library.
Here is my controller code:
public class NotificationController extends Controller {
private RabbitQueueService _rabbitQueueService;
#Inject
public NotificationController(RabbitQueueService service) {
_rabbitQueueService = service;
}
#BodyParser.Of(BodyParser.Json.class)
public Result post() {
ObjectMapper mapper = new ObjectMapper();
Notification notification;
try {
JsonNode notificationJsonNode = Controller.request().body().asJson();
notification = mapper.readValue(notificationJsonNode.toString(),
Notification.class);
_rabbitQueueService.push(notification);
return Results.created(notificationJsonNode, "UTF-8");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Results.badRequest();
}
}
My RabbitQueueService code:
public class RabbitQueueService {
private Channel _channel;
private Connection _connection;
public RabbitQueueService() {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(Config.RABBITMQ_HOST);
try {
_connection = factory.newConnection();
_channel = _connection.createChannel();
_channel.queueDeclare(Config.RABBITMQ_QUEUE, false, false, false, null);
_channel.exchangeDeclare(Config.RABBITMQ_EXCHANGE, "fanout");
_channel.queueBind(Config.RABBITMQ_QUEUE, Config.RABBITMQ_EXCHANGE, "");
} catch (IOException e) {
e.printStackTrace();
}
}
public void push(Notification notification) {
try {
_channel.basicPublish(Config.RABBITMQ_EXCHANGE, "", null, notification.getBytes());
_channel.close();
_connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void pop() {
}
}
My MockQueueService code:
public class MockQueueService extends RabbitQueueService {
#Override
public void push(Notification notification) {
/* Do nothing because you know... thats what I do */
}
#Override
public void pop() {
/* Do nothing because you know... thats what I do */
}
}
and finally my current unit test code:
public class ApplicationTest {
#Test
public void addMessageToQueue() {
running(fakeApplication(), new Runnable() {
public void run() {
FakeRequest request = new FakeRequest("/POST", "/api/v1/notifications");
Notification notification = new Notification(UUID.randomUUID(),
new NotificationType(UUID.randomUUID(),
"Critical"),
"Test notification message");
try {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(notification);
JsonNode node;
node = mapper.readTree(json);
request.withJsonBody(node);
} catch (IOException e) {
e.printStackTrace();
}
route(request);
}
});
}
}
This all works fine when making a curl request to test my endpoint through play run. My main question is: how do I use the MockQueueService in my unit test? I don't see anyway to do it with fakeApplication() helper. I could instantiate it directly like
NotificationController nc = new NotificationController(new MockQueueService());
nc.post();
but the problem is I need to override the body of the play request with an appropriate request body and I think I need a FakeRequest for that.
Any help, samples, or advice would be helpful.
UPDATE
I have posted a gist example with the necessary example files. The things specifically that I did to get it working:
Setup a new GlobalUnitTest file that I passed into the fakeApplication helper
Changed NotificationController to be a singleton. This allowed me to pull in the NotificationController instance so I could check the QueueService count as part of the assertion.
FakeApplication takes a bunch of arguments that you could use to inject your new service. You could use a combination of any of these:
additionalPlugins
additionalConfiguration
withGlobal
They each let you specify some additional configuration you could use only during testing. Another thing you could do is have a separate Global object just for testing, that is used to create your controllers. The Global object is used to return your controller instance when you use # in your route definition. Then, you can create a separate application.test.conf that refers to GlobalTest that is loaded when you run play test.

TestNG handling external system dependency, clarification needed

What changes do i need to make to the following please?
I'd like make sure that testInsert method to only run when testInternalAccess passes and testInternalAccess not count as a failure.
#Test
public void testInternalAccess() {
URL url = null;
try {
url = new URL("http://internalpage");
InputStream is = url.openConnection().getInputStream();
} catch (Exception e) {
fail();
}
}
#Test(groups = "database", dependsOnMethods = "testInternalAccess")
public void testInsert() {
// some code
}
In the above example:
testInternalAccess runs, fails and being reported as a failed test
testInsert runs and fails
Or, using creator's of TestNG example
#Test
public serverStartedOk() {}
#Test(dependsOnMethods = { "serverStartedOk" })
public method1() {}
How will method1 know whether server actually started ok? How will serverstartedOk communicate to the world it's state?
Based on the discussion we had above, following is the brief summary.
As you wish to run the method testinternalAcecess before you run all the tests in the class use #BeforeClass
#BeforeSuite
public void testInternalAccess() {
URL url = null;
try {
url = new URL("http://internalpage");
InputStream is = url.openConnection().getInputStream();
} catch (Exception e) {
fail();
}
}
The method runs only once and before all tests run in the suite! And you test method would be some thing as below
#Test(groups = "database")
public void testInsert() {
// some code
}
Bingo and this would work!

Categories