How to use a static variable without spoiling my unit tests?

I have a user-snippet class as shown below:

public class User
    {
        private int userID;
        private static int nextID = 99;
        private String firstName;
        private String lastName;
        private String email;
        private String password;
        private String fullName;

        public User()
        {
        }

        public User(String firstName, String lastName, String email, String password)
        {
            userID = nextID + 1;
            nextID++;
            this.firstName = firstName;
            this.lastName = lastName;
            fullName = firstName + " " + lastName;
            this.email = email;
            this.password = password;
        }

I want to provide users with a unique UserID that increases each time a user instance is created.

I tried to do this with a static int NextID to hold the user ID of the next object and increment it in the constructor after using it each time.

However, when I tried this, it messed up my unit tests, and some of them fail when I run all the tests, but they still pass when they run individually.

Does anyone know how I can achieve this without breaking my unit tests?

+2
2

.

, .

public interface IUserIdManager {
    int GetNextId();
}

public interface IUserFactory {
    User Create();
    User Create(String firstName, String lastName, String email, String password);
}

id, .

public class UserFactory : IUserFactory {
    private readonly IUserIdManager ids;
    public UserFactory(IUserIdManager ids) {
        this.ids = ids;
    }

    public User Create() { 
        var user = new User();
        user.UserId = ids.GetNextId();
        return user;
    }

    public User Create(String firstName, String lastName, String email, String password) { 
        var user = new User(firstName, lastName, email, password);
        user.UserId = ids.GetNextId();
        return user;
    }
}

. . POCO/ .

+3

, @Nkosi , . @Nkosi , , . , , !

public class UserIDGenerator : IUserIDGenerator
{
    private int nextUserID = 100;

    public int getNextUserID()
    {
        return nextUserID++;
    }
}

public class UserAdministration : IUserAdministration
{
    private List<User> users = new List<User>();

    private IUserIDGenerator userIDGenerator;

    public UserAdministration(IUserIDGenerator userIDGenerator)
    {
        this.userIDGenerator = userIDGenerator;
    }

    public bool addUser(String firstName, String lastName, String email, String password)
    {
        users.Add(new User(userIDGenerator.getNextUserID(), firstName, lastName, email, password));
        return true;
    }
}
+1

Source: https://habr.com/ru/post/1677091/


All Articles