Unit testing Dapper Update - unit-testing

Database.Setup(x => x.Update(It.IsAny<Subscription>()))
.Callback<object>(sub => SavedSubscription = sub as Subscription);
This line works with PetaPoco. Because of project requirements, had to switch to Dapper (and also had to add DapperExtensions in order to have CRUD methods) so now I am getting this error:
An expression tree may not contain a call or invocation that uses
optional arguments
Any ideas how to handle this?

You can't use Moq to mock methods that have optional parameters (as Update does). See this question for more details, though you're stuck specifying all parameters to the Update method.
Note that this is a limitation inherent to the framework and not Moq; you can't pass a method with a default parameter to an Expression. Jon Skeet gives a good demonstration why here.

Related

Unit Testing RxJava Flowable using spock

I have below snippet for fetching data from MongoDB using com.mongodb.reactivestreams.client.MongoClient and Flowable
The snippet goes like:
Flowable
.fromPublisher(
mongoClient
.getDatabase(mydb)
.getCollection(mycollection)
.find()
.limit()
)
.firstOrError()
.toMaybe()
.doOnError(error -> { /* somecode */ })
I tried mocking every step of this fluent expression, e.g.
MongoDatabase someDb = Mock(MongoDatabase)
mongoClient.getDatabase(mydb) >> somedb
but on doing this somehow the test keeps running.
What is the correct way to unit test this using Spock?
Fluent interfaces are a PITA to mock, my strategy is to put those calls into a separate class / method and mock that. And then to test the fluent part in an integration test.
In addition to Leonard's idea, you might also want to look into implementing a special ThisResponse implements IDefaultResponse which always returns the mock instance for every mock method call and using that like Mock(defaultResponse: ThisResponse.INSTANCE) for your fluent API class(es). This works nicely as long as the fluent API methods used in the test are supposed to return this or at least another object of the given type. Only where another type is returned, you need to stub something.
Check this answer for more details. As soon as you update your question with a little MCVE, you may also ask follow-up questions if you have any problems using that solution.
Update 2022-03-08: I re-wrote the linked answer after learning about the special behaviour of EmptyOrDummyResponse for methods returning the mocked type. I am also describing now the related Spock 2 syntactic sugar syntax there.

Simple definition of stub, spy, fake and mock in unit testing

I'm quite new to unit testing. I've read around on here as well as done some Googling, but am still a bit confused as to the meaning of each of the four meanings. I came across the following definition which help....
Stub - stubs are minimal implementations of interfaces or base classes
Spy - a spy will record which members were invoked
Fake - more complex, a fake may resemble a production implementation
Mock - A mock is usually dynamically created by a mock library and depending on its configuration, a mock can behave like a dummy, a stub, or a spy
However, I'd like to simplify the meaning (if possible) and ask a few questions.
Do all of the above only relate to functions, or can they be objects or any other type?
Stub - Is Stubbing bascially a way to provide dummy info instead of making the calling to the actual database? So for example, if I had an API call, instead of actually making a call to the API, I just instead make a GET request to a JSON file which is in my tests folder which has some dummy data in, and use that instead of making the API call?
Spy - so is this a way of tracking what happens to a function for example. Meaning you follow when it's called, where it gets passed around to?
Fake - Is this for example a function which you create inside the test file to mimic the real function or be a simpified version of the actual function?
Thanks in advance.
There are multiple attempts at definitions. To my knowledge there is no fully consistent definition, probably due to the fact that mocking frameworks defines things slightly differently. Martin Fowler lists the following (https://martinfowler.com/bliki/TestDouble.html):
Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an InMemoryTestDatabase is a good example).
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test.
Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent.
Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive. They can throw an exception if they receive a call they don't expect and are checked during verification to ensure they got all the calls they were expecting.
Fowler has them from this page: http://xunitpatterns.com/Test%20Double.html where you can read about them in a bit more detail.
No, they apply to more then just functions
Yes
Kind of, in most cases you will spy on an object
Yes
The implementation and nomenclatur will depend of what framework you use.

Mocking & Unit Testing- Why check that something was called only once?

I know that many mocking libraries let the programmer check that a method was called only once. But why is that useful?
Also, why is it useful to verify the parameters to a mock's method?
When doing unit tests you are testing a isolated method: all other methods are supposed to work correctly, and you test only that your method behaves in the expected (specified...) way.
But in many occasions the expected way implies calling methods of classes you depend on (via dependency injection, if you want to do unit testing).
For these reason you need to assure that this calls are really done... and of course they are called with the expected parameters.
Example:
In your real application you have a repository class that stores all your changes in the database (and does only this!). But for unit test your "business" class (where all your business rules are defined), you should mock that "repository" class: then you must check that this mocked class receives the correct updated data.
In general, the answers to both of those questions are the same.
It's useful if the requirements of the unit/method you're testing specify that that behavior is required. If that behavior is required, then that's what you need to verify is actually happening.
If it's important to ensure that a particular method is only called once, then you can do that. If it doesn't matter that a method is called more than once, then don't test for it explicitly. Note that the default for the Mockito "verify" method is "times(1)", which means that it confirms that the method was called once and only once.
Concerning the second question, you might want to verify the parameters if it's entirely possible the method could be called with different parameters, and you don't want to count those occurrences, you only care about a specific set of parameter values.

What are strict and non-strict mocks?

