Ошибка проверки утверждения: исключение нулевой ссылки. В экземпляре объекта не задана ссылка на объект

Итак, у меня есть одна строка кода, которая вызывает у меня горе, но, к сожалению, без нее моя программа не работает. Это единственный способ, которым я могу придумать (кроме полной реструктуризации моей программы), делать то, что я хочу.

Цель этой строки - выбрать следующий класс для запуска (в меню), который находится за пределами его собственной области видимости. Проблема в том, что класс (Логин) существует в рамках меню.

Вот строка:

LoginView.Menu.SetMenuView();

Кто-нибудь может предложить лучший способ написания этого?

Технически, с линией все в порядке, программа работает без сбоев. Но когда я запускаю тест, он не проходит из-за исключения Null Reference.

Вот классы, в которых это появляется:

контроллер:

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);
    }

1 ответ

Решение

В вашем методе тестирования вы не устанавливаете значение для LoginView.Menu, который вы делаете в Show_Login(),

Поэтому, когда вы звоните Compare_Login() из теста, Menu нулевой.

Возможно, стоит изменить конструктор LoginView принять меню и убедиться, что ваш тест проходит что-то в.

Другие вопросы по тегам