如何使用的Mockito和JUnit测试我的春天启动REST API?

问题描述 投票:0回答:2

我在单元测试新并不能弄清楚如何使用的Mockito和JUnit春天,首先我已经preapared中,我创建了两个方法与@Before和@Test,当我把在调试类测试RESTful API模式它告诉我,hasSize集合返回0不是4。

@RunWith(SpringJUnit4ClassRunner.class)
public class EmployeControllerTest {
    private MockMvc mockMvc;
    @InjectMocks
    private EmployeController employeController ; 
    @Mock
    private EmployeService employeService ;

    @Before
    public void setUp() throws Exception{
        MockitoAnnotations.initMocks(this);
        mockMvc=MockMvcBuilders.standaloneSetup(employeController).build();
    }
    @Test
    public void testgetAllEmployee() throws Exception{
        List<Employe> employes= Arrays.asList(
                new Employe("Hamza", "Khadhri", "hamza1007", "123")
                ,new Employe("Oussema", "smi", "oussama", "1234") );
        when(employeService.findAll()).thenReturn(employes);
        mockMvc.perform(get("/employe/dto"))
        .andExpect(status().isOk())
        .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$", hasSize(4)))
         .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(employeService,times(1)).findAll();
        verifyNoMoreInteractions(employeService);
    }
}

这里是EmployeController:

    @CrossOrigin(origins = "*", allowedHeaders = "*")
    @RestController
    @RequestMapping("/employe")
    public class EmployeController {
        @Autowired
        private EmployeService employeService;

        @Autowired
        private ModelMapper modelMapper;

        @GetMapping("/dto")
        public List<EmployeDTO> getEmployeDTOList(){
            try {
                    List<Employe> listemp=employeService.findAllEmployeActive();
                    return listemp.stream()
                        .map(emp ->convertToDto(emp))
                        .collect(Collectors.toList());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

        private EmployeDTO convertToDto(Employe emp) {
            EmployeDTO empDto = modelMapper.map(emp, EmployeDTO.class);

            return empDto;
       }
   }

当我打开调试模式,它告诉我,有NullPointerException

如何使用正确mockitojunit成功测试?

spring-boot junit mockito hamcrest
2个回答
1
投票

我看到一些潜在的问题:

首先,你在呼唤

List<Employe> listemp=employeService.findAllEmployeActive();

在你的控制器的getEmployeDTOList(),但你假装的Mockito写为:

when(employeService.findAll()).thenReturn(employes)

所以,你的测试可能无法工作,只是因为你模仿从未发生过。

其次,你有没有嘲笑,你在你的控制器自动装配的ModelMapper。我觉得春天还是会继续前进,抓住这部分你(有人纠正我,如果我错了),但无论哪种方式,它不是伟大实践中有你的单元测试依赖于外部库,因为你应该只与被关注控制器的功能。这将是更好嘲笑ModelMapper使它“永远”的工作,并编写单独的测试,以验证您的映射。

我继续做我自己的代码的版本测试的东西出来。我因为你只用在你的榜样两个元素改变hasSize为2。

这个测试是为我工作:

@RunWith(SpringJUnit4ClassRunner.class)
public class EmployeeControllerTest {

    private MockMvc mockMvc;
    @InjectMocks
    private EmployeeController employeeController ; 
    @Mock
    private EmployeeService 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{
        Employee emp1 = new Employee("Hamza", "Khadhri", "hamza1007", "123");
        Employee emp2 = new Employee("Oussema", "smi", "oussama", "1234");
        List<Employee> Employees= Arrays.asList(emp1, emp2);

        EmployeeDTO dto1 = new EmployeeDTO("Hamza", "Khadhri", "hamza1007", "123");
        EmployeeDTO dto2 = new EmployeeDTO("Oussema", "smi", "oussama", "1234");
        when(modelMapper.map(emp1,EmployeeDTO.class)).thenReturn(dto1);
        when(modelMapper.map(emp2,EmployeeDTO.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);

    }

}

正如你可以看到我创造我自己的DTO对象并将其传回,这样modelMapper总是像预期的那样为这个单元测试。


0
投票

这是工作的代码,但它忽略了对象EMP1:

 public void testgetAllEmployeeWithModelMapper() throws Exception{
         Employe emp1 = new Employe("Hamza", "Khadhri", "hamza1007", "123");
         Employe emp2 = new Employe("Oussem", "smi", "oussama", "1234");
         List<Employe> Employees= Arrays.asList(emp1, emp2);
         EmployeDTO dto1 = new EmployeDTO("Hamza", "Khadhri", "hamza1007", "123");
         EmployeDTO dto2 = new EmployeDTO("Oussem", "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);
    }

}

该cosole我表明jsonPath(“$ [0] .nom”预计Oussema所以当我将其更改为Oussema它是对象EMP2和它工作得很好。不幸的是它忽略了包含哈姆扎的对象EMP1,personnaly我只是添加两构造函数雇工和EmployeDTO。

这是类雇工:

 public class Employe implements Serializable {



    @Id
    @Column(unique=true, nullable=false, precision=6)
    private Long id;
    @Column(precision=6)
    private BigDecimal cv;
    @Column(length=254)
    private String nom;
    @Column(length=254)
    private String prenom;
    @Column(length=254)
    private String login;
    @Column(length=254)
    private String mp;
    @Column(length=254)
    private String mail;
    @Column(precision=6)
    private BigDecimal idpointage;
    @Column(length=1)
    private Boolean actif;
    public Employe(String nom, String prenom, String login, String mp) {

        this.nom = nom;
        this.prenom = prenom;
        this.login = login;
        this.mp = mp;
    }

这是类EmployeDTO:

public class EmployeDTO {
        private String nom;
        private String prenom;
        private String login ; 
        private String mp ; 


        public EmployeDTO(String nom, String prenom, String login, String mp) {

            this.nom= nom ; 
            this.prenom= prenom ; 
            this.login = login ; 
            this.mp=mp ;
        }
© www.soinside.com 2019 - 2024. All rights reserved.