As far as I did research, I saw Cucumber used for integration tests, not for unit tests. But I wonder if it is possible to migrate to Cucumber as tests are more readable and easy to change in Cucumber classes according to me.
Let's say this is my controller test class;
@WebMvcTest(value = Controller.class)
class ControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private Service service;
private XDTO xDTO;
private List<XDTO> xDTOList;
@BeforeEach
void setUp() {
xDTOList = new ArrayList<>();
X x= new X();
xDTO = new XDTO();
xDTO.setId(x.getId());
xDTOList.add(xDTO);
}
@Test
public void initialize_success() throws Exception {
when(service.initialize()).thenReturn(xDTO);
mockMvc.perform(MockMvcRequestBuilders.post(X INITIALIZE)
.accept(APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id", is(xDTO.getId())));
}
How can I change this to Cucumber test class by starting up partial context like JUnit ?
CodePudding user response:
Cucumber isn't used for unit tests because the main benefit of Cucumber is to be able to express the behaviour you are examining using abstract high level natural language. That sort of language does not have such a good fit with unit tests, which should be much more focused on detail of how a unit behaves.
If you use low level of abstractions in cucumber and document HOW things are done you end up with verbose scenarios that quickly become unwieldy and difficult to work with.
The idea of one testing tool to test (rule) them all
is initially very appealing. I was strongly drawn to it for a while. With greater experience of cuking it became clear this idea is flawed. Unit test tools are much better for writing unit tests, its easy to loop, mock and do more exhaustive testing. If you implement them correctly they will always run much faster as well.
This idea of using different tools at different scales is nothing new, it applies to almost every human endeavour. Testing is no different. Use Cucumber for describing (ideally driving) high level behaviour of a system/application. Use unit testing to smaller detailed testing of units.