How to priortized the test cases in maven run? - maven

I have 3 test cases i.e. 1 2 3. How will i give priority as 2 1 3 while executing maven command.

I assume you want to do it because you need some prerequisition prior the test can be run. You can do it by #Before Annotation prior the actual testcase, or you can call other tests from the test method.
Say, testClient() test will test and verify that new client can be added to the system. Then you can do this:
#Test
public void testWithdrawal(){
testClient(); // i need client existing before the test can be run
// ... do something else
}
In that case you have assured that prerequisites are fullfilled and dont have to worry much about the testcases order
EDIT
I think I understand your needs, because I am in quite similar situation. How I solved it:
For create I have special class, which can create me a data and return needed data. So, i have something like:
#Test
public void testShare(){
CreateTests create = new CreateTests; //This will just initialize the object
create.testCreate(); // this method can contain steps needed to create
String justCreatedEntity = create.getEntity(); // just example how you can use the just created entity in further tests
}
And my class to solve the create is something like this
public class CreateTests{
private static String entity; //static because i dont want it to be flushed when test ends
public void testCreate() throws Exception{
WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(driver, "baseURL");
selenium.... // All the selenium stuff
setEntity(selenium.getText("id=mainForm.createdentity"));
}
public void setEntity(String ent){
this.entity = ent;
}
public String getEntity(){
return entity;
}
Its just an outline - but basically, I have these "crucial" entities as standalone objects, called by the test class. Inside test, i verify everything throgh getters. Like:
Assert.assertNotNull(create.getAuctionID(),"New Entity is NULL!" );

You can run mvn test with options to specify a single test, or multiple tests. The order they are run in is the order specified on the command line.
Reference is here: http://maven.apache.org/plugins/maven-surefire-plugin/examples/single-test.html
Note that Java suggests that the good unit testing practice of tests not requiring to be run in order and test to not rely on each other:
http://java.sun.com/developer/Books/javaprogramming/ant/ant_chap04.pdf

Related

How to perform Tests for DTOs?

I am creating a class to store the tests of all DTO classes, but currently I only manage to cover 10% of the coverage. I need to know how to do the #Tests for the DTOs.
My DTO:
#Data
#NoArgsConstructor
public class ActivityDTO {
private Integer id;
private Integer version;
#JsonProperty("working_days")
private MonthWorkingDays workingDays;
}
My Test class:
#Test
public void ActivityDTOTest() {
ActivityDTO obj = BeanBuilder.builder(ActivityDTO.class).createRandomBean();
}
This is the coverage:
My problem: I don't know how to test the DTO class, I'm testing with assertEquals but I don't know how to apply it. Can someone put what the Test class would be like for this DTO class and thus be able to replicate it in the other classes?
This might be subjective, but in general you should not test to increase the coverage, instead you should always think "what exactly" the test checks.
In a nutshell, there can be two things to be tested:
A state of the object
A behavior
Most of the tests usually (arguably, but at least this is what I usually do in my project) tend to check the behavior that is technically implemented as a business logic inside the methods.
Since the DTOs do not really have methods with the logic, you can only test the state of the object.
Another idea: there is no point in checking the code that you haven't written. So yes, following your example in the question, putting lombok annotations will generate some getters/setters/constructors - but its not your code, the proper handling of these annotations was supposed to be checked by lombok team itself.
What you can do if you really want to test DTOs is generate the one with some default values and check that its internal state indeed matches the expected. Something like this:
public class ActivityDTO {
private Integer id;
private Integer version;
// getters / setters maybe
}
#Test
public void test_state_is_correct() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest.getId(), equalTo(SAMPLE_ID));
assertThat(underTest.getVersion(), equalTo(SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_same_values() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, equalTo(new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_different_id() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, not(equalTo(new ActivityDTO(ANOTHER_SAMPLE_ID, SAMPLE_VERSION));
}
#Test
public void test_equals_two_objects_with_different_version() {
ActivityDTO underTest = new ActivityDTO(SAMPLE_ID, SAMPLE_VERSION);
assertThat(underTest, not(equalTo(new ActivityDTO(SAMPLE_ID, ANOTHER_SAMPLE_VERSION));
}
... test for toString()... and hashCode maybe, etc.
This will make the coverage tool happy for sure, but the real question is will it make your code better (more robust and less buggy, etc)?
One thing for sure - these tests are time consuming, boring, and probably give less value to the project. To overcome the frustration of the programmers who absolutely need to write these tests there are even tools for automatic testing of these simple java beans (DTO can be viewed as a java bean), to name a few:
https://github.com/codebox/javabean-tester
https://code.google.com/archive/p/junit-javabean-runner/
http://javabeantester.sourceforge.net/
Now the entirely different story is if you test the behavior of some service or DAO that, say, generates the DTO - these tests whether they're unit or integration tests are really needed. They'll also increase the coverage of the project (and maybe even will cover the code of the DTO, although its not their primary goal), but I would suggest to start writing these tests first.
I don't know what is the best practice but AFAIK you should exclude the DTO classes from the configuration and you don't have to write unit test for them.
If you are using JaCoCo plugin, you better check this out: How to exclude certain classes from being included in the code coverage? (Java)

#SQL one time per class

I'm writing some integration test using spring framework. I have different SQL scripts for different integration test classes. Something like this:
#ContextConfiguration(classes = ...)
#Sql("classpath:sportCenter-test.sql")
public class SportCenterResourceIT {
...
}
Everything works perfectly except for the fact that the SQL script is executed before each test, instead of one time per class. I have already searched for some time the spring documentation but I was not able to find something related to such an option.
Could anybody give me an hint?
I use this way to resolve the problem:
#DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
#Sql("classpath:sql/DataForRouteTesting.sql")
public class MyTest {}
Scripts are executed every time, but there are not conflict primary key.
Adding the org.springframework.transaction.annotation.Transactional annotation at the class level will prevent any changes from #Sql scripts from persisting between tests. So your code becomes:
#ContextConfiguration(classes = ...)
#Sql("classpath:sportCenter-test.sql")
#Transactional
public class SportCenterResourceIT {
...
}
This combination will result in the following:
Your #Sql script will run before each test
The test itself will run
Any database changes from steps 1 or 2 will be reverted at the end of each test
If we want to execute sql script one time per class, we can execute the script in setup method and set flag to true once the script is executed for one method so it does not execute again.
`
#Autowired
private DataSource database;
private static boolean dataLoaded = false;
#Before
public void setup() throws SQLException {
if(!dataLoaded) {
try (Connection con = database.getConnection()) {
ScriptUtils.executeSqlScript(con, new ClassPathResource("path_to_script.sql"));
dataLoaded = true;
}
}
}`
I solved my problem by putting the sql script in the src/test/resources folder with the name data.sql. This file is executed once at startup of each integration test. For this to work, you need to remove the #Sql annotation.
You can create an empty static method annotated with #BeforeAll and #Sql("classpath:sportCenter-test.sql")
#BeforeAll
#Sql("classpath:sportCenter-test.sql")
public static void initSql() {
}

Multiple runwith for a junit test class

Does any one know how to tackle this.
#RunWith(SpringJUnit4ClassRunner.class)
#RunWith(Parametrized.class)
#ContextConfiguration("/META-INF/blah-spring-test.xml")
public class BlahTest
..
so i want to have a spring nature test and at the same time want to have it parameterized to avoid code duplication ...
You can't use two runners as it noted in the commented post. You should use the Parameterized runner as use Spring's TestContextManager to load the Spring context.
#Before
public void before() throws Exception {
new TestContextManager(getClass()).prepareTestInstance(this);
}
As of Spring Framework 4.2, JUnit-based integration tests can now be executed with JUnit rules instead of the SpringJUnit4ClassRunner. This allows Spring-based integration tests to be run with alternative runners like JUnit’s Parameterized or third-party runners such as the MockitoJUnitRunner. See more details on spring doc.
Building upon John B's answer using TestContextManager, one can also call beforeTestMethod() and afterTestMethod() on it to better simulate SpringJUnit4ClassRunner's behaviour (for instance loading database with #Sql).
These methods require a Method parameter, so one can for instance take advantage of JUnit4's TestName rule to get the current test method's name and then retrieving it by reflection.
private static TestContextManager springTestContext
= new TestContextManager(BlahTest.class);
#Rule
public TestName testName = new TestName();
#Before
public void before() throws Exception {
springTestContext.prepareTestInstance(this);
springTestContext.beforeTestMethod(this,
getClass().getMethod(testName.getMethodName()));
}
#After
public void after() throws Exception {
springTestContext.afterTestMethod(this,
getClass().getMethod(testName.getMethodName()), null);
}

How to execute #Sql before a #Before method

I'm trying to combine the follow annotations:
org.springframework.test.context.jdbc.Sql
and
org.junit.Before
Like the follow code:
#Test
#Sql(scripts = "dml-parametro.sql")
public void testData(){
Iterable<Parametro> parametros = parametroService.findAll();
List<Parametro> parametrosList = Lists.newArrayList(parametros);
Assert.assertThat(parametrosList.size(), Is.is(1));
}
#Before
public void beforeMethod() {
JdbcTestUtils.deleteFromTables(jdbcTemplate, "PARAMETRO");
}
The code in the method #Before is running after then the script "dml-parametro.sql" in the #Sql annotation.
Is it right to do this?
For solution this, I'm using #After in place than #Before, but I'd like to cdelete tables before the test execution, not after.
I wouldn't like to use #SqlConfig. I'm not using transacional scope on test level, so i need to clean my tables in every test method. If every test method need to clean tables, i would like to do this in #Before method. I wouldn't like to do this in every test method with #SqlConfig. I think the behavior of #Sql to be execute before than #Before is wrong.
By default, any SQL scripts executed via #Sql will be executed before any #Before methods. So the behavior you are experiencing is correct, but you can change the execution phase via the executionPhase attribute in #Sql (see example below).
If you want to execute multiple scripts, that is also possible via #Sql.
So if you have a clean-up script named clean-parametro.sql that deletes from the PARAMETRO table, you could annotate your test method like the following (instead of invoking JdbcTestUtils.deleteFromTables() in your #Before method).
#Test
#Sql({"dml-parametro.sql", "clean-parametro.sql"})
public void test() { /* ... */ }
Of course, if dml-parametro.sql inserts values into the PARAMETRO table, then it likely does not make sense to immediately delete those values in the clean-up script.
Please note that #Sql and #SqlConfig provide multiple levels of configuration for script execution.
For example, if you want to create tables before your test and clean up after your test, you could do something like this on Java 8:
#Test
#Sql("create-tables.sql")
#Sql(scripts = "clean-up.sql", executionPhase = AFTER_TEST_METHOD)
public void test() { /* ... */ }
Or use #SqlGroup as a container on Java 6 or Java 7:
#Test
#SqlGroup({
#Sql("create-tables.sql"),
#Sql(scripts = "clean-up.sql", executionPhase = AFTER_TEST_METHOD)
})
public void test() { /* ... */ }
If your tests are #Transactional and you'd like to clean up committed database state, you can instruct Spring to execute your clean-up SQL script in a new transaction like this:
#Test
#Sql("insert-test-data.sql")
#Sql(
scripts = "clean-up.sql",
executionPhase = AFTER_TEST_METHOD,
config = #SqlConfig(transactionMode = ISOLATED)
)
public void test() { /* ... */ }
I hope this clarifies things for you!
Cheers,
Sam (author of the Spring TestContext Framework)
Notes:
AFTER_TEST_METHOD is statically imported from ExecutionPhase
ISOLATED is statically imported from TransactionMode

Retrieve and Modify the #ConfigurationContext programmatically via code?

How to Retrieve and Modify the #ConfigurationContext programmatically via code ?
I have a default configuration where it contains valid xml files.
Now i need to add an invalid configuration for a particular test case and test the same.
How to override, retrieve and modify the #ConfigurationContext programmatically via code ?
Thanks in advance,
Kathir
Disclaimer: I am assuming you are using JUnit since you didn't comment differently in your reply to my comment.
I think what you are trying to do does not make lot of sense, in my opinion it is still better to create a dedicated test class for your not-working configuration in order to be able to do more than one test. However:
annotate your test class with #RunWith(SpringJUnit4ClassRunner.class) and #ContextConfiguration(locations = {"classpath:/working-context.xml"}). In this way you can retrieve the configuration context in two ways: first, you can simply declare a field #Inject ApplicationContext context which will contain the working context. Or, you make your test class implements ApplicationContextAware and then write a public void setApplicationContext (ApplicationContext applicationContext). I would go for the second one since it will come in hand for changing the context programmatically.
write a not-working-context.xml and place it in your classpath
in the test method you want to fail, reload the application context with context = setApplicationContext(new ClassPathXmlApplicationContext("not-working-context.xml")); and test all the errors you like.
though it is not good practice to stand on test case order, make sure your failing test will be executed as the last one (tests are executing alphabetically) so you don't have to reload the working context in the other tests.
In the end your test class will look like:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:/working-context.xml"})
public class TestClass implements ApplicationContextAware {
private ApplicationContext context;
public void setApplicationContext(ApplicationContext context){
this.context = context;
}
//Other tests
#Test
public void zFailingTest() {
context = setApplicationContext(new ClassPathXmlApplicationContext("not-working-context.xml"));
//your test
}
}

Resources