user8728263
user8728263

Reputation:

Unit test for services

I have a services class UserServiceImpl with a method creatUser()

@Autowired
    private UserRepository  userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Override
    public User createUser(User user, Set<UserRole> userRoles) throws DataAccessException {
        User localUser = userRepository.findByUsername(user.getUsername());

        if (localUser != null) {
            LOG.info("user {} already exists. Nothing will be done.", user.getUsername());
        } else {
            for (UserRole ur : userRoles) {
                roleRepository.save(ur.getRole());
            }
            user.getUserRoles().addAll(userRoles);

            localUser = userRepository.save(user);
        }
        return localUser;
    }

I am trying to test this with unit test but don't know how to go about it . Any help would suffice .here is my test case .

 @Test
    public void createUserTest() {
        UserServiceImpl usr = new UserServiceImpl();
        User user = new User();

        String[] SET_VALUES = new String[]{"ADMIN"};

        UserRole userRole = new UserRole();

        userRole.setRole(role);
        Set<String> myset = new HashSet<String>(Arrays.asList(SET_VALUES));

        ObjectMapper objectMapper = new ObjectMapper();

        String[] GPXFILES1 = myset.toArray(new String[myset.size()]);

        usr.createUser(user,myset.toArray());


    }

right now I am stuck here , and I don't know how to pass a set as a parameter input

Upvotes: 2

Views: 168

Answers (1)

Pmakari
Pmakari

Reputation: 274

You can inject the service interface

 @Autowired UserService userService; 

 @Test
 public void createUserTest() {   
    //asserts
        }

In this case you are doing Integration test not unit test. For unit test you will have to mock the object, e.g. you can use Mockito framework.

Upvotes: 2

Related Questions