Mock a repository while testing an api controller - unit-testing

Im trying to get familiar with using MOQ and mocking in general. So I want to test an api controller which uses an assembly which serves as a repository for getting/updating data etc.
eg a structure like this.
HomeController
Index
Repository.GetSomeData (returns JSON object)
This repository class has an interface, and that is what is injected via the .net core startup class. The method in this case, GetSomeData does a number of steps via calls to the Db, as well as reading a file from the file system, parsing it and moving it off to another folder.
Question: How can a "mocked" Repository work without doing the things that the "real" object does? All the examples I see are simple addition, returning strings etc.

When you mock something like your repository, you going to stub out methods on the repository to return some canned result. Calls to those methods on the repository mock, then, bypass the real methods and instead just do what you've stubbed.
Essentially, you need to first identity what methods will be utilized. Then, you should determined appropriate responses those methods should return based on the particular scenario you're attempting to unit test. Then, you create the mock and add stubs for those methods with those responses.
The whole point of mocking is to remove variables, so you're intentionally trying to get to the "happy path": the set of internal responses that put the action in the state you need it to be in for specific test you're conducting.

Related

CanJS: Unit testing of different parts

I have one question. I've started to use CanJS just recently and trying to create unit tests (funcunit / jasmine ) that will work in maven build with TeamCity (headless).
It was relatively easy to test Model, because it doesn't rely on any view and you can create instance and test functionality.
But it not so clear for me how to test Components and other parts of CanJS. Just to clarify i don't need E2E tests with user interaction, what i'm trying to achieve is just have some data provided by Can.fixtures and then just test that my functions works fine by calling them in tests.
Controller tests benefit from the addition of jasmine-fixture to your Jasmine test bed. You can affix() the appropriate DOM elements and instantiate the controller in beforeEach() before adding spies to the instance or the controller prototype, then fire events or directly call functions requiring some DOM tree to be available.
For Components, there's one more step involved. Because of the way Components are instantiated, either you have to use can.view() to create and attach their custom elements to the DOM (and clean it up in afterEach()), or you have to use can.view.callbacks.tagHandler(el, tag_name) to manually instantiate the Component for an element already in the DOM.
To be clear, this makes things easier when your controller/component functions are slurping data from the DOM, as in event handlers. It also works to just call the functions directly on the prototype and make spy objects for this.scope and this.options

mocking database objects with Rhino mock

I am sorry if this question is already been asked. I am very new to Unit Testing and I am suppose to use Rhino for mocking.
So the problem is...I have a method to test and that method is suppose to do retrive some data based on input parameter and return as datatable.
It also do some calculation for finding out which stored procedure should be called and with which set of parameters.
I issue is that, When I call the method with mock objects....it throws an error at date from database retrival line of code as object is not set to an instanse. That is expected as their is no data retruning from database since we are mocking it.
so what could be done it that case.
Seems like it is a good time to introduce Repository Pattern.
If you introduce than, the logic to generate query to DB and the logic to read data from DB will be encapsulated in the Repository.
In this case you can mock/stub the Repository in your tests and you can unit test all the classes, which use Repository, without creation test DB at all.
The Repository mock will verify whether incoming parameters are correct.
And the Repository stub will return any test-specific data which you need for each particular test.

Testing Mongoose Node.JS app

I'm trying to write unit tests for parts of my Node app. I'm using Mongoose for my ORM.
I've searched a bunch for how to do testing with Mongoose and Node but not come with anything. The solutions/frameworks all seem to be full-stack or make no mention of mocking stuff.
Is there a way I can mock my Mongoose DB so I can return static data in my tests? I'd rather not have to set up a test DB and fill it with data for every unit test.
Has anyone else encountered this?
I too went looking for answers, and ended up here. This is what I did:
I started off using mockery to mock out the module that my models were in. An then creating my own mock module with each model hanging off it as a property. These properties wrapped the real models (so that child properties exist for the code under test). And then I override the methods I want to manipulate for the test like save. This had the advantage of mockery being able to undo the mocking.
but...
I don't really care enough about undoing the mocking to write wrapper properties for every model. So now I just require my module and override the functions I want to manipulate. I will probably run tests in separate processes if it becomes an issue.
In the arrange part of my tests:
// mock out database saves
var db = require("../../schema");
db.Model1.prototype.save = function(callback) {
console.log("in the mock");
callback();
};
db.Model2.prototype.save = function(callback) {
console.log("in the mock");
callback("mock staged an error for testing purposes");
};
I solved this by structuring my code a little. I'm keeping all my mongoose-related stuff in separate classes with APIs like "save", "find", "delete" and no other class does direct access to the database. Then I simply mock those in tests that rely on data.
I did something similar with the actual objects that are returned. For every model I have in mongoose, I have a corresponding class that wraps it and provides access-methods to fields. Those are also easily mocked.
Also worth mentioning:
mockgoose - In-memory DB that mocks Mongoose, for testing purposes.
monckoose - Similar, but takes a different approach (Implements a fake driver). Monckoose seems to be unpublished as of March 2015.

