Does it make sense to test controllers - unit-testing

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.

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

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.

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.

Mocking a datacontext for an object that has a dependency

I'm writing some unit tests in my project and I have a datacontext dependency on the controller containing the methods I'd like to test.
I'm using Ninject to inject the dependency and Moq to create my mock datacontext. My DI makes use of an interface IDataContext which my dbml impliments and is used through out the injection process.
In my unit test I'm creating my mock datacontext as follows:
var mock = new Mock<IDataContext>();
var myController = new MyController(mock.Object);
This throws a Object reference not set to an instance of an object. exception on the second line whilst executing the datacontexts constructor.
I'm clearly missing a fundamental piece in setting this up however most of the Moq examples I've seen involve some kind of test against the mocked object using Setup().
Am I going about this the right way? Should I be creating a mock of my IDataContext interface or something else?
haha,
the answer came while i was reading through emad's blog on unit testing in ASP.Net MVC.
I'm guessing that you didn't add the connection string to the app.config of your test project right? :)
And that's the database dependency way because you're still not mocking the database end.
So if you want to do that, you need to google up for some codes, there are a few ways to do that.
i find these few references below to be quite useful, but since i don't really have a need to mock the database end, i'm just using my test DB server for now.
link