MOQ Testing return types - moq

Given the following:
var mockIActionService = new Mock<IActionService>();
var mockValidAgeRule = new Mock<ValidAgeRule>(mockIActionService.Object);
mockValidAgeRule.Setup(t => t.Execute(app));
Now t.Execute returns a "Rules" object, how can I verify that something has been called on Rules?
I am attempting to call it as such mockValidAgeRule.Verify(x => x.Execute(app).Passed)
I want to test that the object Result returned true given the inputs.
Sorry for all questions just am having a little trouble finding info about MOQ that is up to date and helpful

Well, as stated by Chris, you haven't provided enough detail to get a proper answer. Nonetheless, IMHO it's pretty clear that this test has a code smell. It don't appear to have any concrete implementations. A test completely composed of mock objects is not likely testing anything useful.
Which class represents your SUT? It sounds like it might be your Rules object. If you provide further detail about your object model and expected behaviors, it would be easier to provide a feedback.

I suggest to add RulesMock object something like this:
var rulesMock = new Mock<Rules>();
rulesMock.SetUp(x => x.MethodInRules).Return(some_object);
then add this mock to your code:
var mockIActionService = new Mock<IActionService>();
var mockValidAgeRule = new Mock<ValidAgeRule>(mockIActionService.Object);
mockValidAgeRule.Setup(t => t.Execute(app)).Returns(rulesMock.Object);
so, if your Rules getter call MethodInRules() you can check this is called by:
rulesMock.Verify(x => x.MethodInRules, Times.Once);
It is an idea, hope this helps someone, good luck!

Related

C# 7.0 Value Tuple compile error?

When I am trying to compile the following code:
var post = iPostService.GetAll().Select(x => (x.Title, x.Author));
I get the compiler error: 'An expression tree may not contain a tuple literal.'
So I also tried this:
var post = iPostService.GetAll().
Select(x => new ValueTuple<string, string>(x.Title, x.Author))
The result is runtime error:'Cannot resolve method Void .ctor(System.String, System.String) because the declaring type of the method handle System.ValueTuple`2[T1,T2] is generic. Explicitly provide the declaring type to GetMethodFromHandle.'
I googled to find out the solution to this problem but nothing really helpful.
Any help really appreciated.
Thanks
It works for me, create a tuple first and convert it to a ValueTuple:
var post = iPostService.GetAll().
Select(x => new Tuple<string, string>(x.Title, x.Author).ToValueTuple())
Finally, I found out what wrong with my code:
I am using deferred execution so data won't load from the database when the constructor executed.
The solution is to add conversion operators before creating instance command.
Hope it works with your code.

getViewData vs. getNormData and DataTransformers - different results depending on context

I have a form with several fields.
Then I bound DataTransformer to the one of them. Transformer works correctly if I get data getViewData and getNormData.
But if I issue these methods on whole form, data processed by transformers are completely ignored.
In Form data is being overwritten due to the:
$childrenIterator = new InheritDataAwareIterator($this->children);
$childrenIterator = new \RecursiveIteratorIterator($childrenIterator);
$this->config->getDataMapper()->mapFormsToData($childrenIterator, $viewData);
My mapper is PropertyPathMapper. Unfortunately, it bases on getData method of each child.
Is it possible to bypass viewData overwrite / achieve correctly transformed data without writing a global transformer?
a workaround:
$data = array();
foreach ($form->all() as $k => $el) {
$data[$k] = $el->getData(); // or getNormData or getViewData
}
Unfortunately I have no solution.
The current behaviour is not what I expected. It should at least be mentioned in the symfony cookbook.
As you see I have the same problem. I wrote a test case to be sure that I do not misunderstand how the transformers work. I found your question later.
my test case:
https://github.com/SimonHeimberg/SymfonyFormForm_DataTransformer_Demo

When to specify certain Setups in Moq