I have started using moq for mocking. Can someone explain me the concept of strict and non-strict mocks? How can they can be used in moq?
edit:
in which scenario do we use which type of mock?
I'm not sure about moq specifically, but here's how strict mocks work in Rhino. I declare that I expect a call to foo.Bar on my object foo:
foo.Expect(f => f.Bar()).Returns(5);
If the calling code does
foo.Bar();
then I'm fine because the expectations are exactly met.
However, if the calling code is:
foo.Quux(12);
foo.Bar();
then my expectation failed because I did not explicitly expect a call to foo.Quux.
To summarize, a strict mock will fail immediately if anything differs from the expectations. On the other hand, a non-strict mock (or a stub) will gladly "ignore" the call to foo.Quux and it should return a default(T) for the return type T of foo.Quux.
The creator of Rhino recommends that you avoid strict mocks (and prefer stubs) because you generally don't want your test to fail when receiving an unexpected call as above. It makes refactoring your code much more difficult when you have to fix dozens of test that relied on the exact original behavior.
Ever come across Given / When / Then?
Given a context
When I perform some events
Then an outcome should occur
This pattern appears in BDD's scenarios, and is also relevant for unit tests.
If you're setting up context, you're going to use the information which that context provides. For instance, if you're looking up something by Id, that's context. If it doesn't exist, the test won't run. In this case, you want to use a NiceMock or a Stub or whatever - Moq's default way of running.
If you want to verify an outcome, you can use Moq's verify. In this case, you want to record the relevant interactions. Fortunately, this is also Moq's default way of running. It won't complain if something happens that you weren't interested in for that test.
StrictMock is there for when you want no unexpected interactions to occur. It's how old-style mocking frameworks used to run. If you're doing BDD-style examples, you probably won't want this. It has a tendency to make tests a bit brittle and harder to read than if you separate the aspects of behaviour you're interested in. You have to set up expectations for both the context and the outcome, for all outcomes which will occur, regardless of whether they're of interest or not.
For instance, if you're testing a controller and mocking out both your validator and your repository, and you want to verify that you've saved your object, with a strict mock you also have to verify that you've validated the object first. I prefer to see those two aspects of behaviour in separate examples, because it makes it easier for me to understand the value and behaviour of the controller.
In the last four years I haven't found a single example which required the use of a strict mock - either it was an outcome I wanted to verify (even if I verify the number of times it's called) or a context for which I can tell if I respond correctly to the information provided. So in answer to your question:
non-strict mock: usually
strict mock: preferably never
NB: I am strongly biased towards BDD, so hard-core TDDers may disagree with me, and it will be right for the way that they are working.
Here's a good article.
I usually end up having something like this
public class TestThis {
private final Collaborator1 collaborator1;
private final Collaborator2 collaborator2;
private final Collaborator2 collaborator3;
TestThis(Collaborator1 collaborator1, Collaborator2 collaborator2, Collaborator3 collaborator3) {
this.collaborator1 = collaborator1;
this.collaborator2 = collaborator2;
this.collaborator3 = collaborator3;
}
public Login login(String username) {
User user = collaborator1.getUser(username);
collaborator2.notify(user);
return collaborator3.login(user);
}
}
...and I use Strict mocks for the 3 collaborators to test login(username). I don't see how Strict Mocks should never be used.
I have a simple convention:
Use strict mocks when the system under test (SUT) is delegating the call to the underlying mocked layer without really modifying or applying any business logic to the arguments passed to itself.
Use loose mocks when the SUT applies business logic to the arguments passed to itself and passes on some derived/modified values to the mocked layer.
For eg:
Lets say we have database provider StudentDAL which has two methods:
Data access interface looks something like below:
public Student GetStudentById(int id);
public IList<Student> GetStudents(int ageFilter, int classId);
The implementation which consumes this DAL looks like below:
public Student FindStudent(int id)
{
//StudentDAL dependency injected
return StudentDAL.GetStudentById(id);
//Use strict mock to test this
}
public IList<Student> GetStudentsForClass(StudentListRequest studentListRequest)
{
//StudentDAL dependency injected
//age filter is derived from the request and then passed on to the underlying layer
int ageFilter = DateTime.Now.Year - studentListRequest.DateOfBirthFilter.Year;
return StudentDAL.GetStudents(ageFilter , studentListRequest.ClassId)
//Use loose mock and use verify api of MOQ to make sure that the age filter is correctly passed on.
}

Rhino Mocks: "Verify" vs. "Assert"

When using Rhino Mocks, when is it appropriate to use "VerifyAll" and when should I do "Asserts"?
VerifyAll and Verify are used to check that some methods have been called (and possibly verify the parameters with which they were called). This is considered "interaction-based testing", and is used when you want to verify that the system-under-test calls a method on one of its dependencies.
Asserts normally means that you want to make sure the value returned has the correct value. Asserts are used for what is called "state-based testing", which is essentially verifying the state of the system-under-test after it has been acted upon.
verifyall, check out this.
Also, differentiate Mock and Stub .
I believe VerifyAll belongs to the older style of using RhinoMocks, where you would have a record step and a playback step, after which you would verify all Expectations. In this model you would during the record step set up an expectation (eg, Expect that this method will be called with parameters x, y, and z, etc).
The newer versions of RhinoMocks introduce Arrange-Act-Assert (AAA) syntax as the preferred pattern; Using this pattern, it makes more sense to use Assertions at the end of your test method. It is still possible to use VerifyAllExpectations(), but personally I think it reads easier if all of your Assertions happen in a block at the end of the test.
So I guess the answer (to me anyway) is that it is personal preference; See the link above where he has several examples of the same test and choose the one that reads best to you.