在测试期间如何强制返回实现方法?

时间:2019-06-27 19:35:54

标签: spring-boot mockito jhipster

我正在Spring和Service类中测试一个休息请求,在保存发送的对象之前,有必要调用一个接口方法来实现微服务之间的通信,但是在测试中不存在其他微服务。我该如何模拟此接口的方法,以便在测试期间在Service中运行时返回特定值?

我尝试了以下操作:

带有摘要代码的测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SecurityBeanOverrideConfiguration.class, AccountApp.class})
public class UserSystemResourceIntTest {

    @MockBean
    private UaaAccountInternalRequest uaaAccountInternalRequest;

    private MockMvc restUserSystemMockMvc;

    private UserSystem userSystem;

    @Autowired
    private JhiUserUaaVM jhiUserUaaVM;


    @Test
    @Transactional
    public void createUserSystem() throws Exception {
        int databaseSizeBeforeCreate = userSystemRepository.findAll().size();

    // Attempt to do method mock
        given(uaaAccountInternalRequest.addJhiUserUaa(jhiUserUaaVM))
                .willReturn(11);

        // Create the UserSystem
        UserSystemDTO userSystemDTO = userSystemMapper.toDto(userSystem);

        userSystemDTO.setLangKey(DEFAULT_LANG_KEY);

        restUserSystemMockMvc.perform(post("/api/user-systems")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(userSystemDTO)))
            .andExpect(status().isCreated());

        // Validate the UserSystem in the database
        List<UserSystem> userSystemList = userSystemRepository.findAll();
        assertThat(userSystemList).hasSize(databaseSizeBeforeCreate + 1);
        UserSystem testUserSystem = userSystemList.get(userSystemList.size() - 1);
        assertThat(testUserSystem.getName()).isEqualTo(DEFAULT_NAME);
        assertThat(testUserSystem.getEmail()).isEqualTo(DEFAULT_EMAIL);
        assertThat(testUserSystem.getPhone()).isEqualTo(DEFAULT_PHONE);
        assertThat(testUserSystem.getDocumentCode()).isEqualTo(DEFAULT_DOCUMENT_CODE);
        assertThat(testUserSystem.getDocumentType()).isEqualTo(DEFAULT_DOCUMENT_TYPE);
        assertThat(testUserSystem.getGender()).isEqualTo(DEFAULT_GENDER);
        assertThat(testUserSystem.getCreatedOn()).isNotNull(); //isEqualTo(DEFAULT_CREATED_ON);
        assertThat(testUserSystem.getUpdateOn()).isNull(); // EqualTo(DEFAULT_UPDATE_ON);
        assertThat(testUserSystem.isActive()).isEqualTo(DEFAULT_ACTIVE);
        assertThat(testUserSystem.getUserId()).isEqualTo(DEFAULT_USER_ID);

        // Validate the UserSystem in Elasticsearch
        verify(mockUserSystemSearchRepository, times(1)).save(testUserSystem);
    }


}

剩余的实现代码:

通信接口:

@AuthorizedFeignClient(name = "uaa-account-service", url= "http://localhost:8080/uaa")
@RequestMapping("/api")
public interface UaaAccountInternalRequest {

    @PostMapping(path = "/register")
    public Integer addJhiUserUaa(@RequestBody JhiUserUaaVM object);

}

RestController:

@RestController
@RequestMapping("/api")
public class UserSystemResource {

    @PostMapping("/user-systems")
    public ResponseEntity<UserSystemDTO> createUserSystem(@Valid @RequestBody UserSystemDTO userSystemDTO) throws URISyntaxException {
        log.debug("REST request to save UserSystem : {}", userSystemDTO);
        if (userSystemDTO.getId() != null) {
            throw new BadRequestAlertException("A new userSystem cannot already have an ID", ENTITY_NAME, "idexists");
        }
        UserSystemDTO result = userSystemService.save(userSystemDTO);
        return ResponseEntity.created(new URI("/api/user-systems/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }
}

服务:

@Service
@Transactional
public class UserSystemService {

    private final Logger log = LoggerFactory.getLogger(UserSystemService.class);

    private final UserSystemRepository userSystemRepository;

    private final UserSystemMapper userSystemMapper;

    private final UserSystemSearchRepository userSystemSearchRepository;

    private final UaaAccountInternalRequest uaaAccountInternalRequest;

    public UserSystemService(UserSystemRepository userSystemRepository, UserSystemMapper userSystemMapper, UserSystemSearchRepository userSystemSearchRepository, UaaAccountInternalRequest uaaAccountInternalRequest) {
        this.userSystemRepository = userSystemRepository;
        this.userSystemMapper = userSystemMapper;
        this.userSystemSearchRepository = userSystemSearchRepository;
        this.uaaAccountInternalRequest = uaaAccountInternalRequest;
    }

    public UserSystemDTO save(UserSystemDTO userSystemDTO) {
        log.debug("Request to save UserSystem : {}", userSystemDTO);

        // requisição para o serviço UAA para criar o jhi_user do login
        JhiUserUaaVM jhiUser = new JhiUserUaaVM();

        // Authorities default
        Set<String> authorities = new HashSet<>();
        authorities.add("ROLE_USER");

        String userName = userSystemDTO.getName();
        String[] splitUserName = userName.split(" ");

        jhiUser.setLogin(userSystemDTO.getEmail());
        jhiUser.setEmail(userSystemDTO.getEmail());
        jhiUser.setPassword(userSystemDTO.getPassword());
        jhiUser.setLangKey(userSystemDTO.getLangKey());
        jhiUser.setAuthorities(authorities);

        // seta os campos referentes ao nome do usuário
        if (splitUserName.length > 0) {
            jhiUser.setFirstName(splitUserName[0]);

            if (splitUserName.length >= 2) {
                jhiUser.setLastName(splitUserName[(splitUserName.length-1)]);
            } else {
                jhiUser.setLastName("");
            }
        } else {
            jhiUser.setFirstName("");
            jhiUser.setLastName("");
        }

        // envia dados para o UAA para criar o registro de user login
        Integer jhiUserId = uaaAccountInternalRequest.addJhiUserUaa(jhiUser);

        // set informações pendentes (uesrId, active default true, createdOn)
        userSystemDTO.setActive(true);
        userSystemDTO.setUserId(jhiUserId);
        userSystemDTO.setCreatedOn(Instant.now());

        // convert DTO para Entity
        UserSystem userSystem = userSystemMapper.toEntity(userSystemDTO);

        // salva no banco e no Elasticsearch
        userSystem = userSystemRepository.save(userSystem);
        UserSystemDTO result = userSystemMapper.toDto(userSystem);
        userSystemSearchRepository.save(userSystem);

        return result;
    }


}

0 个答案:

没有答案