I'm trying to follow this Get Started example for testing with Moq. I'm able to duplicate the examples within my own testing project and can get my tests to pass (testing my service where my context is injected). However, what I don't understand is WHEN to use each of the following Setup calls:
var mockSet = new Mock<DbSet<Blog>>();
mockSet.As<IQueryable<Blog>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<Blog>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<Blog>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<Blog>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
Can someone explain in very basic terms as to when each of these should be used?
For example, It seems that if the method in my service that I'm testing uses an expression, I need to do the 2nd setup call above (I've done some trial and error by removing and re-inserting these calls). I've been to the Moq documentation as well as MSDN for Table-TEntity and I still don't see it. Perhaps because I don't have a strong grasp of the Linq namespace.
TL;DR - When using an Entity Framework DBContext dependency, you will need perform these Setups on any DBSet which you intend to mock, specifically to return fake data to any LINQ queries on the DBSet. All 4 setups should be done for each mocked DbSet - this can be done generically in a helper method.
In more Detail:
In general, with Strict mode off, Setup is only required on methods that you actually want to Mock. In this case, if you haven't done a Setup on a method which is invoked during your Unit Test, Moq will instead provide default behaviour for any method which hasn't been explicitly Setup, which typically is to return the default(T) of any expected return type, T. For classes, the default is null, which isn't really going to help any during testing of classes dependent on a Mocked EF DbContext.
The specific example you have provided is the standard mocked setup for an Entity Framework DbSet, which then allows you to provide fake data for this specific DbSet (DbSet<Blog>), by providing an alternative IQueryable<Blog> from a List<Blog> collection (as opposed to the usual concrete RDBMS implementation).
A suggestion would be to move the DbSetmock code into your standard unit test plumbing setup framework / toolkit, to create a helper method like:
public static Mock<IDbSet<T>> GetMockedDbSet<T>(IList<T> fakeData) where T : class, new()
{
var data = fakeData.AsQueryable();
var mockSet = new Mock<IDbSet<T>>();
mockSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(data.Provider);
mockSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(data.Expression);
mockSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(data.ElementType);
mockSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
return mockSet;
}
Which you can then set up on your Mock DBContext, as follows:
var mockContext = new Mock<IMyDbContext>();
var mockBlogDbSet = GetMockedDbSet<Blog>(new List<Blog>{... fake data here ...});
mockContext.Setup(c => c.Blogs).Returns(mockBlogDbSet.Object);
var sut = new SomeClassIWantToTest(mockContext.Object); // Inject dependency into Ctor
sut.DoSomething();...

Is it possible to use Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert on an IEnumerable<T>?

I have a testing scenario where I want to check if two collections are equal. I have found the class Microsoft.VisualStudio.QualityTools.UnitTesting.CollectionAssert, but it only works on ICollection<T>. Since I'm testing a repository for Entity Framework, and thus need to compare IObjectSet<T>s, that won't do - IObjectSet<T> doesn't implement ICollection<T>.
Is there any way I can use this class to compare the collecitons, or do I have to create my own implementation? (And why the heck didn't the Microsoft team make the class work with IEnumerable<T> instead, as that is the "base interface" for collections?)
EDIT: This is my test code:
// Arrange
var fakeContext = new FakeObjectContext();
var dummies = fakeContext.Dummies;
var repo = new EFRepository<DummyEntity>(fakeContext);
// Act
var result = repo.GetAll();
// Assert
Assert.IsNotNull(result, NullErrorMessage(MethodName("GetAll")));
Assert.IsInstanceOfType(result, typeof(IEnumerable<DummyEntity>), IncorrectTypeMessage(MethodName("GetAll"), typeof(IEnumerable<DummyEntity>)));
CollectionAssert.AreEqual(dummies.ToList(), result.ToList());
The CollectionAssert.AreEqual call on the last line fails, stating that the elements at index 0 are not equal. What am I doing wrong?
A cheeky option (not quite as much info though) is to assert that expected.SequenceEqual(actual) returns true.
You could write a wrapper method that forces a collection (.ToList() on each)? But to be honest you might as well just call .ToList() in the unit test code:
CollectionAssert.AreEqual(expected.ToList(), actual.ToList()); // but tidier...
If you're comparing result sets you might want to use CollectionAssert.AreEquivalent which will ignore the order. You should also make sure you have implemented Equals on the type of elements you are comparing.

Testing an object's state at save

I'm looking to write unit tests for a method such as this one:
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
ISPMembershipUserDao userDao = GetISPMembershipUserDao();
if (ValidateUser(username, password))
{
SPMembershipUser user = userDao.GetUserByUserName(username);
user.PasswordQuestion = newPasswordQuestion;
user.PasswordAnswer = newPasswordAnswer;
userDao.Save(user);
return true;
}
return false;
}
It's a fairly straight-forward method to test. I'm using the Rhino Mocks framework. But one aspect has me questioning myself. I stub the DAO object and its save method, and I'm wondering how deeply I should test that user object that is passed to the save method. Should I assert that every property of that object is as I expect it to be? Or should I only assert that the PasswordQuestion and PasswordAnswer properites have the correct values? The former seems right to me, as I should make sure that only those two properties have been modified, and the others haven't been touched.
I was hoping some people could give their opinions on this. Is there a rule of thumb or pattern to keep in mind for these types of situations?
Warning: personal opinion ahead
Ok, now that that's out of the way.... for me, it comes down to what I need to do to feel that my code properly implements the needed logic. In this case? I'd have two test cases:
Dealing with ValidateUser returning false
Should return false
Save should not have been called
Dealing with ValidateUser returning true
Should return true
Save should have been called
Object passed to save has the modified question and answer
No checks of other properties on user object
However, if/when I got a bug filed that affected this part of the code, I'd add whatever (initially failing) tests were needed to cover the bug, fix the bug, and leave the tests.
Since it's so easy to set up a constraint here, why not test it to ensure there are no side-effects to your method?
stubbedUserDao.AssertWasCalled(x => x.Save(null), o => {
o.IgnoreArguments();
o.Constraints(Property.AllPropertiesMatch(expectedMatchingUser));
});

Resources