Which opensource java or .net project has best unit test coverage? - java

I want to dive more into the unit testing concepts. An open source project which will illustrate the best practices in unit testing is required.

I work on CruiseControl (original Java version) and I think it is worth considering as a source of study for a few reasons:
Lots of unit tests. Certainly not the highest coverage but there are plenty to look at.
Diverse technology. There are pojos, tag libs, velocity macros, spring, etc.
Uneven quality of unit tests. Because we take contributions from outside the quality and throughness of unit tests vary. The core classes are very well tested. Lots of the contributions are untested or poorly tested. Consider the poorly tested ones as "an exercise left for the reader". ;)
Maybe the best reason: You can ask questions about the tests on developer mailing list. In the best case you could even end up writing tests for some of the untested areas and get coaching on your efforts.

The source code for NUnit (.NET unit testing software) would be worth a look.

You might be able to get hold of the Spring Framework source code, the team behind it advocates test driven development and the framework is available for both Java .net.

Related

Java program to prove Test Driven Development

I have to write a java program, and prove that i used TDD while writing the program.
I need to find some method to prove the use of Test Driven Development, meaning to somehow log the failures of some tests, then log writing of some code, then log the tests passing, and so on.
Any help is welcome.
Also any java related TDD documentation sources would help!
Thank you!
Personally, I disagree that you should judge developers based on whether they used TDD or not. It’s like judging a Striker by how skilful they are in dribbling. The only thing that matters is whether they helped their team to win or scored enough goals. As with dribbling, TDD is a mean, not a destination. As it is not a goal on its own, there is no need to test whether you have used TDD while developing you app or not. You decide to use TDD if you believe that this helps you with creating a maintainable, tested and future-proof solution and this should be your goal. If you can achieve the same results using some other technique, the results should speak for themselves. Having said that, TDD is by far the most popular and proven technique to achieve above mentioned qualities. Therefore, you can test if someone skilfully used TDD (or equally efficient technique) by measuring the quality of the result. TDD is just a tool and as with any other tool, you need practice to use it properly. Poor TDD can lead to a poor design with a bunch of useless tests.
To test if someone used TDD or equally efficient process:
Run static analysis (such as sonar, qulice etc.) and compare the results with some reference projects (with good and bad design, as you need some benchmark). TDD provides a feedback loop that helps you deliver a well-designed software. Poor design is a clear indicator that TDD hasn't been used or the person didn't know how to use the feedback that TDD provided.
Run mutation tests (such as pitest) and, as above, compare the results with some reference project that is well tested and poorly tested. 100% coverage is not a TDD goal. However, one of its goals is to give you confidence to change and improve your code by providing a valuable test suite and self-documented code. The side effect of applying Three Laws of TDD is that you have very high code coverage. I encourage you to use a mutation framework, not merely a coverage analysis. Mutation tests check if the test suite actually tests the behaviour (and not merely executes lines of code to achieve high coverage).
If, according to the check above, the project has good design and is well tested, you can ask the author whether they used TDD out of curiosity, but this should not affect your judgement. On the contrary – if the design is good and the project is well tested despite not using TDD, it is an opportunity for you to discover and add new tools to your toolbox that can help you to achieve your goals as a developer.
Test Driven Development is more a kind of development methodology.
The reference book, by Kent Beck, defines TDD by example. Literally speaking, you can't prove the use of TDD. To cite the author, TDD is a sets of rules that imply "Red/green/refactor-the TDD mantra". That is to say:
Red-Write a little test that doesn't work, and perhaps doesn't compile at first
Green-Make the test work quickly, committing whatever sins necessary in the process
Refactor-Eliminate all of the duplication created in merely getting the test to work
This would not be a prove bot only a track of your work: for the points 1 and 2 you could log the result of JUnit tests to show the sequence between red and green (assuming, on point 1, that your tests compile).
For the third point, this is about the measure of refactoring. A tool such as Sonar could give you measure of duplication. For that, the simple way is a project managed with Maven, what should help writing the JUnit tests. Usually, the project is built with a continuous integration tool such as Jenkins or Hudson.
I can suggest that you should read Test-Driven Java Development - Second Edition
,written by Viktor Farcic, Alex Garcia, . It's amazing book.
Explore the tools and frameworks required for effective TDD development
Perform the Red-Green-Refactor process efficiently, the pillar around which all other
TDD procedures are based
Master effective unit testing in isolation from the rest of your code
Design simple and easily maintainable code by implementing different techniques
Use mocking frameworks and techniques to easily write and quickly execute tests
Develop an application to implement behavior-driven development in conjunction with
unit testing
Enable and disable features using feature toggles

Approach to perform unit and integration tests from Scratch for untested code

