Junit testing for Rest crud operation - java

I have a 4 rest api for crud operations. So when I am writing a junit for those rest api's,
1.Should I write a single test case which do all the crud operation or it should be different test cases for each rest api?
2.I'f I write separate test case, then is it ok to use the record created in create test case in the update or get test cases. In that case there is a dependency between each test cases.
3.How can I enforce to Junit to run test cases on implement order given that my test case method are not in alphabetical order.

DISCLAIMER: there is no "one right answer".
SUGGESTIONS:
If at all possible, you should code your JUnit tests so that each runs independently. There should not be any "ordering" dependency between any specific test.
All things being equal, I would recommend a different test for each operation.
I would also recommend liberal use of fixtures, or a Mock object library like Mockito.
Failing all else, Junit 4.11 and higher offers #FixMethodOrder annotation

Related

Whether Cucumber JUnit can be used to UnitTest Spring?

Whether Cucumber JUnit along with Mockito can be used to test Spring? Wherever I see it's either only using Mockito JUnit or SpringJUnit Runner and have never seen UnitTestCases with Cucumber JUnit+Mockito for Spring..
Whether that is really possible?
The problems those technologies aim to solve is very different.
In an unit test you are trying to test the smallest possible piece of your software (normally a single class) and you abstract (mock) everything else. This is a very good use case for Mockito.
JUnit runner and SpringTestRunner are the engines running your tests, they will take care of configuration and class loading for you.
Cucumber allows you to write tests in a language that is more business friendly (Gherkin) and your goal here is to cover business user cases and test your entire application to see if it solves your problems.
For example: lets say you have an application that gives you the tax value to be added to a check.
You can have a class that given a product connects to an external service and returns the tax rate for that item. To test that class you don't hit the real service, you use Mockito to create a mock service where you can control the returned values. Here you are testing the ability of your class to make requests to external services.
Now you can have a business requirement that says that if you have multiple items in your check only some of them are taxed. Here you write a cucumber test and send the request to your application. Here you are testing the full logic of your app, recognizing items, getting taxes for the right ones and so on.
Thats a case where you will have cucumber and Mockito running on the same app. And who is running them? Most likely the JUnit runner.

How can I run a test class only if another test was passed?

