Referring to this question:
Moq how to replace obsolete expression
I have the following:
[Test]
public void OnSearchRequest_ViewFiresEvent_EventIsHandled()
{
// Arrange
Mock<IViewUsers> view = new Mock<IViewUsers>();
Users users = new Users(view.Object);
// Act
view.Raise(v => v.SearchForUsers += null, this, new SearchEventArgs());
// Assert
view.VerifySet(v=> v.SearchResult = It.IsAny<List<IUser>>());
}
originally I had:
// Assert
view.VerifySet(v => v.SearchResult);
But was getting the warning:
'Moq.MockExtensions.VerifySet(Moq.Mock,
System.Linq.Expressions.Expression>)' is
obsolete: 'Replaced by VerifySet(Action)'
So I found the question referenced above, and changed it to match, but now I'm STILL getting that warning, and on top of that, a hard error on "v.SearchResult" within the call to VerifySet :
An expression tree may not contain an assignment operator.
I can't see that I'm formatting this improperly - so why isn't it recognizing this as an action as the other question implies it should?
I found something relatively close to what you are asking about. Moq how to replace obsolete expression I don't know if this helps because I only ever used mock.Setup and mock.Verify.
Also as mentioned before try using lambda expressions within your It.IsAny to pinpoint smaller things this way . If a verify fails you know exactly where it failed. Especially if you are expecting a value at a certain position for example.
I don't know if it helps, but I've had problems in the past using It.IsAny<> with lists. Could you try something like It.Is<List<IUser>>(l => l != null)?
Related
I am trying to create a function that evaluates a DynamicLinq expression. While the expression itself is valid, the Parameter objects it has available to use may not always be what it needs.
I would like some method of checking if I have all the Parameters available that the expression needs before actually executing it. Currently the best option I have found is to wrap it in a try-catch and ignore the missing param exception.
var ValidLambdaExpression = "ObjectType.Attribute == \"testvalue\" && ObjectType2.Attribute == \"testvalue2\"";
var paramObjects = new List<System.Linq.Expressions.ParameterExpression>();
var p = System.Linq.Expressions.Expression.Parameter(typeof(ObjectType), "ObjectType");
paramObjects.Add(p);
var lam = System.Linq.Dynamic.DynamicExpression.ParseLambda(paramObjects.ToArray(), null, ValidLambdaExpression);
//var lambody = System.Linq.Dynamic.DynamicExpression.Parse(null, ValidLambdaExpression);
//var lam = System.Linq.Expressions.Expression.Lambda(lambody, paramObjects);
var result = DataValidation.ToBoolean(lam.Compile().DynamicInvoke(data));
In the block of code above, the ValidLambdaExpression variable may be referencing objects that do not exist in the data array. If that happens both the ParseLambda and Parse lines blow up. I have not found any method of parsing the lambda then checking for missing parameters, or even required parameters.
This block will blow up with the error:
ParseException -> Unknown identifier 'ObjectType2'
At the time of execution paramObjects gets dynamically built, it is not hard coded, so I do not know what objects will be put into it.
Does anyone have a better method "in terms of speed" of validating what parameters the Lambda needs before parsing it?
It seems as though no one had a solution for this problem. Here is the work-around I ended up coming up with.
At the time the Lambda expression was being built, I knew which objects were being put into it, even if I did not have that information by the time I needed to use the expression.
So I ended up prefixing the expression with a csv list of objects so I could gain access to them in the method that was using the expression.
The expression ended up looking like this:
ObjType1,ObjType2,ObjType3|ObjType1.Attribute == ObjType2.Attribute
Then I wrote a wrapper around the DynamicExpressionParser that was able to parse this string and make some intelligent decisions off of it before trying to invoke the expression.
I am trying to write a custom rule (code analysis) where, if the body of a method contains empty statements, an error is raised.
However, there is one problem. I can not seem to figure out how to get the body of a method (the text that is in the method).
How can I get the text inside a method, and assign it to a string?
Thanks in advance.
For reference; I use c# in visual studio, with FxCop to make the rule.
Edit: Some code added for reference, this does NOT work.
using Microsoft.FxCop.Sdk;
using Microsoft.VisualStudio.CodeAnalysis.Extensibility;
public override ProblemCollection Check(Member member)
{
Method method = member as Method;
if (method == null)
{
return null;
}
if (method.Name.Name.Contains("{}"))
{
var resolution = GetResolution(member.Name.Name);
var problem = new Problem(resolution, method)
{
Certainty = 100,
FixCategory = FixCategories.Breaking,
MessageLevel = MessageLevel.Warning
};
Problems.Add(problem);
}
return Problems;
}
FxCop doesn't analyse source code, it works on .Net assemblies built from any language.
You may be able to find whether the method contains a statement or not using FxCop, I advice you to read the documentation and check the implementation of existing rules to understand it.
An empty statement in the middle of other code might be removed by the compiler and you may not find it using FxCop. If you want to analyze source code you should take a look at StyleCop.
However, there is one problem. I can not seem to figure out how to get the body of a method
(the text that is in the method).
You can not. FxCop does not work based on the source, but analysis the compiled bytecode.
What you can do is find the source - which is not totally trivial - but you have to do so without the FxCop API. A start point may be analysing the pdb files (not sure where to find documentation) as they can point you to the file that contains the method.
I am trying to use learn how to use FakeItEasy, and wanted to try using it with some data access code from an old project I have access to. While the basics of FIE seemed pretty easy, and I was able to get simple cases working, this one has me stumped.
The system used Entity Framework, and one of the data management classes handles Users, and I'm trying to figure out how to test just the basic GetUserByUserNumber function. I can use a fake IPersistenceManager<User> when instantiating the UserDataManager class, and then call the GetUserByUserNumber method, but the assertion to check that userPersistenceManager.ReadCustom was called always fails.
I've tried calling the Delete method on the fake userPersistenceManager, and the assertion for that works fine. I think it has something to do with the Linq Expression that the ReadCustom method takes as its first parameter. I just don't know how that should be handled. Any help with this would be appreciated!
This is the method in the UserDataManager that I'm trying to test:
public User GetUserByUserNumber(string userNumber, bool loadRelatedRecords = false)
{
if (string.IsNullOrWhiteSpace(userNumber))
{
throw MyAppExceptions.CreateMyAppFatalException(Constants.ExceptionKeys.Unexpected, new ArgumentNullException("userNumber"));
}
Logger.Write(string.Format("Executing GetUserByUserNumber with UserNumber {0}.", userNumber), LogCategory.General, TraceEventType.Verbose);
return _UserPersistenceManager.ReadCustom(mem => mem.UserNumber == userNumber, EntityConstants.EntityNames.UserDetail);
}
This is the IPersistenceManager method that I want to ensure is called:
TEntity ReadCustom(Expression<Func<TEntity, bool>> predicate, string includeEntityName);
This is my unit test:
[TestMethod]
public void GetUserByUserNumber_Calls_ReadCustom()
{
// Arrange
var userPersistenceManager = A.Fake<IPersistenceManager<User>>();
var dataManager = new UserDataManager(userPersistenceManager);
// Act
dataManager.GetUserByUserNumber("123456", false);
// Assert
A.CallTo(() => userPersistenceManager.ReadCustom(u => u.UserNumber == "123456", EntityConstants.EntityNames.UserDetail)).MustHaveHappened();
}
I think Tim Long's answer is essentially correct although my slant is not that this is a failing of mocking frameworks—it comes down to how easy it is (in general, not just when mocking) to determine whether two things are "the same".
The problem you have is that unless told otherwise, FakeItEasy uses .Equals to compare the arguments. Expressions don't compare well with .Equals, and so you'll get a mismatch.
One option is to explore Expression equality-checkers. There are a number of questions on StackOverflow about this already, such as How to check if two Expression<Func<T, bool>> are the same. If you can find a good way to determine the equality of the expressions, I think you could provide that method to FakeItEasy's argument matcher
(e.g. with A<Expression<Func<TEntity, bool>>.That.Matches(…)).
Alternatively, you can go Mr. Long's route and capture the argument and then interrogate it later. I suggested a similar approach just a bit ago when answering
How to fake an action<> with FakeItEasy.
In your case, you could capture the predicate and then verify its correctness by seeing how it reacts to various input objects - does it like ones with UserNumber "123456".
This seems to be an area of mocking frameworks that is very counter-intuitive and hard to use correctly. I generally shy away from doing argument matching and try to return or capture some sort of object that I can later make assertions against.
In your case, you are essentially comparing two expressions for equality. The 'look' different in the code even though they have the same syntax. I wonder, can you create those two expressions outside of the test context and see if they compare equal then?
I truly love NUnit's new(er) ability to test for expected exception testing, ie:
var ex = Assert.Throws<SomeException>(()=>methodToThrowException("blah"));
One minor issue I find is that to test some sort of operator overload or other assignment type functionality, the only way I can know how to do this is by giving the compiler a variable to assign to, like so:
// test division operator "/"
var ex = Assert.Throws<PreconditionException>(() => { var ignored = nbr / m; });
This is compact and works great, but has the annoyance where Resharper puts out a warning that the variable ignored is never used. This is counter productive if you like to use Resharper visuals to help you judge the quality of the code at a glance, as I do. Resharper is technically correct of course, but is there a way to tell Resharper this is my intention? I have a test with a lot of these sorts of tests, so a pragma will look nasty.
Any suggestions (besides "get over it, dude")?
Cheers
You could write your own Throws method which takes a Func<object> instead, and then just write:
var ex = Assert.Throws<PreconditionException>(() => nbr / m);
Then submit the new method to NUnit and wait for the next release :)
Add a field to the unit test and suppress the warning, ie:
// ReSharper disable UnaccessedField.Local
private object _ignore;
// ReSharper restore UnaccessedField.Local
The use that field as the assignment variable in your test delegate:
// test division operator "/"
var ex = Assert.Throws<PreconditionException>(() => { _ignore = nbr / m; });
This keeps resharper quiet, so you know if it does complain about something now it is likely a legitimate complaint that should be looked at. This eliminates the noise level so you can focus (I have over 50 tests like this in an important class that needs some refactoring).
Cheers,
Berryl
And it's really neat you can get the exception and work with it ...
var exception = Assert.Throws<ArgumentException>(() => dlinvalid.ProcessData());
Assert.That(exception.Message, Is.EqualTo("foo bar"), "Expected bar foo");
Plus it works with Resharper, whereas ExpectedException seems to be failing with NUnit 2.5
How do I verify that method was NOT called in Moq?
Does it have something like AssertWasNotCalled?
UPDATE: Starting from Version 3.0, a new syntax can be used:
mock.Verify(foo => foo.Execute("ping"), Times.Never());
Run a verify after the test with the Times.Never() option.
_mock.Object.DoSomething()
_mock.Verify(service => service.ShouldntBeCalled(), Times.Never());
UPDATE: Since version 3, check the update to the question above or Dann's answer below.
Either, make your mock strict so it will fail if you call a method for which you don't have an expect
new Mock<IMoq>(MockBehavior.Strict)
Or, if you want your mock to be loose, use the .Throws( Exception )
var m = new Mock<IMoq>(MockBehavior.Loose);
m.Expect(a => a.moo()).Throws(new Exception("Shouldn't be called."));
Stolen from: John Foster's answer to the question, "Need help to understand Moq better"
One of the things that you might want to test is that the pay method
does not get called when a person aged over 65 is passed into the
method
[Test]
public void Someone_over_65_does_not_pay_a_pension_contribution() {
var mockPensionService = new Mock<IPensionService>();
var person = new Person("test", 66);
var calc = new PensionCalculator(mockPensionService.Object);
calc.PayPensionContribution(person);
mockPensionService.Verify(ps => ps.Pay(It.IsAny<decimal>()), Times.Never);
}
This does not work in recent versions of Moq (since at least 3.1), it should be specified in the Verify method as mentioned in the
answer.
Actually, it's better to specify .AtMost(0) after the Returns statement.
var m = new Mock<ISomething>();
m.Expect(x => x.Forbidden()).Returns("foo").AtMost(0);
Although the "throws" also works, AtMost(0) is more expressive IMHO.
Using VerifyNoOtherCalls (requires Moq 4.8 or later)
This answer is an indirect approach. Instead of checking that a particular method wasn't called, you check that no unexpected calls were made in general.
Consider that a thorough test of a mock does 2 things:
Verify that all expected calls were made
Verify that no unexpected calls were made
If you're already doing step 1, adding step 2 is trivial:
// Step 1 (if relevant - see note below)
mock.Verify(..., Times.Exactly(2));
mock.Verify(..., Times.Once());
// ...
// Step 2
mock.VerifyNoOtherCalls();
Notes
If you omit step 1, step 2 will simply ensure no calls were made to the mock at all.
This does not require a strict mock.
Source: Moq Quickstart
I realise this is a very old question, but it just appeared in my sidebar, and I'd like to add my solution.
Many unit tests appear to mock several functions, as part of the setup, but then aren't used during the test.
Surely it's better to enable strict mocking (which means anything not explicitly setup will throw an exception), and then don't set up any functions you don't expect to be called. Or to put it another way, only set up the functions that one test expects to be called, and anything else will thrown an exception.
var thingBeingTested = new Mock<IThink>(MockBehaviour.Strict);
thingBeingTested.ThisWillThrowAnExceptionBecauseItHasNotBeenMocked();
Suppose you have this method and you want to test that it's not being called
//Setup
var databaseSessionMock = new Mock<IDatabaseSession>();
databaseSessionMock.Setup(m => m.Commit()).Returns(true).Verifiable();
RepositoryFactory.Configure<IDatabaseSession>(databaseSessionMock.Object);
you can test like this
databaseSessionMock.Verify(m => m.Commit(It.IsAny()), Times.Never(), "Database Session mock object was not used");
Use .AtMostOnce();
After the real test, call the method again. If it throws an exception, it was called.