2

In JUnit, can we explicitly create individual test cases (not necessarily all the test cases provided by a test case class) and run them? For comparison, in pyunit, I can do that by test suite (see the example below).

I saw some JUnit examples using test suite at https://www.codejava.net/testing/junit-test-suite-example-how-to-create-and-run-test-suite-in-command-line-and-eclipse and https://www.tutorialspoint.com/junit/junit_suite_test.htm. But the examples implicitly create all the test cases provide by a test case class and run them. Can I create some but not all the test cases from a test case class, and add the test cases into a test suite?

An example of pyunit from https://docs.python.org/3/library/unittest.html#organizing-test-code

import unittest
class WidgetTestCase(unittest.TestCase):
    def setUp(self):
        self.widget = Widget('The widget')
    def tearDown(self):
        self.widget.dispose()
        self.widget = None
    def test_default_size(self):
        self.assertEqual(self.widget.size(), (50,50),'incorrect default size')
    def test_resize(self):
        self.widget.resize(100,150)
        self.assertEqual(self.widget.size(), (100,150),'wrong size after resize')
    def test_somethingelse(self):
        ...

widgetTestSuite = unittest.TestSuite()
widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
widgetTestSuite.addTest(WidgetTestCase('test_resize'))
unittest.TextTestRunner(verbosity=2).run(suite)
halfer
  • 19,824
  • 17
  • 99
  • 186
Tim
  • 1
  • 141
  • 372
  • 590
  • Possible duplicate of https://stackoverflow.com/questions/9288107/run-single-test-from-a-junit-class-using-command-line ? – antonyh Apr 10 '19 at 23:01
  • It's also possible to run single tests in Intellij and Eclipse, not just whole test classes but the individual methods within. In Intellij, right-click on the method and chose run. I presume it's similar in Eclipse. – antonyh Apr 10 '19 at 23:03
  • You might also have joy with the @Tag annotation. – antonyh Apr 10 '19 at 23:06
  • Thanks. The link you gave test a single test case. Can I select more than one but not all the test cases from a test case class to create and run? – Tim Apr 11 '19 at 00:01
  • Not a direct answer. But it looks like you are really looking for parameterized tests which are supported by the JUnit natively: https://blog.codefx.org/libraries/junit-5-parameterized-tests/ – Maxim Fateev Apr 11 '19 at 00:05
  • Counterintuitively, the JUnit logic is that 1 test class = 1 test case ("A test case defines the fixture to run multiple tests" - http://junit.sourceforge.net/junit3.8.1/javadoc/junit/framework/TestCase.html). – daniu Jul 10 '19 at 11:12

0 Answers0