below is my controller:
@RestController
@RequestMapping("/Employee")
public class Employeecontroller {
@Autowired
Employeeservice empservice;
@PostMapping("/addEmployee") // adding emp details into the table
public Employee addemployee(@RequestBody Employee emp)
{
empservice.saveemp(emp);
return emp;
}
}
- this is the empservice class:
@Service
public class Employeeservice {
@Autowired
EmployeeRepository emprepo;
public Employee saveemp(Employee emp) {
System.out.println("inside save emp");
return emprepo.save(emp);
}
}
(here i dont want to call to emprepo.save(emp) method, which is a database call, so i used Mockito.when and then methods in below test class) below is the test class:
@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
@AutoConfigureMockMvc
class RestServiceApplicationTests {
@Autowired
private MockMvc mvc;
@Autowired
ObjectMapper objectMapper;
@MockBean
Employeeservice empservice;
Employee reqemp = new Employee("Bob", "java");
@Test
public void testaddemp() throws Exception {
when(empservice.saveemp(reqemp)).thenReturn(new Employee(1, "Bob", "java"));
RequestBuilder request = MockMvcRequestBuilders.post("/Employee/addEmployee")
.contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(reqemp));
MockHttpServletResponse returnedemp = (MockHttpServletResponse) mvc.perform(request).andExpect(status().isOk())
.andReturn().getResponse();
Employee expectedemp = new Employee(1, "Bob", "java");
assertEquals(objectMapper.writeValueAsString(expectedemp), returnedemp.getContentAsString());
}
}
Testcase failed with:
org.opentest4j.AssertionFailedError: expected: <{"id":1,"name":"Bob","tech":"java"}> but was: <{"id":0,"name":"Bob","tech":"java"}>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
at com.easytocourse.demo.RestServicewithActuatorApplicationTests.testaddemp(RestServicewithActuatorApplicationTests.java:55)
when i use @Mock or @SpyBean it is returning expected employee object
Please help me in understanding why @MockBean is not working?
Please clarify the below points
1. what is the difference between @Mock, @MockBean, @SpyBean, @InjectMock annotations, when to use these annotations?