StoreCode
StoreCode

Reputation: 155

Java: Testing Concrete Class passing by Interface, Mockito, JUnit

I have this interface:

public interface RepositoryUserDB {

    User createUser(User user);
}

and the method implemented into the following class:

public class MemoryUserDB implements RepositoryUserDB{

    Map<String, User> repo = new HashMap<>();

    @Override
    public User createUser(User user) {
        return repo.put(user.getUsername(), user);
    }
}

The target is to test the method. I started to write this, but I think it is not correct:

@Test
public void testCreateUser(){
    User result = new User("luca", "antico", "23.11.2011", "112");
    Assert.assertEquals("luca", result.getUsername());
}

How can I accomplish it?

Thanks

edit:

the class User:

 public class User {

    private String username;
    private String password;
    private String dateOfBirth;
    private String SSN;

    public User(String username, String password, String dateOfBirth, String SSN) {
        this.username = username;
        this.password = password;
        this.dateOfBirth = dateOfBirth;
        this.SSN = SSN;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public String getSSN() {
        return SSN;
    }
}

Upvotes: 1

Views: 230

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26572

Frankly, that test does not add much of a value.

What you should aim for is to verify whether the repo contains the user that you have passed through that method.

Assuming you have some kind of getByUserName method on that repo, and the User class has equals and hashCode properly defined, you could go for a test like this:

private MemoryUserDB memoryUserDB;

@Test
public void shouldCreateUser(){
   // Arrange
   User user = new User("luca", "antico", "23.11.2011", "112");

   // Act
   User addedUser = memoryUserDB.createUser(user);

   // Assert
   assertEquals(user, addedUser);
   assertEquals(user, memoryUserDB.getByUsername("luca");
}

Also try not to put test in your test method names, try to explain the bahavior through the name.

Upvotes: 2

Related Questions