The basic question is "How should one start with writing unit and integration testing for a untested project? Especially considering the fact that the person is not familiar with the code and has not done integration testing before."
Consider the scenario where unit tests and integration tests have to be written for a project. The project uses Java/J2EE technology does not have any tests written at all.
The dilemma that I face is since I have not written the code, I don't want to refactor the code immediately to write tests. I also have to select a testing framework. I am thinking of using Mockito and Powermock.
I also have to estimate code coverage for the tests. And then perform integration testing. I will have to research on integration testing tools and select one. I have not done any integration testing or estimated acceptable level of code coverage for a project before.
Since I am working independently, if there are some strategies, tips, suggestions on what should I start with and tools that one can recommend, I will appreciate it.
First comes first:
Understand the architecture, what are the main components?
If you have no good overview of the features and functions the program offers, make a list of them and create a hierarchy of them
Get familiar with the code, I recommend the following approach:
after you understand where the code of its different components are started, try to figure out the method invocation hierarchy (in Eclipse you can easily jump the source code definitions by pressing F3)
later you can do the same, while debugging the code, this way it will jump automatically to the definitions, plus you can observe how the state of the program changes
For Unit Testing itself, I can recommend Clean Code Chapter 9 (circa 12 pages) for starters. It uses JUnit for the example and gives a very good introduction how good testing is done.
There you will learn things like the F.I.R.S.T. principle, that Unit Tests should be:
Fast, Independent, Repeatable, Self-Validating and Timly
Some clarifications, JUnit is the most used and accepted test framework itself. Mockito and Powermock are mocking frameworks, they are used together with JUnit when you want to do integration tests.
For code coverage I can only recommend Cobertura, but there are many more.
Start with unit tests before you dive into integration tests (bottom-up), you can also do it the other way around (top-bottom), but since you say you are not so much experienced I would stay stick to the first.
Finally, just go for it and get started. You will learn the most and fastest while actually writing the test code.
Stop. "..not familiar with the code..". First get familiar with the code and most importantly its expected functionality. You can't refactor or unit test a code that you are not comfortable with.
Since you have not done unit-tests before, I would suggest learning and getting convenient with unit-tests.
Important: Bad/Wrong unit-tests are worse than no unit-tests. This is because the next guy who will maintain your code will misinterpret
the functionality.
There are bunch of Code Coverage tools out there. You can use which ever seduces you better.
Adding tests to legacy code that has no tests is a difficult task. As #Suraj has mentioned, get familiar with the code base and the expected functionality. You can't test it if you don't know what it is supposed to do.
In terms of choosing which areas of the code to test. Start with the high business value areas. Which functionality is most important? You want to make sure you have a strong test set for that code.
Since you don't have any unit/integration tests, I would start with some high level end to end tests that at least ensure that given some inputs to the system you get some expected outputs. This doesn't ensure correctness but at least ensures consistency.
Then as you develop a test suite you can be confident that the refactorings you are doing are not changing the behavior of the code (unless you find bugs of course that are being fixed).
For testing frameworks, JUnit is the standard unit testing framework. Note that the frameworks Mockito and Powermock are not testing frameworks themselves, but they can be used within JUnit.
For acceptance tests, there are also a variety of frameworks to help. For web UI testing, Selenium is pretty standard. There are also tools like Fitnesse for more table driven testing.
There are also some common frameworks to help with code coverage - Cobertura, Emma, Clover come to mind.
I would also set up an automated build (Jenkins build server is pretty simple to set up). This will allow you to run your tests on every checkin. Even though your code coverage is going to be low to start, getting in this habit is a good one.

Does it make sense to do unit testing on Java EE applications?

