Javatpoint Logo
Javatpoint Logo

Behavior-driven development (BDD)

Behavior-driven development is an Agile software development process that supports collaboration among the developers, quality analysts, and business members in a software project. It is developed from the Test-driven development (TDD) software.

The BDD is a combination of general techniques and principles of the TDD with the ideas originated from the Domain-driven design (DDD) and the object-oriented analysis and design (OOAD) approach.

Mockito uses the BDDMockito class that is available in the org.mockito package. It develops a test in BDD style. The BDD style of writing texts uses the //given //when //then comments as the primary part of the test body. It uses given(..)willReturn(..) method in place of when(..)thenReturn(..) method.

Following are some important methods of the BDDMockito class:

Method and method type Description
<T> given(T methodCall) It is very similar to the when(TmethodCall) method. It enables stubbing.
<T> then(T mock) It enables the BDD style verification of mock behavior.
BDDStubber will(Answer<?> answer) It is similar to the doAnswer(Answer answer) method. It is used when we want to stub a void method with the generic Answer.
BDDStubber willReturn(Object toBeReturned) It is similar to the doReturn(Object toBeReturned) method. It is used instead of when(Object).
BDDStubber willThrow(Class<? extends Throwable> toBeThrown) It is similar to the doThrow(Class<? extends Throwable> toBeThrown) method. It is used when we want to stub a void method with an exception.

The following code snippet shows how to use the BDD style test:

In the above code snippet, we have used assertThat() method instead of assertEquals() method. It makes the code more readable and understandable if they are referenced through static import.

Example of BDD style

Here, we are going to create an example of a BDD style test. Switching to BDD style makes a minor difference only in the test syntax. It splits the test syntax into three parts: given, when, and then that makes the code more readable.

  • Given: We can use the setup part and the given kind of syntax.
  • When: We can do the actual invocations of the test.
  • Then: We can use the readable asserts like assertThat() and can also check whether the post-conditions are satisfied or not.

Let's understand the BBD style test by creating an example.


The following output shows that the test is successfully running using the BDD style.

Behavior-driven development
Next TopicArgumentCaptor

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA