How to use junit 5 group test(gather user cases) in a beautiful way

Viewed 5504

because the test method have many user cases, how to gather these cases?

like jest javascript unit test


describe('test methon', () => {
  test('user case one', () => {
    //test code
  });

  test('user case two', () => {
    //test code
  });

  test('user case three', () => {
    //test code
  }); 

  test(...) 
});
2 Answers

I'm not aware of anything in JUnit5 that looks as expressive and concise as tests in javascript you showed. But there is at least one thing to consider that would allow you to group tests in a similar way.

It is @Nested annotation. It allows you to group a set of tests into a logical group. Once your test pack is executed it will be easier to navigate and understand which groups of tests passed/failed. Quite useful if you have a big set of tests within your JUnit test case class. Here is an example of how it looks like:

public class YourTestCase {
    …

    @Nested
    @DisplayName("Tests for my method")
    class MyMethodUseCases {
        @Test
        void testUseCase1() {
            ...
        }

        @Test
        void testUseCase2() {
            ...
        }

        @Test
        void testUseCase3() {
            ...
        }
    }

If your group of tests shares some context that needs to be set up before tests executed then you might also consider a special JUnit runner for that like HierarchicalContextRunner. This is not a part of standard JUnit, but a custom extension.

And the last thing, if the only difference between your use cases is data input, then you might consider to use @ParametrizedTest annotation. It allows you to write one test and execute it with multiple data inputs.

Since JUnit 5 is a platform for all kind of test engines you can choose among many approaches/engines to specify your tests. An engine that goes in the direction you sketch is Specy. Here’s an example from the documentation:

class StackSpec extends ScalaSpecsy {
  val stack = new scala.collection.mutable.Stack[String]
 
  "An empty stack" >> {
 
    "is empty" >> {
      assertTrue(stack.isEmpty)
    }
    "After a push, the stack is no longer empty" >> {
      stack.push("a push")
      assertFalse(stack.isEmpty)
    }
  }
 
  "When objects have been pushed onto a stack" >> {
    stack.push("pushed first")
    stack.push("pushed last")
 
    "the object pushed last is popped first" >> {
      val poppedFirst = stack.pop()
      assertThat(poppedFirst, is("pushed last"))
    }
    "the object pushed first is popped last" >> {
      stack.pop()
      val poppedLast = stack.pop()
      assertThat(poppedLast, is("pushed first"))
    }
    "After popping all objects, the stack is empty" >> {
      stack.pop()
      stack.pop()
      assertTrue(stack.isEmpty)
    }
  }
}

See this list of 3rd party test engines.

Related