有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java模拟执行PUT函数的控制器

我试图创建一个模拟我的控制器来更新用户内部的数据。从代码中,我尝试只更新电子邮件、密码和年龄。我们应该这样做吗?因为我对Mockito和Junit还很陌生

Controller Mock

@Test
public void testUpdateUserController() throws Exception{
    String username = "User";
    String email = "user@email.com";
    String password = "password123";
    int age = 90;
 Mockito.when(userService.updateUser(username,email,password,age)).then(invocationOnMock -> {
     User user = new User();
     user.setUsername("User");
     user.setEmail("user@user.com");
     user.setPassword("123456");
     user.setAge(12);
     user.setAddress("11111");
     user.setIsActive(true);
     return Optional.of(user);
 });
 mockMvc.perform(MockMvcRequestBuilders.put(BASE_URL + "/users/{username}",username)
         .contentType(MediaType.APPLICATION_JSON_UTF8)).andExpect(MockMvcResultMatchers.status().isOk());
 Mockito.verify(userService, Mockito.times(1)).updateUser(userCaptor.capture(),emailCaptor.capture(),passwordCaptor.capture(),ageCaptor.capture());
    Assert.assertEquals("User", userCaptor.getValue());
    Assert.assertEquals("user@email.com", emailCaptor.getValue());
    Assert.assertEquals("password123", passwordCaptor.getValue());
    Assert.assertEquals("90", ageCaptor.getValue());
    Assert.assertEquals("11111", addressCaptor.getValue());
}

UserServiceImpl

@Override
public boolean updateUser(String username, String email, String password, Integer age) {
    Optional<User> userList = userRepository.findByUsernameAndIsActiveTrue(username);
    if (userList.isPresent()) {
        User user = userList.get();
        user.setEmail(email);
        user.setPassword(password);
        user.setAge(age);
        userRepository.save(user);
        return true;
    } else {
        return false;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    下面是我的一个MVC模拟代码示例

    @RunWith(PowerMockRunner.class)
    public class TrainingControllerTest {
    
        @Mock
        private TrainingService trainingService;
    
        @Mock
        private FileStorageService fileStorageService;
    
        @InjectMocks
        private TrainingController controller = new TrainingController();
    
    
        private MockMvc mockMvc;
    
    
        @Before
        public void setup() {
            this.mockMvc = MockMvcBuilders.standaloneSetup(controller)
                    .setControllerAdvice(new ExceptionController())
                    .build();
        }
    
        @Test
        public void testCreateHappyPath() throws Exception {
            Training training = new Training();
            Optional<Training> result = Optional.of(training);
            TrainingExt ext = result
                    .map(TrainingExt::of)
                    .get();
    
            when(trainingService.createTraining(any(Training.class))).thenReturn(result);
    
            ObjectMapper mapper = new ObjectMapper();
            String trainingPayloadJSON = mapper.writerFor(Training.class).writeValueAsString(training);
            String trainingExtJSON = mapper.writerFor(TrainingExt.class).writeValueAsString(ext);
    
            mockMvc.perform(MockMvcRequestBuilders.post(TestConstants.POST_TRAINING_URI)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(trainingPayloadJSON)
            )
                    .andExpect(status().isCreated())
                    .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(content().json(trainingExtJSON));
        }
    
        @Test
        public void testPutHappyPath() throws Exception {
            Training training = new Training();
            Optional<Training> result = Optional.of(training);
            TrainingExt ext = result
                    .map(TrainingExt::of)
                    .get();
    
            when(trainingService.update(any(Training.class))).thenReturn(result);
    
            ObjectMapper mapper = new ObjectMapper();
            String trainingPayloadJSON = mapper.writerFor(Training.class).writeValueAsString(training);
            String trainingExtJSON = mapper.writerFor(TrainingExt.class).writeValueAsString(ext);
    
            mockMvc.perform(MockMvcRequestBuilders.put(TestConstants.GET_PUT_DELETE_TRAINING_URI, TestConstants.ID)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(trainingPayloadJSON)
            )
                    .andExpect(status().isOk())
                    .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(content().json(trainingExtJSON));
        }
    
        @Test
        public void testAddAttendeesHappyPath() throws Exception {
            Attendees attendees = new Attendees();
            Optional<Training> result = Optional.of(new Training());
            TrainingExt ext = result
                    .map(TrainingExt::of)
                    .get();
    
            when(trainingService.registerTrainingAttendees(any(Attendees.class))).thenReturn(result);
    
            ObjectMapper mapper = new ObjectMapper();
            String attendeesPayloadJSON = mapper.writerFor(Attendees.class).writeValueAsString(attendees);
            String trainingExtJSON = mapper.writerFor(TrainingExt.class).writeValueAsString(ext);
    
            mockMvc.perform(MockMvcRequestBuilders.post(TestConstants.ADD_ATTENDEES_URI)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(attendeesPayloadJSON)
            )
                    .andExpect(status().isCreated())
                    .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                    .andExpect(content().json(trainingExtJSON));
        }
    }