I am doing some Junit testing and I need to know how to run a Test class only if a specific test from another class was passed.
There is 'Categories' feature in JUnit. (See: https://github.com/junit-team/junit/wiki/Categories)
This question has already been replied in this post
In the #Before function you need to retreive a runtime value from your system and check that it matches your requirement. Everything will stop if it doesn't
IMHO, This is bad practice, even in a well-designed Integration test-suite. I would encourage you to rethink your overall test class design.
If these tests are truly meant to be unit tests, they should be atomic and independent of each other. See this post for a good read.
Having said that, I have often used JUnit 4.x to build & run rather large suites of Integration tests (backend functional tests that test a RESTful services responses). If this is your use case, I recommend restructuring your tests such that you never have one test in TestClassA depend on a test in TestClassB. That is a bad idea, as it will making your tests more fragile. And difficult for other devs to understand the intention of your tests, taken together as a whole.
When I have found that I have dependencies across multiple test classes, I have factored out a "test-superclass" to both test classes and do my "setup work" in that superclass. Or you can factor out a utility class that contains static methods for creating somewhat complex test conditions to start with.
But, even using JUnit as a vehicle to run these kind of "integration" tests should be done with caution and careful intent.

Java spring junit writing tests that persist data

I have written tests in the past using in memory databses.
What i wanted to know was is it possible to write tests in spring, junit, java, using in memory DB and the data is not rolledback after each test but kept in the db.
Basically whereby the tests are dependant on each other?
any ideas?
Rollbacking db changes or not is up to you.
But unit test should be independent from each other.
Small extract from a recent DZone article on the subject:
Make each test independent to all the others
Do not make chain of unit test cases. It will prevent you to identify the root cause of test case failures and you will have to
debug the code. Also, it creates dependency, means if you have to
change one test case then you need to make changes in multiple
testcases unnecessarily.
Try to use #Before and #After methods to setup per-requisites if any for all your test cases. If you need to multiple things to support
different test cases in #Before or #After, then consider creating new
Test class.
Your tests should be independent.
But if you want I guess you can try the #Rollback annotation.
I have not tried but have seen in the doc spec while doing transactions.

Junit and EasyMock understanding clarifications

Still Now I am using JUnit, I came across EasyMock, I am understanding both are for the same purpose.
Is my understanding correct?
What are the advantages does EasyMock has over the Junit?
Which one is easier to configure?
Does EasyMock has any limitations?
Please help me to learn
When I explain unit testing I like to describe them as a list of phases:
Test Setup : Define and Create all the Data and Objects you need for the tests
Expectations : Say what methods and parameters you expect to be executed during the test
Test : The actual behavior/method call you want to test
Assertions : Statements that make sure the outcome of the test were successful
Test Tear down : Destroy any side effects that occurred during the test
jUnit is a Unit Testing Framework and provides all but the Expectations phase of testing. Alternatives in the Java space include:
TestNG
jtest
jBehave (sort of)
jDave (sort of)
Other Language equivalents include:
PHP - phpUnit
Ruby - Test::Unit
Flash - FlexUnit
The concept of mocking is what added the new phase of Expectations, and since jUnit saw most of it's major development prior to the mocking movement, those features were not incorporated into the core, and a set of tools to fill that gap in the java space have opened up. Those libraries include
EasyMock
jMock
jMockIt
All of these libraries are compliments to any of the above Unit Testing frameworks I listed, including jUnit. They add the ability to define mock objects. Mock objects get "expectations" assigned to them, which are then asserted in the Assertions phase. Each Mock library accomplishes this slightly differently, but the major models are
Record Replay - EasyMock
Expectations - jMock, jMockIt
I personally am a fan of the Expectations approach, which is more declarative, and less error prone, because it requires less methods to be called by the implementor, but that is a stylistic preference not a technical one.
Other Languages (since they came to the unit testing world later than java) don't have this seperation for the most part. The Unit Testing Library and Mock Library are one and the same. This is the case in phpunit, rspec. I imagine jUnit will not be incorporating this natively any time soon, since there is already such a rich set of alternative mock libraries available.
They are not the same thing
JUnit is a xUnit testing framework - It has a test runner that loops over your test suites, executes each automated unit test and records the results.
EasyMock is a mock-object framework. It is used to replace hard to setup collaborators with dummies/fakes/mocks to help focus on the behavior I intend to test.
e.g. if my SUT.AuditCustomers() calls DAO.GetCustomer(databasePath), in my test I'd like to focus on the method AuditCustomers(), so I'd use a mockDAO which does not read the customers from the database instead returns known/hardcoded Customer objects to easy testing. This also has the benefit that any bug in GetCustomer does not fail the test for AuditCustomers()
I am not sure but I think JUnit and EasyMock instead of being exclusive to each other are supposed to work in tandem together.
JUnit idea is to test a given method and therefore you want to inject dummy instances of other classes into it, to ensure the JUnit test is not dependent on other class methods at all. This purpose of providing mock objects in JUnit is served by EasyMock and other similar mock object creators. Similar idea is used when using spring to inject dummy implementations into JUnit.
EasyMock seems to be promising, but you should evaluate if Spring or some other proxy object generators fit your scenario.

Data-driven tests with jUnit

What do you use for writing data-driven tests in jUnit?
(My definition of) a data-driven test is a test that reads data from some external source (file, database, ...), executes one test per line/file/whatever, and displays the results in a test runner as if you had separate tests - the result of each run is displayed separately, not in one huge aggregate.
In JUnit4 you can use the Parameterized testrunner to do data driven tests.
It's not terribly well documented, but the basic idea is to create a static method (annotated with #Parameters) that returns a Collection of Object arrays. Each of these arrays are used as the arguments for the test class constructor, and then the usual test methods can be run using fields set in the constructor.
You can write code to read and parse an external text file in the #Parameters method (or get data from another external source), and then you'd be able to add new tests by editing this file without recompiling the tests.
This is where TestNG, with its #DataSource, shines. That's one reason why I prefer it to JUnit. The others are dependencies and parallel threaded tests.
I use an in-memory database such as hsqldb so that I can either pre-populate the database with a "production-style" set of data or I can start with an empty hsqldb database and populate it with rows that I need to perform my testing. On top of that I will write my tests using JUnit and Mockito.
I use combination of dbUnit, jMock and jUnit 4. Then you can ether run it as suite or separately
You are better off extending TestCase with a DataDrivenTestCase that suits your needs.
Here is working example:
http://mrlalonde.blogspot.ca/2012/08/data-driven-tests-with-junit.html
Unlike parameterized tests, it allows for nicely named test cases.
I'm with #DroidIn.net, that is exactly what I am doing, however to answer your question literally "and displays the results in a test runner as if you had separate tests," you have to look at the JUnit4 Parameterized runner. DBUnit doesn't do that. If you have to do a lot of this, honestly TestNG is more flexible, but you can absolutely get it done in JUnit.
You can also look at the JUnit Theories runner, but my recollection is that it isn't great for data driven datasets, which kind of makes sense because JUnit isn't about working with large amounts of external data.
Even though this is quite an old topic, i still thought of contributing my share.
I feel JUnit's support for data driven testing is to less and too unfriendly. for eg. in order to use parameterized, we need to write our constructor. With Theories runner we do not have control over the set of test data that is passed to the test method.
There are more drawbacks as identified in this blog post series: http://www.kumaranuj.com/2012/08/junits-parameterized-runner-and-data.html
There is now a comprehensive solution coming along pretty nicely in the form of EasyTest which is a a framework extended out of JUnit and is meant to give a lot of functionality to its users. Its primary focus is to perform Data Driven Testing using JUnit, although you are not required to actually depend on JUnit anymore. Here is the github project for refernece: https://github.com/anujgandharv/easytest
If anyone is interested in contributing their thoughts/code/suggestions then this is the time. You can simply go to the github repository and create issues.
Typically data driven tests use a small testable component to handle the data. (File reading object, or mock objects) For databases, and resources outside of the application mocks are used to similate other systems. (Web services, and databases etc). Typically I see is that there are external data files that handle the data and the output. This way the data file can be added to the VCS.
We currently have a props file with our ID numbers in it. This is horribly brittle, but is easy to get something going. Our plan is to initially have these ID numbers overridable by -D properties in our ant builds.
Our environment uses a legacy DB with horribly intertwined data that is not loadable before a run (e.g. by dbUnit). Eventually we would like to get to where a unit test would query the DB to find an ID with the property under test, then use that ID in the unit test. It would be slow and is more properly called integration testing, not "unit testing", but we would be testing against real data to avoid the situation where our app runs perfectly against test data but fails with real data.
Some tests will lend themselves to being interface driven.
If the database/file reads are retrieved by an interface call then simply get your unit test to implement the interface and the unit test class can return whatever data you want.

Categories