mocking the return value of domainInstance.validate() - unit-testing

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.

Related

Mock a repository while testing an api controller

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.

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

Does it make sense to test controllers

I have a simple MVC application consisting of View->Controller->Service->Model.
My controllers are really skinny. All they do is call service method and populate the ModelAndView.
Is it considered a good practice to unit tests controllers to make sure they set required properties in the ModelAndView while mocking the services completely?
At some point it would not harm to test even controllers - then you would be sure that they are calling correct service methods, passing (modifying - if any needed) request parameters properly and returning correct ModelAndView.

Unit Testing basic Controllers

I have a number of simple controller classes that use Doctrine's entity manager to retrieve data and pass it to a view.
public function indexAction() {
$pages = $this->em->getRepository('Model_Page')->findAll();
$this->view->pages = $pages;
}
What exactly should we be testing here?
I could test routing on the action to ensure that's configured properly
I could potentially test that the appropriate view variables are being set, but this is cumbersome
The findAll() method should probably be in a repository layer which can be tested using mock data, but then this constitutes a different type of test and brings us back to the question of
What should we be testing as part of controller tests?
Controller holds core logic for your application. Though simple "index" controller actions don't have any specific functions, those that verify/actively use data and generate viewmodels have pretty much the most functionality of the system.
For example, consider login form. Whenever the login data is posted, controller should validate login/password and return: 1) to index page whenever logins are good. Show welcome,{user} text. 2) to the login page saying that login is not found in db. 3) to the login page saying that password is not found in db.
These three types of outputs make perfect test cases. You should validate that correct viewmodels/views are being sent back to the client with the appropriate actions.
You shouldn't look at a controller like at something mysterious. It's just another code piece, and it's tested as any other code - any complicated logic that gives business-value to the user should be tested.
Also, I'd recommend using acceptance testing with framework like Cucumber to generate meaningful test cases.
Probably the controller is the hardest thing to test, as it has many dependencies. In theory you should test it in full isolation, but as you already seen - it has no sense.
Probably you should start with functional or acceptance test. It tests your controller action in a whole. I agree with previous answer, that you should try acceptance testing tools. But Cucumber is for Ruby, for PHP you can try using Codeception. It makes tests simple and meaningful.
Also on a Codeception page there is an article on how to test sample controllers.

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.