How to unit test library that relies on Session object - asp.net-mvc

I have several asp.net mvc websites consuming the same controller and model.
This common logic is put in seperate libraries.
These libraries use the HttpContext.Current.Session. How can I make these unit testable?
I read about the StateValue but can't completely grasp it. Where should I get this StateValue thing? Is it a lib I reference?

You can use mock helpers such as seen here

Your code should use IHttpSessionState not HttpSessionState.
If you look up the MSDN documentation for IHttpSessionState you will find an example implementation you can lift into your Unit Test project to create a mock session.
Replace code aquiring the Session with static delegate that return IHttpSessionState.
Initialise that static delegate with a function that uses HttpContext.Current.Session.
During Unit Testing replace delegate with your Mock implementation of IHttpSessionState.

just to channel people out of this sinkhole (which it is as of .NET 3.5) -- don't touch IHttpSessionState for purposes of mocking and testing:
http://www.codemerlin.com/2011/07/mocking-httpcontext-httpresponse-httprequest-httpsessionstate-etc-in-asp-net/

Related

OCMVerify/Expect in Swift?

I would like to Verify that an expected method is called with the correct parameters in Swift in unit-testing. This was very easily done in Objective-C using the OCMock framework. You could do a combination of partialMocking and running OCMExpect/Verify to assert code paths with the right parameters were being called. Any idea how to do something like this in Swift?
Swift doesn't support reflection, so traditional mocking libraries aren't feasible. Instead, you need to create your own mock. There are at least two approaches to do this.
Create a testing subclass of the class under test. This is partial mocking. Avoid this if possible.
Use an interface instead of a class. Create a testing implementation of the interface.
Hand-crafted mocks aren't hard. You want to
Count the number of calls to a method
Capture its arguments
Simulate its return value
It is a lot of boilerplate. There are libraries out there that can auto-generate this code.

Why is mocking with DI better than mocking objects in objective-c?

