Reputation: 53906
I have a test :
@Test
testLogin {
String returnValue = login(username, password)
}
Once this test completes I would to test the value of returnValue
in a separate test. returnValue
is also a method parameter for another method :
@Test
testVal {
performTest(returnValue)
}
To achieve this I could declare returnValue as a global variable and then ensure the tests run in order using @FixMethodOrder(MethodSorters.NAME_ASCENDING)
but this seems like a non standard and unclean approach ?
Does this imply that the code which is being tested should be re-factored ?
What are the alternatives ?
Upvotes: 1
Views: 1049
Reputation: 5588
Such test
@Test
public void testLogin() {
String returnValue = login(username, password)
}
doesn't have much value. The only thing it tests is that method login
doesn't throw an exception and I am pretty sure that it is not what you want to test. Where are the assertions? The following implementation satisfies this test:
public String login(Object a, Object b) {
return null;
}
Your test should look like this:
@Test
public void successfulLoginReturnsExpectedResponseCode() {
String responseCode = login(username, password)
assertThat(responseCode, is(equalTo("SUCCESSFUL_LOGIN")));
}
If the login
method does nothing, the return value will be incorrect.
This example uses hamcrest for better diagnostics and readability. You can also use assertEquals
.
Regarding your question about tests sharing variables, it is very important that your tests (no matter whether they are unit test, integration tests or acceptance tests) do not share anything and are independent. Otherwise you will run into problems such as failing test because the other test didn't run or the tests were run in different order. You should be able to run any subset of tests in any order.
You should also consider a better name of the test, so it describes what the code under test should be doing. For example successfulLoginReturnsExpectedResponseCode()
.
Upvotes: 3