如何在不搞乱单元测试的情况下使用静态变量? [英] How do I use a static variable without messing up my unit tests?
问题描述
我有一个用户类 - 片段如下:
I have a user class - snippet as 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;
}
我想给用户一个唯一的 UserID,每次实例化用户时都会增加.
I want to give users a unique UserID that increments each time a user is instantiated.
我尝试使用静态 int NextID 来保存下一个对象的 UserID,并在每次使用后在构造函数中递增它.
I tried doing this with a static int NextID to hold the UserID of the next object and increment it in the constructor after it is used each time.
然而,当我尝试这个时,它搞砸了我的单元测试,当我运行所有测试时,其中一些失败了,但它们在单独运行时仍然通过.
However, when I tried this, it messed up my unit tests and some of them fail when I Run All Tests but they all still pass when run individually.
有谁知道我如何在不搞乱单元测试的情况下实现这个目标?
Does anyone know how I can achieve this goal without messing up my unit tests?
推荐答案
这看起来像是一个设计问题.
This looks like a design issue.
例如,尝试分离所涉及的类的关注点.
For example, try separating the concerns of the classes involved.
public interface IUserIdManager {
int GetNextId();
}
public interface IUserFactory {
User Create();
User Create(String firstName, String lastName, String email, String password);
}
让用户管理器实现依赖于创建实例时要使用的 id 管理器.
Have the user manager implementation depend on the id manager to be used when creating instances.
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;
}
}
用户类不应该关心创建自己的 id.那不是它的责任.它应该保持精益,作为一个简单的 POCO/模型来保存数据.
The user class should not be concerned with creating its own id. That is not its responsibility. It should be kept lean as a simple POCO/model to hold data.
这篇关于如何在不搞乱单元测试的情况下使用静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!