Home > Blockchain >  C# unit testing with mstest and mockink unexpected error
C# unit testing with mstest and mockink unexpected error

Time:10-11

My testing code threw following error for unknow reason. Probably setting up mocking incorrectly but I have no idea how to do it right please help.

Message: Test method GUI_VIS.MsTests.LoginTest.TestEmptyIsAdminWindow threw exception: System.NotSupportedException: Unsupported expression: x => x.GetAllEmailAsync("Pepa", "Heslo", new Worker() { }) Non-overridable members (here: GenericController.GetAllEmailAsync) may not be used in setup / verification expressions.

Stack Trace: Guard.IsOverridable(MethodInfo method, Expression expression) line 109 MethodExpectation.ctor(LambdaExpression expression, MethodInfo method, IReadOnlyList1 arguments, Boolean exactGenericTypeArguments, Boolean skipMatcherInitialization, Boolean allowNonOverridable) line 87 ExpressionExtensions.<Split>g__Split|5_0(Expression e, Expression& r, MethodExpectation& p, Boolean assignment, Boolean allowNonOverridableLastProperty) line 219 ExpressionExtensions.Split(LambdaExpression expression, Boolean allowNonOverridableLastProperty) line 150 Mock.SetupRecursive[TSetup](Mock mock, LambdaExpression expression, Func4 setupLast, Boolean allowNonOverridableLastProperty) line 643 Mock.Setup(Mock mock, LambdaExpression expression, Condition condition) line 498 Mock1.Setup[TResult](Expression1 expression) line 452 LoginTest.TestEmptyIsAdminWindow() line 48 ThreadOperations.ExecuteWithAbortSafety(Action action)

    [TestMethod]
    public async Task TestEmptyIsAdminWindow()
    {
        Login login = new Login();

        Mock<GenericController> gcMock = new Mock<GenericController>();
        GenericController gc = new GenericController();

        login.IdBoxGet().Text = "John";
        login.PasswordBoxGet().Text = "Password";
        

        ObservableCollection<Worker> workers = new ObservableCollection<Worker>() {
            new Worker
            {
                Name = "John",
                My_password = "Password",
                Role = "Boss"
            }
        };

        gcMock.Setup(x => x.GetAllEmailAsync("John", "Heslo", new Worker() { }))
            .ReturnsAsync(workers);
        
        var workersFromMocking = await gc.GetAllEmailAsync("John", "Password", new Worker() { });


        Assert.IsTrue(workersFromMocking[0].Name == "John");
    }

CodePudding user response:

Firstly, you are not using the gcMock and login objects anywhere. In your case the SUT (system under test) is gc. A mock should be something that gc uses while calling the method that you want to test, not the GenericController itself.

Secondly, your error states that the GetAllEmailAsync method is not overridable. Moq can only work with abstract, virtual or interface methods. See the accepted answer to this question for clarification.

  • Related