mocking the return value of domainInstance.validate()

I am writing a spock unit test that tests a controller method.
The controller action under test instantiates a new domain instance object and
calls validate on it before it saves.
Is there anyway of mocking the call to domainInstance.validate() so I
can make it return whatever I want? Or do I have to hide this
instanciation and saving behind a service method to achieve this?
I do this this way, because within the context of a unit test for a
controller, the constraints of a domain object should not be involved.
I test those elsewhere (in the MyDomainClassTests, obviously). If I
wanted to take those into into account my test would be an integration
test.
If you didn't place the validate on the domain instance itself, but rather in a service,
you could let your controller take a Service in its constructor (or rather an interface of a service). Let that service handle the validation.
Now for your unittest of that controller, you would pass in a Mock of that interface(service) to the controller and configure the mock to return whatever you want.
For .net i can recommend Moq (http://code.google.com/p/moq/)
After a while I have come to the conclusion that what I wanted is rather tricky. If you're in a scenario where you don't have to use mockDomain(), you could add a groovy metaclass method and it's implementation (return true or false, whichever you want)
If you do need mockDomain() because you need to mock pre-existing instances you are out of options, at least for now because mockDomain() and fiddling with metaclass methods that mockDomain actually provides will not mix.

Need an advice for unit testing using mock object

I just recently read about "Mocking objects" for unit testing and currently I'm having a difficulties implementing this approach in my application. Please let me explain my problem.
I have a User model class, which is dependent on 2 data sources (database and facebook web service). The controller class simply use this User model as an interface to access data and it doesn't care about where the data came from.
Currently I never done any unit test to this User model because it is dependent on an external web service. But just a while ago, I read about object mocking and now I know that it is a common approach to unit test a class that depends on external resources (like in my case).
Now I want to create a unit test for the User model, but then I encountered a design issue:
In order for the User model to use a mocked Facebook SDK, I have to inject this mocked Facebook SDK to the User object (probably using a setter). Therefore I can't construct the Facebook SDK inside the User object. I have to construct it outside the User object, and inject the SDK into the User object.
The real client of my User model is the application's controller. Therefore I have to construct the Facebook SDK inside the controller and inject it to the user object. Well, this is a problem because I want my controller to be as clean as possible. I want my controller to be ignorant about the application's data source.
I'm not good at explaining something systematically, so you'll probably sleeping before reading this last paragraph. But anyway, I want to ask if anyone here ever encountered the same problem as mine? How do you solve this problem?
Regards,
Andree
P.S: I'm using Zend framework, PHP 5.3.
One way to solve this problem is to create two constructors in User: the default one instantiates the real-life data sources, the other one gets them as parameters. This way your controller can use the default constructor, while your tests use the parameterized one to pass in mock data sources.
Since you haven't specified your language, I show you an example in Java, hopefully this helps get the idea:
class User {
private DataBase database;
private WebService webService;
// default constructor
public User() {
database = new OracleDataBase();
webService = new FacebookWebService();
}
// constructor for unit testing
public User(DataBase database, WebService webService) {
this.database = database;
this.webService = webService;
}
}
This isn't really a question about mocking, but about dependencies--and trying to unit test has forced the issue. It sounds like currently you create your User object within your Controller.
If the User and Controller have the same lifetime (they're created at the same time), then you can pass the User into the Controller's constructor, which is where you can make the substitution.
If there is a User object per call, then perhaps the User object should be passed in by the environment, or returned from some Context object.
If you make the Facebook SDK Object(s) publicly accessible, your User object can still create it when it sets up but you can replace it with a mock before you actually do anything on the User object.
[Test]
public void Test()
{
User u = new User(); // let's say that the object on User gets created in the ctor
u.FacebookObj = new DynamicMock(typeof(FacebookSDK)).MockInstance;
Assert.That(u.Method(), Does.Stuff, "u.Method didn't do stuff");
}
You don't say what language you are using, but I use Ruby and Mocha for mocking objects, and it's quite easy.
See http://mocha.rubyforge.org/.
here the fourth example shows that any call to Product.name from the unit under test is intercepted and the value 'stubbed_name' is returned.
I guess there are similar mechanisms in Java, etc.
Since you will be Unit Testing your test class will play the role of the Controller, so that one should not be touched. So that can remain clean.
You are well underway of reinventing Dependency Injection. So it may be worthwhile to look at Spring or Guice to help you with the plumbing. (If you are in Java land).
Your test can indeed do the injection of the Mocked Facebook SDK and your Database service using setter or constructor arguments.
your tests will now do what the controllers (and maybe views) will do and verify the proper routines are called in the SDK's and that the resources are properly obtained and disposed of.