I developed a java application and I want to write unit test for it. (I have never written a unit test in java before) I noticed that there are 2 different example by writing Junit test. like E.g. 1
public void testExample(){
//do something...
}
than E.g. 2
#Test
public void Example(){
//do something...
}
which one is the more usefull ?
Test convention have changed in JUnit4
There's no need for test prefix anymore, just use #Test annotation before the method:
JUnit 3 used naming conventions for the identification of test methods. JUnit 4 uses annotations for that purpose, so that the prefix "test" is actually superfluous. It is not only superfluous, but also redundant.
Instead writing something like:
#Test
public void testAverageTotalStartedThreadCount() {}
you could just skip the prefix "test" and go with the annotation only:
#Test
public void averageTotalStartedThreadCount() {}
The "test" prefixes are still generated by Eclipse and NetBeans, so if you don't like the superfluous naming, you will have to remove it manually. The "test" prefix in the test-class name, however, is still useful. It makes the search for test classes more easy.
For example 1, I assume you are planning to throw exception or log if something goes wrong.
Although you can do it, but the preferred way is to write proper unit test using frameworks like Junit (#Test is from Junit framework).
Junit framework makes testing easier and is considered standard in Java Development. You can use features like Assert to check the output of method or fields inside it. Thus Ex 2 is preferred in industry. refer this test file written using junit framework -
https://github.com/akashchandwani/Algorithms/blob/master/Algorithms/test/sorting/SortingTest.java .
Here's a junit tutorial you can refer to, there are several available on web, you can choose what suits you.
http://www.vogella.com/tutorials/JUnit/article.html
Related
I am studing how to create java test cases. In internet I saw two structures:
public class XXX {
#Test
#Test
}
And
public class XXX extends TestCase {
//test cases
}
I am trying to use the second one but I can not create ignore case. In first example I can use #Ignore. What about the second one?
The second method is the old method with JUnit (up to JUnit 3). It doesn't use Annotations (those things that start with #).
The new method uses Annotations (#Test and #Ignore to name just two).
If you insist on using the old method (JUnit 4), check out this question for more information.
I am new to tdd and the mockito web framework.
Basically this is the getter method in the class:
public Long getDeviceManufactureId()
{
return deviceManufacturerId;
}
How would I write a unit test?
so far I am thinking this:
dem is the name of the class
#Test
public void testGetDeviceManufactureIdreturnsDeviceManufactureId()
{
assertEquals("Richard", dem.getDeviceManufactureId());
}
In general we write test cases for methods that has some logic in it. Like service methods that may have multiple dao calls. Simply writing test cases for all method does not make sense and usually wastage of time in build (however small that is). So my opinion would be not to write such trivial test cases.
If it is just about code coverage then I am sure getter/setters will be used in some other method that will have a test for it. That should cover these. But if you absolutely have to write a test case then what you have done seems fine. You can also assert not null if the instance variable can never be null.
Testing getters and setters could be a requirement in certain though rare scenarios where the container class is not just a POJO.
If that is a case,I would recommend creating a single TestSuite,dedicated to such instance variables,with each testcase's naming convention like :
TestGetVariableNameClassName
TestSetVariableNameClassName
You need to organize the test data such as maintenance is not tricky.
I have this problem. One class (and actually with one public method) to test, and ~30 test scenarios stored in the separate xml files. As one unit test class would be too long (need to test all the files in separate test), I decided to divide them into few groups (few classes), and now the questions occur.
The unit test itself implements few other methods, used in testing (for getting resources, formatting calendar in different matter), as I got few of those unit classes I should also copy those methods.
I just thought if I could create additional class for the methods, and use simply inheritance, or maybe I should create each unit test with the those copied methods? What is the good practice in such a case?
An alternative to inheritance is delegation, as mentioned by Alan Stokes. A good way to make use of this in junit is: use Rules. Some are provided, but you can rather easy create your own set of rules.
The major benefit we have experienced is that you can cherry pick the common features you want to have. Sometimes you just want a tiny bit of the common abstract test class. But as you can only have the full set or nothing, you may end up setting up a database state for a rather simple unit test.
In the sample below from the junit Wiki the TemporaryFolder Rule adds the ability to the test to create temporary folders and files. Those will be deleted after every test execution.
public static class HasTempFolder {
#Rule
public TemporaryFolder folder = new TemporaryFolder();
#Test
public void testUsingTempFolder() throws IOException {
File createdFile = folder.newFile("myfile.txt");
File createdFolder = folder.newFolder("subfolder");
// ...
}
}
Another good thing about it is that you can change the behaviour to class level rather easy. A situation where you might want to have this is the setup of an expensive fixture state in a database or search index. Or when you create a big sample XML for some ETL process for which you want to run an integration test. This should be used only when performing read only operations.
To move it to class level, you just need to make the member static and add the #ClassRule annotation instead of #Rule
public static class HasDataBaseState {
#ClassRule
public static DataBaseState dbState = new DataBaseState();
#Test
public void testUsingDataBaseState() throws IOException {
// perform tests
dbState.query("select count from table where attribute = 'x'");
}
}
There are more features, but those are covered rather good on the junit wiki. The facts I pointed out are the ones we like most about it.
If you need common test fixtures for a number of different test cases, it's perfectly fine to use an abstract base class for your unit tests. For example, small-scale integration tests using Spring will often use a base class that sets up the test runner and context and then add the specific components they're testing.
I Want to write my unit test in the same source file being tested (like you can do in D http://dlang.org/unittest.html).
I also want to be able to run the test in eclipse as i usually do with a dedicated test file.
In this example Junit complains if there is no public zero argument constructor:
public class Dummy {
private String _name;
public Dummy(String name) {
_name = name;
}
public String name () {
return _name;
}
#Test
public void testName() throws Exception {
assertEquals("dummy", new Dummy("dummy").name());
}
}
Any suggestions on how to put the test method in the "real" source code and be able to run the test (in other words how to fool the no arg constructor restriction)?
Thanks
You could consider classical TDD (based on Kent Beck's book "Test Driven Development By Example"), where the idea is not to write tests for specific classes/methods, but rather for features that you want to implement.
That way, it really doesn't make sense to put tests in production classes.
To run the JUnit Test framework, it internally requires a zero argument constructor to instantiate it. Generally it creates by default, if you don't have any constructor. But since you have one constructor with argument, the framework will not be able to instantiate the respective class to execute the test case. To avoid it create a blank no argument constructor.
Having test methods in the same class is not possible with JUnit and is also a quite strange design choice. Well, it would be possible if you had a zero argument constructor, but still, a test class is not meant to be the class that is tested. However, you can create a test class in the same file to carry out your test cases.
You can create a second constructor without parameters if you really want to put your JUnit tests inside the same class. Nevertheless this is not the way you do it according to the java conventions.
Also it bloats the class with unnecessary test cases (unnecessary for the actual task the class should do). You should maybe think about it if it would not be better to put the test cases in a separate class.
You can write your own Runner instead of using JUnit's default BlockJUnit4ClassRunner. Please let me know if you need help.
I've recently inherited an application that is written by different people at different times and looking for guidance on how to standardize.
Assuming NUnit:
[Test]
public void ObjectUnderTest_StateChanged_Consequence()
{
Assert.That(tra_la_la);
}
[Test]
public void ObjectUnderTest_Behaviour_Consequence()
{
Assert.That(tra_la_la);
}
for example:
[Test]
public void WifeIsTired_TakeWifeToDinner_WifeIsGrateful()
{
Assert.That(tra_la_la);
}
[Test]
public void WifeIsTired_MentionNewGirlfriend_WifeGetsHalf()
{
Assert.That(tra_la_la);
}
I just write what it's for. It's not like you're going to have to type the names in anywhere else, so having a testWibbleDoesNotThrowAnExceptionIfPassedAFrobulator isn't a problem. Anything which is a test begins with 'test', obviously.
There is no standard as such, different people/places will have different schemes. The important thing is you stick to a standard.
Personally I'm a fan of the following - example code in C#, but very close to Java, same rules apply:
[Test]
public void person_should_say_hello()
{
// Arrange
var person = new Person();
// Act
string result = person.SayHello();
// Assert
Assert(..., "The person did not say hello correctly!");
}
Explicit
The test name should give the name of the class under test. In this example, the class being tested is Person. The test name should also have the name of the method that is being tested. This way, if the test was to fail, you'll at least know where to look to solve it. I'd also recommend following the AAA - Arrange, Act, Assert rule, it will ensures your tests are easy to read and follow.
Friendly fail messages
When it comes to asserting a result/state, its useful to include an optional message. This makes it easier when a test fails, especially when run as part of a build process or via an external tool.
Underscores
The final (though optional) stance I follow is using underscores for tests names. While I'm no fan of underscores in production code, their use in test names is useful as test names are often much longer. Quickly glancing at a test name that uses underscores proves to be much more readable, though this is subjective and the source of much debate with regards unit testing practices.
Integration Tests
The same standards apply to integration tests, the only difference being the location of such tests should be separate from unit tests. In the example code above, the test class would be called PersonTests and located in a file called PersonTests.cs. The integration tests would be named in a similar manner - PersonIntegrationTests, located in PersonIntegrationTests.cs. The same project can be used for these tests, but ensure they are located in separate directories.
It's instructive to look at BDD (behavioural driven development) and this blog post in particular.
BDD is essentially focusing on components and what they should do. Consequently it impacts directly on how you name/structure your tests, and the code they use to set up conditions and validate. BDD allows not only the developers to read/write the tests, but non-technical members of the team (business analysts etc.) can contribute by specifying the tests and validating them.
I ran across two good suggestions. Links here: http://slott-softwarearchitect.blogspot.com/2009/10/unit-test-naming.html
http://weblogs.asp.net/rosherove/archive/2005/04/03/TestNamingStandards.aspx
http://openmrs.org/wiki/Unit_Testing_with_#should
In that situation I'd probably find the naming convention that was used the most and refactor the rest of the code to use that. If the one that was used the most is truly horrid, I'd still look to the existing code and try to find one that I could live with. Consistency is more important than arbitrary conventions.
I use a FunctionTestCondition construct. If I have two methods, Get and Set I would maybe create the following test methods:
GetTest being a positive test (everything is ok).
GetTestInvalidIndex to test an invalid index being passed to the method.
GetTestNotInitialized to test when the data is not inited before use.
SetTest
SetTestInvalidIndex
SetTestTooLargeValue
SetTestTooLongString
Group your tests by setup, make a test class around this setup and name is with suffix Test or IntegrationTest. Using a test framework like JUnit or TestNG you can name your test methods as you want. I would name the method as what it tests, a sentence in camel case, not test prefix. The frameworks use a #Test annotation to mark a method as test.