I have heard that Java EE unit testing is much harder than standard Java applications. The testing for my company's application stays at User Acceptance testing. We verify UI and functions behave as they are supposed to. Does it make sense to do unit testing on Java EE applications? If yes, what are some good starting points?
Of course it makes sense.
Let me guess: in the case of your company, when you make a minor change to a central component, I suppose that you'll repeat once and again your User Acceptance Tests. A real PITA, and overboring for a development team, in my opinion.
Unit testing allows you to develop in a consistent way the different layers of your Java EE app (i.e. view, business and model), AND, moreover, it allows you to do regression testing. The magic with regression testing is that in a long life application, this provides you a way to be sure that a new patch, code refactoring, or evolution doesn't break the current system behaviour. And it can be done automatically if you use a continuous integration tool.
So, you can write unit test for business and model layer in a direct way using, as an example, jUnit. And here comes the problem with Unit testing in Java EE apps: What do we do with the view layer?
Well, for the view layer you can use an automated test tool, say Apache jMeter, to check the expected behaviour of your Webapps, check your data validation, your system stability (programing long tests with a regular number of users) and scalability (with increasing and decreasing concurrent users), stress testing, etc. (I know it's not Unit testing, but it can be used in a similar way for regression testing).
I think it's a capital part of every software project, and I invite you to apply it to some of your project, and compare by yourself the final result.
Java EE 6's CDI resource injection was practically made for unit testing; you can swap out #Inject-ed FacesContexts, database resources, and beans for #Alternative beans that have known, predictable behaviour for testing.
It always makes sense to do unit testing on the server. Java EE is not necessarily harder to unit test. A good starting point is the code and the various layers of the application. i.e. start writing unit tests for persistence, then write unit tests for the services, etc....
Testing at the UI level alone is dangerous, because you can have bugs in the lower layer that are either hidden by, or compensated for in, the upper layers MOST of the time. It also means when you experience a problem, you have to first find out whether the problem is in the front end or the back end.
Yeah, Java EE is harder to unit-test. It's also much harder to fix it when you break something and don't notice it for two weeks because you never bothered to write unit tests.
The more complex the application is, the more you need to have a good testing regimen. And since we're talking about Java EE, it's safe to assume that your application is complex.

Which UnitTest framework to learn for Java now? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Although I have programmed with Java for roughly 3 years + now (not day-to-day but at least I understand the fundamentals), haven't really come into the field of Unit Testing...
My work is now more Testing / Problem Analysis oriented, so I reckon a good Java Unit Testing Framework will be quite helpful to this role.
Obviously there is no formal rule of which framework to go with in my Team. So just wondering, as a beginner, which framework is a good one to get started quickly?
Junit?
TestNG?
or something else?
Edit: it seems JUnit has more printed books as references compared to TestNG on Amazon. But I don't know their popularity / trend in Java Industry as for now.
I'm the creator of TestNG and author of the "Next Generation Testing" book, so here are a few (obviously biased) thoughts.
For functional (or end to end / integration / system, whatever term you prefer) testing, TestNG offers a few features that JUnit doesn't have and that users have found very useful:
Groups. Once you have compiled your tests, you can just ask TestNG to run all the "front-end" tests, or "fast", "slow", "database", etc...
Support for multithreaded testing. This has two different meanings:
1) You can tell TestNG to run all your tests concurrently in thread pools that you define (one line change in an XML file). This is very configurable so that tests that are not multithreaded can still be run in single threads.
2) You can tell TestNG to invoke your test methods n times from p threads. This gives you a good idea of how thread safe the code you are testing is.
Test dependencies and deterministic ordering. This is very useful for integration testing where it's very common to see test methods that need prior test methods to succeed before they can even run. TestNG is very popular in the Selenium community for this specific reason ("don't bother testing this page of my web site if the login test failed").
Another immediate advantage of test dependencies is that TestNG can tell you "1 method failed, 99 methods skipped", which is a much more accurate result than "100 methods failed".
TestNG has many, many more features and I'm happy to answer questions here or on our mailing-list (http://groups.google.com/group/testng-users ).
I would learn TestNG with Unitils. Covered all my needs all the time. Add XMLUnit and DBUnit and you should be settled for a long time.
To be perfectly honest I JUnit is way more popular than TestNG, at least here where I work and live. I know this might be a strange argument, but if I were you I'd scan through some job adds and see which framework does the industry in your area/country favour (for example I'm going for JUnit because of that, I mean sure I could learn TestNG, it might turn out to be better, but what good would it do to me if all the employers require JUnit knowledge?).
Although it may seem to be a petty criterion, all things being equals, it looks like job trends heavily favour JUnit.
http://www.indeed.com/jobtrends?q=TestNG%2C+JUnit&l=
Both do their jobs equally well, so there is no right or wrong. You can use both in combination with numerous frameworks to help support your development.
If you need to work for a client, you can learn the one that you are expected to use. If not, the best idea is to try them both out and find out what works best for you.
I've used both and found that for unit testing only jUnit works very well, but in terms of System testing I would recommend TestNG. TestNG offers a few extra features (like parametric testing) and is highly flexible. For example, in jUnit one test failing in a suite usually means you have to re-run your entire suite, but in TestNG you can simply rerun the test that failed. Heres a really good article outlining both (its a bit biased towards TestNG though)
http://www.ibm.com/developerworks/java/library/j-cq08296/index.html
JUnit is very well supported in many IDE's including Eclipse, and JUnit 4 with annotations is quite nice to work with.
Unless you have specific needs then go for tool support, i.e. jUnit.
TestNG with Unitils is really great. It covers almost all the requirements. Unitils support lot of assertion utils, Spring, Hibernate, mocking frameworks, dbutils etc.
To me, it is just a matter of taste. I've personnaly used jUnit daily for more than 5 years now and I'm very happy with it, especially with the last version and its #Rule feature that prevents my team from writting the same code over and over.
It integrates well with all the tools I use daily : IDE, build, continuous intégration...
Junit is famous and best unit test tools, I think you and me both know Junit is so important so that Java developer changes their coding pattern as junit contribution, You can learn some Junit as basic unit test technology as well as learn testng as second unit test technology.
The following link maybe be useful for you!
http://www.javarmi.com/2010/08/junit-4-tutorial-and-example-get-starting/
Junit is the best place to start. Junit 4.x has many rich features like annotations etc as well its get good support from popular frameworks like Spring.
I would go for JUnit.

