Recently I was working in a team, who were writing the unit tests for the tests automation code base which was surprising to me. Do we even need that? If someone's answer is yes, then what about the unit tests for the unit tests and so on?
First, I think #jonrsharpe hit the nail on the head.
Second, this might not be a good SO question since it's more opinion based. However, I find it to be a good question to reflect on, so I'll throw my opinion in.
Finally, to the point and put broadly, anytime you write code to functionally support a project that is sufficiently complex, it is worthwhile to test it to ensure it behaves. Whether that's supporting the function, delivery or monitoring of your particular project, it's all fair game to test.
To your question of the recursive test problem, the test code itself doesn't functionally support a project (i.e. if it disappeared, you would still be delivering functional software), so you don't need to write code to test your test code. Also, test code should aim to be fairly straightforward so if you find yourself writing sufficiently complex test code, you have a different problem!
Related
When the JUnit test cases have to be written logically? Before or after creating the application? For big applications how it should be written? Based on the code we created or based on the requirement specification.
Ideally unit test cases should be written first and then the code. Many people follow Test driven Development(TDD). But again its choice and as part of best practice i prefer TDD.
TDD (Test Driven Development) is a computer programming method that
consists of small iterations. In this method you begin by writing the
test cases covering the new functionality, then you write the
production code necessary to make the test pass, and after that you
refactor the code to make it more maintainable. Writing the tests
before writing the code guaranties immediate feedback after changes
are made. TDD (test-driven development) is a technique for designing
the software as well as testing it.
In Test Driven Development (TDD) automated unit tests are written
before the code is actually written. Running these tests give you fast
confirmation of whether your code behaves as it should
.
It seems to me that I am fundamentally misunderstanding the purpose of Robolectric. I've been battling with it for a week already, and so far getting a new error message is considered as making progress. I am able to test some basic stuff like static views in an activity, but when something more complicated things come into play things just fall apart. I had to extend Robolectric to support 3-rd party libraries with certain parameters, Appcompat action bars and numerous other things which was extremely time-consuming and wasn't really documented anywhere, and things are advancing at a pretty much glacial pace. I am starting to think that I am using it in a wrong way and it simply isn't supposed to do what I want it to do.
The general app logic is quite straightforward so there isn't really much to unit test, the most complicated stuff is in the UI and remote API calls. Is Robolectric just supposed to make unit testing for Android less painful than with JUnit because it can run on the JVM and supports a few Android classes? Perhaps a black-box behaviour testing framework like Espresso would be more suitable for my needs? But we use continuos integration, and Robolectric was nice and easy to set up to run tests on the CI server, and I'd kind of like to keep it that way.
What do you use Robolectric for? A lot of blog posts recommend it for "activity lifecycle testing", but since I'm also quite new in the Android world, I don't really understand the purpose of it, especially since the app I'm testing is portrait-only. Could someone please give an overview of what you use Robolectric for, and how do you do it, preferably with code examples and explain why and how those tests are important?
We use it for:
unit testing: all components from parsers and utils, to controllers and presenters
integration/acceptance testing: the business logic of the app, per screen (which falls into integration and/or acceptance testing)
We don't use it for (and have found it difficult to use for these):
testing the network layer (we run all tests by injecting the test data in the same way the network layer would; parsers are tested separately)
user flows through different screens
If you're looking for more of the latter, perhaps Espresso/Robotium are better suited for your needs. And you absolutely can run these as part of your CI pipeline, but you'll need to invest some time in setup, or integrating with something like Appurify.
If you are finding it very difficult to write your tests, it might have to do more with the way your app is architected than the way you're using robolectric. See my answer here as well, it might help you: Writing Android acceptance tests with robolectric: how could it be done?
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
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.
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.