I have a problematic situation with some quite advanced unit tests (using PowerMock for mocking and JUnit 4.5). Without going into too much detail, the first test case of a test class will always succeed, but any following test cases in the same test class fails. However, if I select to only run test case 5 out of 10, for example, it will pass. So all tests pass when being run individually. Is there any way to force JUnit to run one test case at a time? I call JUnit from an ant-script.
I am aware of the problem of dependant test cases, but I can't pinpoint why this is. There are no saved variables across the test cases, so nothing to do at #Before annotation. That's why I'm looking for an emergency solution like forcing JUnit to run tests individually.
I am aware of all the recommendations, but to finally answer your question here is a simple way to achieve what you want. Just put this code inside your test case:
Lock sequential = new ReentrantLock();
#Override
protected void setUp() throws Exception {
super.setUp();
sequential.lock();
}
#Override
protected void tearDown() throws Exception {
sequential.unlock();
super.tearDown();
}
With this, no test can start until the lock is acquired, and only one lock can be acquired at a time.
It seems that your test cases are dependent, that is: the execution of case-X affects the execution of case-Y. Such a testing system should be avoided (for instance: there's no guarantee on the order at which JUnit will run your cases).
You should refactor your cases to make them independent of each other. Many times the use of #Before and #After methods can help you untangle such dependencies.
Your problem is not that JUnit runs all the tests at once, you problem is that you don't see why a test fails. Solutions:
Add more asserts to the tests to make sure that every variable actually contains what you think
Download an IDE from the Internet and use the built-in debugger to look at the various variables
Dump the state of your objects just before the point where the test fails.
Use the "message" part of the asserts to output more information why it fails (see below)
Disable all but a handful of tests (in JUnit 3: replace all strings "void test" with "void dtest" in your source; in JUnit 4: Replace "#Test" with "//D#TEST").
Example:
assertEquals(list.toString(), 5, list.size());
Congratulations. You have found a bug. ;-)
If the tests "shouldn't" effect each other, then you may have uncovered a situation where your code can enter a broken state. Try adding asserts and logging to figure out where the code goes wrong. You may even need to run the tests in a debugger and check your code's internal values after the first test.
Excuse me if I dont answer your question directly, but isn't your problem exactly what TestCase.setUp() and TestCase.tearDown() are supposed to solve? These are methods that the JUnit framework will always call before and after each test case, and are typically used to ensure you begin each test case in the same state.
See also the JavaDoc for TestCase.
You should check your whole codebase that there are no static variables which refer to mutable state. Ideally the program should have no static mutable state (or at least they should be documented like I did here). Also you should be very careful about cleaning up what you write, if the tests write to the file system or database. Otherwise running the tests may leak some side-effects, which makes it hard to make the tests independent and repeatable.
Maven and Ant contain a "forkmode" parameter for running JUnit tests, which specifies whether each test class gets its own JVM or all tests are run in the same JVM. But they do not have an option for running each test method in its own JVM.
I am aware of the problem of dependant
test cases, but I can't pinpoint why
this is. There are no saved variables
across the test cases, so nothing to
do at #Before annotation. That's why
I'm looking for an emergency solution
like forcing JUnit to run tests
individually.
The #Before statement is harmless, because it is called for every test case. The #BeforeClass is dangerous, because it has to be static.
It sounds to me that perhaps it isn't that you are not setting up or tearing down your tests properly (although additional setup/teardown may be part of the solution), but that perhaps you have shared state in your code that you are not aware of. If an early test is setting a static / singleton / shared variable that you are unaware of, the later tests will fail if they are not expecting this. Even with Mocks this is very possible. You need to find this cause. I agree with the other answers in that your tests have exposed a problem that should not be solved by trying to run the tests differently.
Your description shows me, that your unit tests depend each other. That is strongly not recommended in unit tests.
Unit test must be independent and isolated. You have to be able to execute them alone, all of them (in which order, it does not matter).
I know, that does not help you. The problem will be in your #BeforeClass or #Before statements. There will be dependencies. So refactor them and try to isolate the problem.
Probably your mocks are created in your #BeforeClass. Consider to put it into the #Before statement. So there's no instance that last longer than a test case.
Related
The following test is one of several tests that fail when I run my tests in random order using this Maven command: mvn -Dsurefire.runOrder=random clean test
#Test
public void ShouldReturnCorrectAccountLoanSumForDebtRatioWhenRedemptionAmountIsNull(){
AccountVO account = mock(AccountVO.class);
CustomerGroupInformationVO group = mock(CustomerGroupInformationVO.class);
when(group.getCustomerIds()).thenReturn(Set.of("199406208123"));
when(account.getAccountOwners()).thenReturn(List.of((new AccountOwnerVO(null, "199406208123", null))));
when(account.getAmount()).thenReturn(BigDecimal.valueOf(500000));
when(account.getRedemptionAmount()).thenReturn(null);
assertEquals(BigDecimal.valueOf(500000), getAdjustedAccountLoanSumForDebtRatio(account, group, caseClientVO));
}
More specifically this is the line mentioned:
when(account.getAccountOwners()).thenReturn(List.of((new AccountOwnerVO(null, "199406208123", null))));
Any idea what is causing this and how I can fix it? When I run my tests normally using mvn clean install there are no issues at all. The reason I want it to work with a random order is that our build tool seems to use it and it can't build. Like I said it works fine locally.
Because Mockito works through side-effects stored in ThreadLocal variables, it is particularly subject to test pollution: If your tests fail when run in random order, it may be because some previous test left a mock in a state it wasn't expecting to be in. Also, Mockito stubbing relies on observing method calls in a specific order, which can cause odd exceptions if it can't observe the method calls (such as when they're final) or if you interact with a different mock while preparing a thenVerb argument.
One of your first lines of defense is to use validateMockitoUsage, which is meant to be run at the end of every test and confirms that no interaction with Mockito is left unfinished. You could put this in an #After method, but Mockito does so automatically if using MockitoJUnitRunner or MockitoRule. I'd recommend either of those latter options if possible, particularly MockitoRule.
This should help you confirm which test(s) are problematic. Once you're there, try these:
Double-check that you're not trying to mock final methods without Mockito's opt-in final support. If Mockito can't override your mock method, it won't be able to detect your stubbing calls in its expected order. If any of your methods are written in Kotlin, remember that unlike Java the methods are final unless declared open.
Your test doesn't seem to use Matchers, but if you do, make sure you use them for all arguments in a method if you use them for any argument in a method.
Be careful about calling real methods in the middle of stubbing. new AccountOwnerVO(...) shouldn't interact with mocks, but if it does, then Mockito might interpreted it as if your when call never got a thenReturn (when in reality it just hasn't gotten to it yet). Extracting your return value as a local variable is a reasonable step to try.
In my project I have to do some repository setup before all tests and after successful tests I want to clean up, I know #afterClass is used for this but it requires static variables but i dont want to make my objects statics, so is there any other way by which I can achieve this??
If you're using JUnit4, then use #After. Documentation here. Note that your methods annotated this way will be executed after each test case, in a similar fashion to #Before being executed before each test case.
If you're writing an integration test with multiple test cases and your setup is heavy, you could use a combination of #BeforeClass to set up static objects and #After to mutate/clean up/reset certain parts of these objects' states. This, of course, would violate your requirement of not using static variables, but I can't really see the rationale behind that requirement. Recall that JUnit instantiates the test class once for every single test case.
If you want set up and tear down before and after each test method, use #Before and #After. If you want to set up once, run all your tests and then tear down, use #BeforeClass and #AfterClass.
Yes, #BeforeClass and #AfterClass are static methods, but note that JUnit recreates your test class instance for each test method, so you cannot maintain any information in non-static fields of a test class across different tests.
I, as the other commenters here, have a feeling that you want to avoid static fields because there's a common opinion that they are bad practice. Please note, however, that good practice in writing code often does not apply to good practice in writing tests. This is one such example.
Why does a JUnit Suite class, in my cases its called TestSuite.class, not execute its own Test, Before, and After annotations? It only exectutes its own BeforeClass, AfterClass, and then ALL annotations of the suite test classes. I proved this is the case by creating a test project around this theory: https://gist.github.com/djangofan/5033350
Can anyone refer me to where this is explained? I need to really understand this.
Because a TestSuite is not a Test itself. Those annotation are for unit tests only. See here for an example.
public class FeatureTestSuite {
// the class remains empty <----- important for your question
}
A TestSuite is way of identifying a group of tests you wish apply some common behaviour to.
Perhaps better explained with an example.
So say you were doing some basic CRUD tests on an Orders Table in a Database MyDB.
Everyone needs mydb to be there and the orders table to exist, so you put them in a suite. It sets up the db and the table, the tests run, then before the suite goes out of scope the db is dropped, everything is nice and clean for the next test run. Otherwise you'd have to do that in every test which is expensive, or worse have test data from previous tests cause the others to fail often apparently randomly as you would have created an implicit dependancy between them.
There are other ways of achieving the same thing, but they clutter up your tests and you have to remember to call them.
You don't have to test it. If it doesn't get done none of your tests will execute.
As others have said, it's because a TestSuite is not a Test. It's just a class with an annotation to group other tests, so that it is more convenient to run.
It does have one special property, however, and that is the execution of #BeforeClass and #AfterClass. These are enabled to allow a global setup/teardown for the suite. It does not execute any tests (including #After, #Before or any rules).
Recently a new concept of Theories was added to JUnit (since v4.4).
In a nutshell, you can mark your test method with #Theory annotation (instead of #Test), make your test method parametrized and declare an array of parameters, marked with #DataPoints annotation somewhere in the same class.
JUnit will sequentially run your parametrized test method passing parameters retrieved from #DataPoints one after another. But only until the first such invocation fails (due to any reason).
The concept seems to be very similar to #DataProviders from TestNG, but when we use data providers, all the scenarios are run inspite of their execution results. And it's useful because you can see how many scenarious work/don't work and you can fix your program more effectively.
So, I wonder what's the reason not to execute #Theory-marked method for every #DataPoint? (It appears not so difficult to inherit from Theories runner and make a custom runner which will ignore failures but why don't we have such behaviour out of the box?)
UPD: I have created a fault-tolerant version of Theories runner and made it available for a public access: https://github.com/rgorodischer/fault-tolerant-theories
In order to compare it with the standard Theories runner run StandardTheoriesBehaviorDemo then FaultTolerantTheoriesBehaviorDemo which are placed under src/test/... folder.
Reporting multiple failures in a single test is generally a sign that
the test does too much, compared to what a unit test ought to do.
Usually this means either that the test is really a
functional/acceptance/customer test or, if it is a unit test, then it
is too big a unit test.
JUnit is designed to work best with a number of small tests. It
executes each test within a separate instance of the test class. It
reports failure on each test. Shared setup code is most natural when
sharing between tests. This is a design decision that permeates JUnit,
and when you decide to report multiple failures per test, you begin to
fight against JUnit. This is not recommended.
Long tests are a design smell and indicate the likelihood of a design
problem. Kent Beck is fond of saying in this case that "there is an
opportunity to learn something about your design." We would like to
see a pattern language develop around these problems, but it has not
yet been written down.
Source: http://junit.sourceforge.net/doc/faq/faq.htm#tests_12
To ignore assertion failures you can also use a JUnit error collector rule:
The ErrorCollector rule allows execution of a test to continue after
the first problem is found (for example, to collect all the incorrect
rows in a table, and report them all at once)
For example you can write a test like this.
public static class UsesErrorCollectorTwice {
#Rule
public ErrorCollector collector= new ErrorCollector();
#Test
public void example() {
String x = [..]
collector.checkThat(x, not(containsString("a")));
collector.checkThat(y, containsString("b"));
}
}
The error collector uses hamcrest Matchers. Depending on your preferences this is positive or not.
AFAIK, the idea is the same as with asserts, the first failure stops the test. This is the difference between Parameterized & Theories.
Parameterized takes a set of data points and runs a set of test methods with each of them. Theories does the same, but fails when the first assert fails.
Try looking at Parameterized. Maybe it provides what you want.
A Theory is wrong if a single test in it is wrong, according to the definition of a Theory. If your test cases don't follow this rule, it would be wrong to call them a "Theory".
I have a test class in java and there are several methods annotated by #Test in it, somehow, i want to Junit run method A before method B when i run the whole tests. Is it possible or necessary?
This sort of dependency on test methods is bad design and should be avoided. If there is initialization code in one test method that needs to be done for the next, it should be factored out into a setUp method.
The problem I have with this is reporting. If you WANT/NEED to see if each test method fails or passes then you're SCREWED.
I understand that you don't want one test to build upon previous tests, But regardless of that, there may be situations that you need it to do this (or you'll increase the complexity of the test by an order of magnitude).
Should the flow of tests in the code be up to the developer of the tests or the developer of the framework ?
Show JUnit test code to 10 java developers, and I'll be willing to bet most will assume that the tests (regardless of anything external) will be run in the order they appear in the test class.
Shouldn't THAT be the default behaviour of JUnit ? (Give me the option of telling it the order instead of JUnit figuring it out" on its own.)
Update: 2014-11-18
The newer version of JUnit supports method sorters
// This saves the tests in alphabetical order
#FixMethodOrder(MethodSorters.NAME_ASCENDING)
I would think that you might be able to create your own method sorter if you "really" wanted do do your own specific order.
Tests should have independent order, but some times we have not what we want.
If you have a large legacy project with thousands of tests, and they depends on their execution order, you will have many problems, when, for example you will try to migrate on java 7, because it will shuffle all tests.
You can read more about this problem here:
junit test ordering and java 7
If it's only two methods then you'd need to wrap it in a single unit test that truly isn't order-dependent.
#Test
public void testInOrder() throws Exception {
testA();
testB();
}
use the following to setup thing before and after tests
#Before
public void setUp() throws MWException {
}
#After
public void tearDown() {
}