Ожидаемая коллекция с размером 2, но размер коллекции был 0? - PullRequest
0 голосов
/ 03 апреля 2019

Я пишу некоторый код для тестирования веб-сервиса с использованием mockito и junit, поэтому я столкнулся с проблемой в hasSize (2), я ввел контроллер и вызвал метод findAll, который возвращает список Employe, но ошибкаpersist, в режиме отладки он говорит мне, что коллекция была пустой, но это не так.ошибка:

java.lang.AssertionError: путь JSON "$" Ожидается: коллекция с размером <2>, но: размер коллекции был <0>

вот класс:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class GestionPointage3ApplicationTests {

        private MockMvc mockMvc;
        @InjectMocks
        private EmployeController employeeController ; 
        @Mock
        private EmployeService employeeService;
        @Mock
        private ModelMapper modelMapper;
        @Before
        public void setUp() throws Exception{
            MockitoAnnotations.initMocks(this);
            mockMvc=MockMvcBuilders.standaloneSetup(employeeController).build();
        }

        @Test
        public void testgetAllEmployeeWithModelMapper() throws Exception{
            Employe emp1 = new Employe("Hamza", "Khadhri", "hamza1007", "123");
            Employe emp2 = new Employe("Oussema", "smi", "oussama", "1234");
            List<Employe> Employees= Arrays.asList(emp1, emp2);

            EmployeDTO dto1 = new EmployeDTO("Hamza", "Khadhri", "hamza1007", "123");
            EmployeDTO dto2 = new EmployeDTO("Oussema", "smi", "oussama", "1234");
            //when(modelMapper.map(emp1,EmployeDTO.class)).thenReturn(dto1);
           // when(modelMapper.map(emp2,EmployeDTO.class)).thenReturn(dto2);
            when(employeeService.findAll()).thenReturn(Employees);


            mockMvc.perform(get("/employe/dto"))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].nom", is("Hamza")))
                .andExpect(jsonPath("$[0].prenom", is("Khadhri")))
                .andExpect(jsonPath("$[0].login", is("hamza1007")))
                .andExpect(jsonPath("$[0].mp", is("123")))
                .andExpect(jsonPath("$[1].nom", is("Oussema")))
                .andExpect(jsonPath("$[1].prenom", is("smi")))
                .andExpect(jsonPath("$[1].login", is("oussama")))
                .andExpect(jsonPath("$[1].mp", is("1234")));

            verify(employeeService,times(1)).findAll();
            verifyNoMoreInteractions(employeeService);

        }

    }

и это Контроллер:

@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/employe")
public class EmployeController {

    @Autowired
    private EmployeService employeService;

    @Autowired
    private ModelMapper modelMapper;

    @GetMapping("/dto")
    public List<Employe> findAll() throws Exception{
    return employeService.findAllEmployeActive(); 
    }   
}

подпись метода:

public List<Employe>findAll() throws Exception;     
public List<Employe>findAllEmployeActive() throws Exception;

Ошибки StackTrace:

java.lang.AssertionError: Ожидаемый статус: <200>, но был: <500> в org.springframework.test.util.AssertionErrors.fail (AssertionErrors.java:55) в org.springframework.test.util.AssertionErrors.assertEquals (AssertionErrors.java:82) в org.springframework.test.web.servlet.result.StatusResultMatchers.lambda $ matcher $ 9 (StatusResultMatchers.java:619) в org.springframework.test.web.servlet.andMecpect.(MockMvc.java:178) в com.cynapsys.pointage.GestionPointage3ApplicationTests.testgetAllEmployeeWithModelMapper (GestionPointage3ApplicationTests.java:66) в sun.reflect.rce) at sun.reflect.DelegatingMethodAccessorImpl.invoke (Неизвестный источник) в java.lang.reflect.Method.invoke (Неизвестный источник) по адресу org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall (FrameworkMet50) или.junit.internal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:12) в org.junit.runners.model.FrameworkMethod.invokeExplosively (FrameworkMethod.java:47) в org.junit.inet.hote(.java: 83) в org.junit.internal.runners.statements.RunBefores.evaluate (RunBefores.java:26) в org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate (RunBeforeTestMate)..

1 Ответ

1 голос
/ 03 апреля 2019

Вы издеваетесь EmployeeService и говорите смоделированному экземпляру возвращать список Employee (с двумя его элементами) при вызове метода findAll():

when(employeeService.findAll()).thenReturn(Employees)

Но в EmployeeController вы фактически вызываете другой метод для EmployeeService:

return employeService.findAllEmployeActive()

Итак, вы должны обновить свое смоделированное ожидание следующим образом:

when(employeeService.findAllEmployeActive()).thenReturn(Employees)
...