わかりましたので、悲しみを引き起こしているコードが1行ありますが、残念ながらそれがないと、プログラムが壊れます。これは、私がやりたいことを実行するために (プログラムを完全に再構築する以外に) 考えられる唯一の方法です。
この行の目的は、次に実行するクラスを (メニューで) 選択することです。これは、独自のスコープ外です。問題は、メニューのスコープ内にクラス (Login) が存在することです。
ここに行があります:
LoginView.Menu.SetMenuView();
誰かがこれを書くためのより良い方法を提案できますか?
技術的には、この行に問題はなく、プログラムは問題なく動作します。しかし、テストを実行すると、Null 参照例外が原因でテストが失敗します。
表示されるクラスは次のとおりです。
コントローラ:
public void Show_Login(Menu_View Main_Menu)
{
// Creates an object of the User_LoginView.
// Set the Parent Form of the Child window
// Display the new form.
User_LoginView LoginView = new User_LoginView();
LoginView.MdiParent = Main_Menu;
// This line changes the reference to the "Menu" variable for later use.
LoginView.Menu = Main_Menu;
LoginView.Show();
}
public static void Compare_Login(User_LoginView LoginView)
{
// Creates a new object of User_Model and populates it from the User_Controller.
User_Model AccessModel = new User_Model();
AccessModel.Name = screenName;
AccessModel.Pwd = screenPwd;
// Runs the Login Comparsion in the Database_Facade, and passes in the Model.
Database_Facade Database = new Database_Facade();
Database.GetLoginAccess(AccessModel);
// screenAccess used for testing.
screenAccess = AccessModel.AccessLevel;
Menu_View.accessLevelSet = AccessModel.AccessLevel;
// If the return is placed here, the assert passes, but the rest of the code
// becomes unreachable.
// return;
// Compares the returned AccessLevel.
// if it is corect; closes the Login and runs the SetMenuView method,
// if it is incorrect; shows an error.
if (AccessModel.AccessLevel > 0)
{
Console.WriteLine("Access Level " + AccessModel.AccessLevel);
LoginView.Menu.SetMenuView();
LoginView.Close();
Menu_View.accessLevelSet = AccessModel.AccessLevel;
}
else
{
ErrorCodes_Controller LoginError = new ErrorCodes_Controller();
LoginError.WrongLoginError();
}
}
意見:
public partial class User_LoginView : Form
{
// This is where the new reference is set, for when it gets called
// at the end of the Login Comparison.
public Menu_View Menu { get; set; }
public User_LoginView()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
User_Controller.Check_Login(this);
}
}
テストは次のとおりです。
[TestMethod()]
public void Compare_LoginTest()
{
User_LoginView LoginView = new User_LoginView();
User_Controller.screenName = "ben";
User_Controller.screenPwd = "password";
User_Controller.Compare_Login(LoginView);
int actual = User_Controller.screenAccess;
int expected = 1;
Assert.AreEqual(expected, actual);
}