Bringing unit testing to an existing project

I'm working on an existing Java EE project with various maven modules that are developed in Eclipse, bundled together and deployed on JBoss using Java 1.6. I have the opportunity to prepare any framework and document how unit testing should be brought to the project.
Can you offer any advice on...
JUnit is where I expect to start, is this still the defacto choice for the Java dev?
Any mocking frameworks worth setting as standard? JMock?
Any rules that should be set - code coverage, or making sure it's unit rather than integration tests.
Any tools to generate fancy looking outputs for Project Managers to fawn over?
Anything else? Thanks in advance.
Any tools to generate fancy looking outputs for Project Managers to fawn over?
Be careful. A fancy tool for displaying metrics on unit test counts, coverage, code quality metrics, line counts, check-in counts and so on can be dangerous in the hands of some project managers. A project manager (who is not in touch with the realities of software development) can get obsessed with the metrics, and fail to realize that:
they don't give the real picture of the project's health and progress, and
they can give a completely false picture of the performance of individual team members.
You can get silly situations where a manager gives the developers the message that they should (for example) try to achieve maximal unit test coverage for code where this is simply not warranted. Time is spent on pointless work, the important work doesn't get done, and deadlines are missed.
Any rules that should be set - code coverage, or making sure it's unit rather than integration tests.
Code coverage is more important for parts of the code that are likely to be fragile / buggy. Acceptable coverage levels should reflect this.
Unit tests versus integration tests depends on the nature and complexity of the system you are building.
Adding lots of unit level tests after the fact is probably a waste of time. It should only be done for class identified as being problematic / needing maintenance work.
Adding integration level tests after the fact is useful, especially if the projects original developers are no longer around. A decent integration test suite helps to increase your confidence that some change does not break important system functionality. But this needs to be done judiciously. A test suite that tests the N-th degree of a website's look and feel can be a nightmare to maintain ... and impediment to progress.
Concerning the unit testing framework, there are mainly two of them : jUnit and TestNG. Both have theuir advantages, and both are equally performant. The main dvantage of jUnit is (to my mind) its default incoproration of an Eclipse plugin allowing easy tests calling.
Concerning the mocking framework, I don't find them to be a required part of your testing approach. Of course they're useful, but they solve a specific purpose : testing a behaviour (as opposite to testing an interface - what jUnit allows. With mocking frameworks, you're able to test how a specific class implements a specific interface. Will you need it ? Obviously. Will you need it first ? I don't know.
Concerning the rules, the only one I've found to be useful is simple (as always) : "always test code that broke at least once.". Consider your bug tracker. Each time a bug is encountered, there must be a unit test ensuring there is no regression. It's, to my mind, the faster way to have quality code.
Concerning the fancy- and efficient - output, I can recommend you enough to install a continous integration server (Hudson, obviously). It will run all your test suite each time code is commited, to ensure there are no side effects. it will generate graphs shoiwing the number of test run, and so on. it also can integrate code coverage tools and graphs. This continuous integration server will really become fast your testing buddy.
This is a complex question, so just a few notes about our practice at $work:
JUnit is indeed still the standard. Most documentation and literature treats JUnit.
Mockito seems to be the new star in Java mocking, although we still use JMock and think it's fine for our needs.
We use the EclEmma Eclipse plugin for checking our test coverage, and like it.
If you haven't done so already, read Working Effectively with Legacy Code by Michael Feathers.
I've been retrofitting unit tests to a C++ project and it is not pleasant.
First thing I did was to identify where most of the 'action' occurs. Then use that to start putting unit tests on the functions that can be test easily.
Then once you have the easier ones you can start looking at expanding the coverage virally - attack the functions that have fewer dependancies, run through them a few times in a debugger seeing what values are passed in and then write unit tests with those values to make sure you don't break anything.
Don't expect a quick fix - it's taken 3 weeks (6hr days, 5 days a week) to get 20% coverage but the code spends 80% of the time in that code so I think it has been time well spent and has uncovered quite a few bugs.
Regarding test coverage, I think that when you're bringing in unit testing to an existing project it's too early to start setting coverage expectations. You should start by ensuring that you actually can integrate the test framework and get reports from the coverage tools. Once you've done that you can start monitoring coverage, and then you can consider targets.

Categories