简体   繁体   中英

How to handle Invalidoperationexception when run the unit test in c#

I wrote the unit test using MOQ. When setup the mock I am trying to create the object of class in Linq query. After that I am trying to run the Unit test, but I get below error message.

"When called from 'VisitMemberInit', rewriting a node of type 'System.Linq.Expressions.NewExpression' must return a non-null value of the same type. Alternatively, override 'VisitMemberInit' and change it to not visit children of this type."

I have written code like below -

    _mockLdapAuthenticatorService.Setup(x => x.Authenticate(
                        new LoginRequest { 
                                Username = It.IsAny<string>(), 
                                Password = It.IsAny<string>() })).
                                Returns(new     AuthenticationResult { Success = true });

Update the setup. The following is probably what you were trying to achieve.

_mockLdapAuthenticatorService
   .Setup(x => x.Authenticate(It.IsAny<LoginRequest>()))
   .Returns(new AuthenticationResult { Success = true });

For me, a problem was this new operator when sending parameters to a function. When I create a variable for it and then send the variable as a parameter it worked without error.

NO:

 var absentUser = _fixture.Create<User>();
  var absentUsers = new List<User> { absentUser }.AsQueryable();
  _unitOfWorkMock.Setup(_ => _.UserRepository
  .GetAllConfirmedUsersForGroupIds(new List<int> { It.IsAny<int>() }))
                   .Returns(absentUsers);

YES:

var absentUser = _fixture.Create<User>();
 var absentUsers = new List<User> { absentUser }.AsQueryable();
 var groupIds = new List<int> { It.IsAny<int>() };
 _unitOfWorkMock.Setup(_ => _.UserRepository.GetAllConfirmedUsersForGroupIds(groupIds))
                   .Returns(absentUsers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM