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)
}
}
Related
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)));
I am very new to JUnit and Mockito. I am trying to write a test case using JUnit and Mockito to verify log messages. I have 2 log messages in my code.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public int run(final String[] args) throws Exception {
if (args.length != 2) {
log.info("Usage: input-path output-path");
log.info("Input and output path are required in the same sequence");
System.exit(1);
}
final String inputPath = args[0];
final String outputPath = args[1];
//some code
return 0;
}
The test case that I have written is
import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
#RunWith(MockitoJUnitRunner.class)
public class testRun {
#Mock
private Appender mockAppender;
#Before
public void setup() {LogManager.getRootLogger().addAppender(mockAppender);}
#After
public void teardown() {LogManager.getRootLogger().removeAppender(mockAppender);}
#Test
public void testValidArguments() {
//some code
Logger.getLogger(TryTest.class).info("Usage: input-path output-path");
Logger.getLogger(TryTest.class).info("Input and output path are required in the same sequence");
ArgumentCaptor<LoggingEvent> argument = ArgumentCaptor.forClass(LoggingEvent.class);
verify(appender,times(2)).doAppend(argument.capture());
assertEquals(Level.INFO, argument.getValue().getLevel());
assertEquals("Usage: input-path output-path", argument.getValue().getMessage());
assertEquals("Input and output path are required in the same sequence", argument.getValue().getMessage());
}
}
I have seen some solutions but they require to create another class which I do not want. Also while I execute the code it is taking the second value i.e., "Input and output path are required in the same sequence". The code executes fine if there is only one log message. I can put both the messages in one log.info if it cannot be solved. However, I do wish to know if there are any possible solution to this particular problem.
If you are using sl4j logger you could use ListAppender:
#Test
void test() {
Logger logger = (Logger) LogFactory.getLogger(YourClass.class);
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
logger.addAppender(listAppender);
YourClass yourClass = new YourClass();
yourClass.callYourMethodWithLogs();
List<ILoggingEvent> logsList = listAppender.list;
//make assertions with logList
}
I am writing a unit test to mock a static method in the verticle but getting ClassNotPreparedException always. I think that its only possible to mock this way if only the class is static, but i have non static class. What am i missing?
I have tried various solutions like using #rule or #PowerMockIgnore
//myVerticleTest.java
package com.blabla.me.verticles;
import static com.google.common.truth.Truth.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import io.vertx.core.Vertx;
import io.vertx.junit5.VertxTestContext;
import io.vulpx.VulpxTestBase;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.junit.runner.RunWith;
import com.blabla.me.verticles.AdditionalInformationCardVerticle;
import org.powermock.modules.junit4.rule.PowerMockRule;
import org.junit.Rule;
import com.blabla.me.verticles.st;
#RunWith(PowerMockRunner.class)
#PrepareForTest({ st.class })
#PowerMockIgnore({"org.mockito.*"})
public class myVerticleTest extends VulpxTestBase {
#Rule public PowerMockRule rule = new PowerMockRule();
private Vertx vertx;
private AdditionalInformationCardVerticle dummy;
#BeforeEach
#PrepareForTest({ st.class })
public void setUp(VertxTestContext testContext) throws Exception {
vertx = Vertx.vertx();
try {
PowerMockito.mockStatic(st.class);
PowerMockito.when(st.createClient()).thenReturn("kk");
//deploying verticle
dummy = new AdditionalInformationCardVerticle();
vertx.deployVerticle(dummy, testContext.completing());
} catch (Exception e) {
System.out.println("heyyy eroorrr : " + e);
}
}
#Test
#PrepareForTest({ st.class })
public void justnormaltest() {
cla ownclass = new cla();
String k = ownclass.createfromclass();
assertThat("kk").isEqualTo(k);
}
}
// st.java
public class st {
public static String createClient() {
return "kk";
}
}
// cla.java
public class cla {
public String createfromclass() {
return st.createClient();
}
}
I expect it to run the assertion but i always get below excpetion:
"org.powermock.api.mockito.ClassNotPreparedException:
The class com.sap.me.verticles.st not prepared for test.
To prepare this class, add class to the '#PrepareForTest' annotation.
In case if you don't use this annotation, add the annotation on class or method level. "
Here:
#PrepareForTest({ st.class })
That one goes to exactly one place: in front of your test class public class myVerticleTest.
And hint: instead of adding more and more "things" to not working code: pick any good documentation, and try to follow that to the last ; in the example code (instead of assuming that adding more and more things here or there would help).
One good starting point: the official documentation on static mocking.
And of course, the usual caveat: consider not learning about PowerMock in the first place. Instead focus on writing "easy to test" code. Far too often, people think PowerMock(ito) is the answer to their problem. When their problem in reality is their inability to write "easy to test" production code.
I want to test my code with "real" data. This data can be reused in every test in the suite since is read only data.
The loading of the data is lengthy and I would like to reuse the loaded data all through the suite (in numerous test cases). Right now I store the data as a static field. Something like this:
Context.setData(new DataReader().getData(url));
What would be a more "JUnit" way of doing this (i.e loading a big bulk of data and use it in several test cases)? I really don't like this as it has evident drawbacks. For example, who initializes the data?
What other options do I have to achieve this?
You might want to use ParametrizedTests:
import java.net.URL;
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.Parameters;
#RunWith(Parameterized.class)
public class MyTest {
#Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ new DataReader().getData(url) }
});
}
private final Data data;
public MyTest( Data data) {
this.data = data;
}
#Test
public void test1() {
//
}
#Test
public void test2() {
//
}
}
The method annotated #Parameters is invoked only once.
I was trying to mock my test suites. My test framework creates test cases by scanning test files on disk. So each time the test cases are dynamically created.
I was trying to use PowerMock. Below is the thing I tried first.
public class GroupTestcase_T extends TestSuite {
static void run() {
scan();
junit.textui.TestRunner.run(g);
}
static void scan() {
// scan disk
for (MyTestCase t : tests) { addTest(t); }
}
}
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassToStub.class)
public class MyTestCase extends TestCase {
public MyTestCase(TestInfo info) {...}
#Override
protected void setUp() throws Exception {
PowerMockito.mockStatic(ClassToStub.class);
when(ClassToStub.methodToStub())
.thenReturn(new FakeProxy());
}
#Test
public void test() throws Exception {
// Test!
}
}
Above code seems not working:
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods cannot be stubbed/verified.
2. inside when() you don't call method on mock but on some other object.
3. the parent of the mocked class is not public.
It is a limitation of the mock engine.
I traced the code and found that PowerMockRunner are not called at all.
Also I tried manually force Junit to run it with PowerMockRunner:
Result result = junit.run(new PowerMockRunner(MyTestCase.class));
PowerMockRunner has only one constructor that takes the test class as parameter. My test cases are different each time but all share the same class.
Any idea how to use PowerMock if TestCase are dynamically created?
I was using Junit 4 / PowerMock 1.5
You can generate your tests with the parameterized tests feature and apply the #PowerMockRule.
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
#RunWith(Parameterized.class)
#PrepareForTest(ClassToStub.class)
public class MyTestCase{
#Parameters
public static Collection<Object[]> scan() {
return Arrays.asList(new Object[][] {
{ new TestInfo() }, { new TestInfo() } });
}
#Rule
public PowerMockRule rule = new PowerMockRule();
public MyTestCase(TestInfo info) {
// ...
}
#Test
public void test() throws Exception {
PowerMockito.mockStatic(ClassToStub.class);
PowerMockito.when(ClassToStub.methodToStub()).thenReturn(new FakeProxy());
assertTrue(ClassToStub.methodToStub() instanceof FakeProxy);
}
}
Beware, in your example, you are mixing junit 3 (extends TestSuite, protected setUp) and junit 4 (#Test) test definitions.