I've been trying to transfer my restassured tests using testng over to cucumber and I've almost cracked it however the assertion has thrown me a little bit. This issue I have is the body in my assertion is throwing this error.
java: cannot find symbol
symbol: method body(java.lang.String,org.hamcrest.Matcher<java.lang.String>)
location: class stepdefs.articlesCucumberTests
Here is my current working tests.
import static io.restassured.RestAssured.*;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import org.testng.annotations.Test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
#SuppressWarnings("unchecked")
public class articlesTestNg extends enablers {
//Checks articles individual ID's.
#Test(dataProvider = "getId")
public void TestAllArticles(String articlesId) {
given().
given().log().all().and().
pathParam("id", articlesId).
when().
get(singleArticles).
then().
assertThat().
statusCode(200).
body(("id"), equalTo(articlesId));
}
//Checks the whole content of the json file using an expected outcome in the project structure.
#Test
public void GetArticlesJson() {
JsonPath expectedJson = new JsonPath(new File(pathJson));
given().
when().
get(allArticles).
then().
assertThat().
statusCode(200).
and().
body("", hasItem(expectedJson.getMap("")));
}
Here is my so far attempt at the cucmber tests in the I will receive an individual article the body is throwing the error. Is there a better way to do this?
package stepdefs;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Assertions;
import org.testng.Assert;
import org.testng.annotations.Test;
import skySportsPages.enablers;
import static io.restassured.RestAssured.baseURI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
public class articlesCucumberTests extends enablers {
private Response response;
#Test
#Given("I have a set of articles containing individual ID's")
public void i_have_a_set_of_articles_containing_individual_id_s() {
RestAssured.baseURI = singleArticles;
System.out.println(baseURI);
}
#Test(dataProvider = "getId")
#When("I get an the article ID")
public void i_get_an_the_article_id(String articlesId) {
given().
given().log().all().and().
pathParam("id", articlesId).
when().
get(singleArticles);
}
#Test
#Then("I will receive an individual article")
public void i_will_receive_an_individual_article(String articlesId) {
Assert.assertEquals(body(("id"), equalTo(articlesId)));
}
#Test
#Given("I have a set of articles")
public void i_have_a_set_of_articles(String articlesId) {
}
#Test
#When("I get the list of articles")
public void i_get_the_list_of_articles() {
}
#Test
#Then("It will match the json file")
public void it_will_match_the_json_file() {
}
}
No, I think we don't use #Test annotation in cucumber step. You should check out at toolqa for more tutorials.
Error is here because Assert.assertEquals should have two parameters, in your case you have only one body(("id"), equalTo(articlesId)) that may return boolean, so check first what you have just performing:
#Test
#Then("I will receive an individual article")
public void i_will_receive_an_individual_article(String articlesId) {
body(("id"), equalTo(articlesId));
}
And then try to change to:
Assert.assertTrue(body(("id"), equalTo(articlesId)));
Related
I've just started using Java today and have created some tests but I want to use JavascriptExecutor to be able to report tests passing or failing to Sauce Labs. I've imported the library I believe I need but it doesn't recognise the import either way. I believe I am doing it correctly but evidently I'm not and would like some help to understand where I'm going wrong.
My code looks like this:
package tests;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.RegisterExtension;
import pageobjects.Login;
import org.junit.jupiter.api.extension.TestWatcher;
import org.openqa.selenium.JavascriptExecutor;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TestLogin extends BaseTest {
private Login login;
#RegisterExtension
public SauceTestWatcher watcher = new SauceTestWatcher();
#Before
public void setUp() {
login = new Login(driver);
}
#Test
public void succeeded() {
login.with("tomsmith", "SuperSecretPassword!");
assertTrue("success message not present",
login.successMessagePresent());
}
#Test
public void failed() {
login.with("tomsmith", "bad password");
assertTrue("failure message wasn't present after providing bogus credentials",
login.failureMessagePresent());
}
#Test
public void failed2() {
login.with("tomsmith", "bad password");
assertFalse("success message was present after providing bogus credentials",
login.successMessagePresent());
}
public class SauceTestWatcher implements TestWatcher {
#Override
public void testSuccessful(ExtensionContext context) {
driver.executeScript("sauce:job-result=passed");
driver.quit();
}
#Override
public void testFailed(ExtensionContext context, Throwable cause) {
driver.executeScript("sauce:job-result=failed");
driver.quit();
}
}
}
I use import org.openqa.selenium.JavascriptExecutor; to get and I'm referencing it at the bottom: driver.executeScript("sauce:job-result=failed"); or the passed just above it.
Invalidating cache and restarting resolved. Also changed the code slightly.
((JavascriptExecutor) driver).executeScript("sauce:job-result=passed");
This resolved my issue
I have a method in junit that is responsible for checking errors in a very large file (more than 200k lines).
I would like to know if there is any variable in which Junit put the lines that have the file and the line in which he is doing the test, in order to use them.
I know that in testCase() there is a private variable that contains the line on which the test is running, but I can not access it, any advice?
The code used is like this:
#Test
#FileParameters("fileparameter")
public void testFechaAlteracionExpedienteFS(String line) {
String TEST= 'test';
assertThat(TEST).overridingErrorMessage("Expected: <%s> - but it was: <%s>", line, TEST, ConstantesSql.getConsulta()).isEqualTo(line);
I'm using Maven with Junit 4+.
Why not use simple java api?
Documentation: http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-
Use a parameterized test:
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
#RunWith(Parameterized.class)
public class ParameterizedTest {
#Parameter(0)
public File file;
#Parameter(1)
public String line;
#Parameters(name = "{index}: {0}")
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] { { new File("/path/to/file1"), "line1" },
{ new File("/path/to/file2"), "line2" },
{ new File("/path/to/file3"), "line3" } });
}
#Test
public void test() {
// Your test code here (read file and line variables)
}
}
I am using PowerMockito and this is my test:
import com.PowerMockitoProduction;
import org.apache.commons.httpclient.HttpClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(HttpClient.class)
public class PowerMockitoTest {
#Test(expected = UnsupportedOperationException.class)
public void test() throws Exception {
PowerMockito.whenNew(HttpClient.class).withNoArguments().thenThrow(new UnsupportedOperationException());
new PowerMockitoProduction().createClient();
}
}
This test is failing.
java.lang.AssertionError: Expected exception: java.lang.UnsupportedOperationException
Here's what PowerMockitoProduction does:
package com;
import org.apache.commons.httpclient.HttpClient;
public class PowerMockitoProduction {
public void createClient() {
HttpClient client = new HttpClient();
System.out.println(client);
}
}
I expect this code to create a mock HttpClient based on this line in my test:
PowerMockito.whenNew(HttpClient.class).withNoArguments().thenThrow(new UnsupportedOperationException());
But it doesn't seem to be effecting my production code. What am I doing wrong?
I figured out what I was doing wrong. I need to change:
#PrepareForTest(HttpClient.class)
to
#PrepareForTest(PowerMockitoProduction.class)
I have following class :
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import server.testing.WebTest;
public class CampaignControllerTest extends WebTest {
#Autowired
CampaignController campaignController;
private MockMvc mockMvc;
#Before
public void mySetup() throws Exception {
this.mockMvc = MockMvcBuilders.standaloneSetup(campaignController).build();
}
#Test
public void testStatus() throws Exception{
mockMvc.perform(get("/01/status")).andExpect((status().isOk()));
}
}
And I get following error : Failed tests: testStatus(cz.coffeeexperts.feedback.server.web.controller.CampaignControllerTest): Status expected:<200> but was:<404>
404 is (usually) thrown, if you type wrong address.
This is my CampaingController :
#Controller
#RequestMapping(value = "/api")
public class CampaignController {
#RequestMapping(value = "/01/status", method = RequestMethod.GET)
#ResponseBody
public ServerStatusJSON getStatus() {
return new ServerStatusJSON(activeCampaignService.getActiveCampaign().getIdCampaign());
}
}
This address I try to test works fine when I deploy this application on tomcat. There should not be problem inside that method, because in that case it returns 500 internal error, not 404.
Am I doing something wrong?
Try mockMvc.perform(get("/api/01/status")).andExpect((status().isOk()));
I am trying to write a TestNg test using Powermock to mock a static function call.
My test code is :
import static org.easymock.EasyMock.expect;
import static org.powermock.api.easymock.PowerMock.mockStatic;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.verify;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.Assert;
import org.testng.annotations.Test;
#PrepareForTest(TestStringProvider.class)
public class TryPowerMock {
public void test() {
String string = TestStringProvider.getString();
Assert.assertEquals(string, "testString");
}
#Test
public void tryPowerMock() {
mockStatic(TestStringProvider.class);
expect(TestStringProvider.getString()).andReturn("testString");
replay(TestStringProvider.class);
test();
verify(TestStringProvider.class);
}
}
Class with static function:
public class TestStringProvider {
public static String getString(){
return "WHY AM I CALLED, I AM SUPPOSED TO BE MOCKED";
}
}
Running this test gives me following exception,
FAILED: tryPowerMock
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.EasyMock.getControlForLastCall(EasyMock.java:520)
at org.easymock.EasyMock.expect(EasyMock.java:498)
at com.archit.learn.powermock.TryPowerMock.tryPowerMock(TryPowerMock.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Explored some more and found the solution myself.
I had to extend my unit test from class PowerMockTestCase