Spring测试 - mock返回null

时间:2017-05-25 16:13:45

标签: spring spring-boot junit mocking

我对模拟方法有一个小问题。 mock应返回预定义对象,返回null。这是测试设置:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {

@Autowired
WebApplicationContext webContext;
@MockBean
UserTransferService userTransferService;
@MockBean
UserService userService;
MockMvc mockMvc;

private User user = DummyObjects.getDummyUser();
private User modifiedUser = DummyObjects.getModifiedUser();
private UserTO userTO = DummyObjects.getDummyUserTO();
private UserTO modifiedUserTO = DummyObjects.getModifiedUserTO();

@Before
public void setUp() throws Exception {
    List<User> users = new ArrayList<>();
    users.add(modifiedUser);
    users.add(user);
    given(this.userTransferService.getTO(user)).willReturn(userTO);
    given(this.userTransferService.getObject(userTO)).willReturn(user);
    given(this.userTransferService.getTO(modifiedUser)).willReturn(modifiedUserTO);
    given(this.userTransferService.getObject(modifiedUserTO)).willReturn(modifiedUser);
    given(this.userService.findAll()).willReturn(users);
    given(this.userService.save(user)).willReturn(user);
    given(this.userService.removeById(1)).willReturn(true);
    given(this.userService.getById(1)).willReturn(user);
    given(this.userService.getById(2)).willReturn(null);
    given(this.userService.modify(modifiedUser)).willReturn(modifiedUser);
    given(this.userService.findByLogin(user.getLogin())).willReturn(user);
    given(this.userService.findByLogin("AAA")).willReturn(null);

    mockMvc = MockMvcBuilders
            .webAppContextSetup(webContext)
            .apply(springSecurity())
            .build();
}

测试自己:

    @Test
public void shouldAddUser() throws Exception {
    mockMvc.perform(post("/api/user")
                    .content(TestingUtility.asJsonString(userTO))
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .with(csrf().asHeader()))
            .andExpect(status().is(200))
            .andExpect(content().json(TestingUtility.asJsonString(userTO)));
}

和控制器方法:

    @RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public UserTO modifyUser(@RequestBody UserTO userTO, UsernamePasswordAuthenticationToken principal) throws  IllegalAccessException{
    User user = userTransferService.getObject(userTO);
    if (principal.getName().equals(userTO.getLogin()) || permissionService.hasPermission(principal,Permission.SU)) {
        return userTransferService.getTO(userService.modify(user));
    } else {
        throw new IllegalAccessException("You are not allowed to modify user");
    }
}

用户为空,但UserTO已填写。因此,模拟方法UserTransferService.getObject(userTO)无法正常工作。

0 个答案:

没有答案