Issue
I have a few questions,
first – should naming of the method also follow BDD approach when Given, When, Then is used inside a method?
For example, Given_Preconditions_When_StateUnderTest_Then_ExpectedBehavior or It will be excessive and repeat itself and it’s better to use something like methodNameUnderTest_givenCondition_expectedBehavior
as naming?
Second:
Do I need to write comments in tests marking Given, When, Then. Example:
@Test
void findById() {
// GIVEN
Visit visit = new Visit();
given(visitRepository.findById(1L)).willReturn(Optional.of(visit));
// WHEN
Visit foundVisit = service.findById(1L);
// THEN
assertThat(foundVisit).isNotNull();
then(visitRepository).should().findById(anyLong());
}
Solution
I personally like having the method name resemble what the method is testing in a bdd approach. So I don’t think there are requirements, but it depends on your preference.
I always use a should_when principle, in naming my tests.
shouldFindVisit_whenIdExists
Short and simple, with given_when_then the name could quickly grow big, even though I don’t think it is a big problem in tests!
For your second question, I think it depends on your preference again, but I think yes, it always helps seeing where I currently am in my test. And I can structure my test more easily in case I add something to it.
void shouldFindVisit_whenIdExists() {
// given
Visit should = ...;
// when
actual = service.findById(...);
// then
assertThat(actual, is(should));
}
I also always prefix my expected variables with a should, to mark them as what it should expect in the end. And the actual results from the service call in the when section as actual.
The verification in the end then is very clear and simple.
Answered By – smotastic
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0