Reputation: 383
I'm testing the "find" method of the controler that returns a "findById" but the return is always null.
My project is structured as follows:
I have a LegalPerson entity A repository that extends a JpaRepository
And a service that "uses" the repository.
@SpringBootTest
@AutoConfigureMockMvc
@ExtendWith(SpringExtension.class)
class LegalPersonResourceTest {
@MockBean
private LegalPersonService service;
@Autowired
private MockMvc mvc;
@Test
void find() {
var localDate = LocalDate.of(1955, 10, 25);
List<Long> subsidiaries = new ArrayList<>() {{
add(10L);
add(20L);
}};
List<Long> phones = new ArrayList<>() {{
add(50L);
add(60L);
}};
var mockLP = LegalPerson.builder()
.id(1L)
.active(true)
.companyId(1L)
.tradeName("Test Company Trade Name")
.companyName("Test Company Company Name")
.email("test@com")
.cnpj("testCNPJ")
.stateRegistration("test state Registration")
.municipalRegistration("test Municipal Resgistration")
.openingDate(localDate)
.address(1L)
.companyType(CompanyEnum.HEADOFFICE)
.subsidiaries(subsidiaries)
.phones(phones)
.build();
Mockito.doReturn(mockLP).when(service).find(1L);
}
}
I wonder what I'm forgetting, or writing wrong.
EDITED 01 :
Mockito.when(this.service.find(ArgumentMatchers.eq(1L))).thenReturn(mockLP);
mvc.perform(MockMvcRequestBuilders.get("/api/clients/lp/{id}", 1L))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().contentType("application/json;charset=UTF-8"))
.andExpect(MockMvcResultMatchers.jsonPath("$.active", Matchers.is(true)));
It works perfectly. But if I add
.andExpect(MockMvcResultMatchers.header().string(HttpHeaders.ETAG, "\"1\""))
return null.
Upvotes: 0
Views: 609
Reputation: 134
You only are mocking the service, but no testing anything in this code, you may want to test the controller, something like this:
import static org.mockito.BDDMockito.given;
@Test
public void shouldGetAPerson() throws Exception {
//...
given(service.find(1L)).willReturn(mockLP);
mvc.perform(MockMvcRequestBuilders.get("/person/1")
.contentType("application/json"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", Matchers.containsString("1")));
}
Upvotes: 1
Reputation: 40078
Try with ArgumentMatchers
Mockito.when(this.service.find(ArgumentMatchers.eq(1L)).thenReturn(mockLP);
Upvotes: 1