this blog article says that:
While there are sometimes sensible ways to mock out objects without DI
(typically by mocking out class methods, as seen in the OCMock example
above), it’s often flat out not possible. Even when it is possible,
the complexity of the test setup might outweigh the benefits. If
you’re using dependency injection consistently, you’ll find writing
tests using stubs and mocks will be much easier.
but it doesn't explain why. What are possible scenarios where DI (injecting an id object conforming to protocol) will serve better for mocking in Objective-C, than simple OCMockito:
[given([mockArray objectAtIndex:0]) willReturn:#"first"];
[verifyCount(mockArray, times(1)) objectAtIndex:];
?
I've noticed that it is easier to create a separate class for test target when the original class do some async stuff.
Let assume you write a test for UIViewController which has a LoginSystem dependency which uses AFNetworking to do a request to the API. LoginSystem takes a block argument as a callback. (UIViewController->LoginSystem->AFNetworking).
If you make a mock of LoginSystem probably you will end with problems how to fire a callback block to test your UIViewController behaviour on success/failure. When I tried that I ended with MKTArgumentCaptor to retrieve a block argument and then I had to invoke it inside a test file.
On the other hand, if you create a separate class for LoginSystem (let call it LoginSystemStub which extends from LoginSystem) you are able to "mock" a behaviour in 3 lines of code and outside the test file. We should also keep our test file clean and readable.
Another case is that verify() doesn't work with checking asynchronous behaviour. It is much more easier to call expect(smth2).will.equal(smth)
EDIT:
Pointers to NSError (NSError**) also don't work well with verify() and it's better to create a stub :D
Imagine you are trying to test a more complex behavior of an object interacting with one of its child objects. To make certain that the parent object is operating correctly, you have to mock all the methods of the child object and even potentially track its changing state.
But if you do that, you just wrote an entirely new object in a confusing and convoluted way. It would have been simpler to write an entirely new object and tell the parent to use that.
With DI you inject your model at runtime, it's not bound in your classes but only in the configuration.
When you want to mock you just create a mock model and inject that instead of your real data. Besides the model, you changed your implementation in a single line.
See here for a hands on example or here for the idea behind it.
Disclaimer: Of course you can mock other stuff than the model, but that's probably the most common use-case.
The answer is: It's not better. It's only better if you need some super custom behavior.
The best thing about it is that you don't have to create an interface/protocol for every class you inject and you can limit to DI the modules you really need to inject making your code cleaner and more YAGNI.
It applies to any dynamic language, or language with reflection. Creating so much clutter just for the sake of Unit-Tests struck me as a bad idea.

Is it a good practice to write helper functions in controller itself

I am new to Microsoft ASP.NET MVC framework. I am working on MVC project where I have a controller. It has various ActionResult methods. Also, it needs several helper functions. Can I write them in controller itself? Please guide me.
No, it's not best practice.As helper function needs to be define/implemented in static class. So it is better to to have standalone seprate helper class.
The answer is: it depends. First of all it is not clear what do you mean with helper functions.
if you are talking about ASP.NET MVC HTML Helpers, it is better to move them to separate class. Tutorial how to create and use them.
if you are talking about general helper functions that evaluate something, of course you may leave them in controller, move to the base controller or move to separate class or library (depeneds on context). You may check implementation of standard System.Web.Mvc.Controller, there are a lot of methods and properties in it.
I think there's no specific rule regarding this.
IF
you're going to reuse the helper function, abstract/separate it to another class.
ELSE
put it in the same class for better code cohesion and readability.

Laravel 4: Facade vs DI (when to use)

My understanding is that a facade is used as an alternative to dependency injection. Please correct if I'm mistaken. What is not clear is when one should use one or the other.
What are the advantages/disadvantages of each approach? How should I determine when to use one or the other?
Lastly, why not use both? I can create a facade that references an interface. It seems Sentry 2 is written this way. Is there a best practice?
FACADES
Facades are not an alternative to dependency injection.
Laravel Facade is an implementation of the Service Locator Pattern, creating a clean and beautiful way of accessing objects:
MyClass::doSomething();
This is the PHP syntax for a static methods, but Laravel changes the game and make them non-static behind the scenes, giving you a beautiful, enjoyable and testable way of writing your applications.
DEPENDENCY INJECTION
Dependency Injection is, basically, a way of passing parameters to your constructors and methods while automatically instatiating them.
class MyClass {
private $property;
public function __construct(MyOtherClass $property)
{
/// Here you can use the magic of Dependency Injection
$this->property = $property
/// $property already is an object of MyOtherClass
}
}
A better construction of it would be using Interfaces on your Dependency Injected constructors:
class MyClass {
private $property;
public function __construct(MyInterface $property)
{
/// Here you can use the magic of Dependency Injection
$this->property = $property
/// $property will receive an object of a concrete class that implements MyInterface
/// This class should be defined in Laravel elsewhere, but this is a way of also make
/// your application easy to maintain, because you can swap implementations of your interfaces
/// easily
}
}
But note that in Laravel you can inject classes and interfaces the same way. To inject interfaces you just have to tell it wich one will be this way:
App::bind('MyInterface', 'MyOtherClass');
This will tell Laravel that every time one of your methods needs an instance of MyInterface it should give it one of MyOtherClass.
What happens here is that this constuctor has a "dependency": MyOtherClass, which will be automatically injected by Laravel using the IoC container. So, when you create an instance of MyClass, Laravel automatically will create an instance of MyOtherClass and put it in the variable $class.
Dependency Injection is just an odd jargon developers created to do something as simple as "automatic generation of parameters".
WHEN TO USE ONE OR THE OTHER?
As you can see, they are completely different things, so you won't ever need to decide between them, but you will have to decide where go to with one or the other in different parts of your application.
Use Facades to ease the way you write your code. For example: it's a good practice to create packages for your application modules, so, to create Facades for those packages is also a way to make them seem like a Laravel public class and accessing them using the static syntax.
Use Dependency Injection every time your class needs to use data or processing from another class. It will make your code testable, because you will be able to "inject" a mock of those dependencies into your class and you will be also exercising the single responsibility principle (take a look at the SOLID principles).
Facades, as noted, are intended to simplify a potentially complicated interface.
Facades are still testable
Laravel's implementation goes a step further and allows you to define the base-class that the Facade "points" to.
This gives a developer the ability to "mock" a Facade - by switching the base-class out with a mock object.
In that sense, you can use them and still have testable code. This is where some confusion lies within the PHP community.
DI is often cited as making your code testable - they make mocking class dependencies easy. (Sidenote: Interfaces and DI have other important reasons for existing!)
Facades, on the other hand, are often cited as making testing harder because you can't "simply inject a mock object" into whatever code you're testing. However, as noted, you can in fact "mock" them.
Facade vs DI
This is where people get confused regarding whether Facades are an alternative to DI or not.
In a sense, they both add a dependency to your class - You can either use DI to add a dependency or you can use a Facade directly - FacadeName::method($param);. (Hopefully you are not instantiating any class directly within another :D ).
This does not make Facades an alternative to DI, but instead, within Laravel, does create a situation where you may decide to add class dependencies one of 2 ways - either using DI or by using a Facade. (You can, of course, use other ways. These "2 ways" are just the most-often used "testable way").
Laravel's Facades are an implementation of the Service Locator pattern, not the Facade pattern.
In my opinion you should avoid service locator within your domain, opting to only use it in your service and web transport layers.
http://martinfowler.com/articles/injection.html#UsingAServiceLocator
I think that in terms of laravel Facades help you keep you code simple and still testable since you can mock facades however might be a bit harder to tell a controllers dependencies if you use facades since they are probably all over the place in your code.
With dependency injection you need to write a bit more code since you need to deal with creating interfaces and services to handle the depenancies however Its a lot more clear later on what a controller depends on since these are clearly mentioned in the controller constructor.
I guess it's a matter of deciding which method you prefer using

MVC 3: How to Mock an instance of WebViewPage<T>?

I'm currently using the Rhino Mocks mocking framework. How do you mock an instance of WebViewPageBase AND its Model with Rhino Mocks or any other mocking framework? When I run the following unit test, an exception is thrown when attempting to access the WebViewPageBase.Model property.
var repo = new Rhino.Mocks.MockRepository();
System.Web.Mvc.WebViewPage<IEnumerable<Tuple<string>>> page = repo.DynamicMock<System.Web.Mvc.WebViewPage<IEnumerable<Tuple<string>>>>();
Assert.IsNotNull(page.Model);//exception thrown, not a fail on Assert
Would this be more easily accomplished with a different mocking framework?
Scott Hanselman has a great write-up on mocking MVC 3 classes with Rhino here:
http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx
Are you sure you want to get the view page this way as it won't have a model etc because it has not all been setup.
More typically you would test the controller and inspects its return value which would contain the rendered html if you want to check that.
Assuming you really do want to unit test this, then I don't see anything intrinsically wrong with your code. You could try Moq instead of Rhino which is what I use.
This question may also be pertinent to your issue without how Rhino handles abstract classes:
Mock abstract class default behaviour with Rhino

Resources