I am looking for the best way to mock HttpContext.Request.Cookies in Asp.Net Web Forms.
Following is my code:
public void Method1()
{
var _cookie = this.Context.Request.Cookies["PersonID"];
if (_cookie != null)
{
//some code.........
}
}
Below is part of my Test method code:
using (var httpSimulator = new HttpSimulator("/", #"c:\inetpub\").SimulateRequest(new Uri(request), form))
{
//some code
var aObject= new ClassA(HttpContext.Current);
aObject.Method1();
}
I am not sure if we can mock cookies for HttpRequest.
Please help.
Many Thanks In Advance,
Thanks,
Kan
Your quickest solution is to wrap HttpContext with a wrapper class. But you can only get away with this if the methods return a scalar value or an object via its interface.
So IF it returns a non mock-able object, your screwed.
From my experience, the best way to achieve a high percentage of testable code is to layer your app. In this case you would want to LAYER UP all usages of HttpContext. That means to use HttpContext on the UI layer (code behind or view). You would have to sacrifice testability (mockability) on these upper layers.
Related
I am trying to write a Unit Tests to a legacy code using Mockito.
But I am not able to understand how do I mock it. Can some please help.
The real problem I am facing is actually I am not able to decide how to make a decision on what exactly is to be mocked? Below is the code. I have looked at numerous videos on YouTube and read many Mockito Tutorials but all of them seem to be guiding mostly about how to use the Mockito Framework.
The basic idea of what to Mock is still unclear. Please guide if you have a better source. I do understand that the code showed below does not really showcase the best coding practice.
public class DataFacade {
public boolean checkUserPresent(String userId){
return getSomeDao.checkUserPresent(userId);
}
private SomeDao getSomeDao() {
DataSource dataSource = MyDataSourceFactory.getMySQLDataSource();
SomeDao someDao = new SomeDao(dataSource);
}
}
Well, a Unittest, as the name implies, tests a unit. You should mock anything that isn't part of that unit, especially external dependencies. For example, a DAO is normally a good example for something that will be mocked in tests where the class under tests uses it, because otherwise you would really have actual data access in your test, making it slower and more prone to failure because of external reasons (for example, if your dao connects to a Datasource, that Datasource's target (for example, the database) may be down, failing your test even if the unit you wanted to test is actually perfectly fine). Mocking the DAO allows you to test things independently.
Of course, your code is bad. Why? You are creating everything in your method by calling some static factory method. I suggest instead using dependency injection to inject the DAO into your facade, for example...
public DataFacade(SomeDao someDao) {
this.someDao = someDao;
}
This way, when instantiating your DataFacade, you can give it a dao, which means, in your test you can give it a mock, for example...
#Test
public void testSomething() {
SomeDao someDaoMock = Mockito.mock(SomeDao.class);
DataFacade toTest = new DataFacade(someDaoMock);
...now you can prepare your mock to do something and then call the DataFace method
}
Dependency injection frameworks like Spring, Google Guice, etc. can make this even easier to manage, but the first step is to stop your classes from creating their own dependencies, but let the dependencies be given to them from the outside, which makes the whole thing a lot better.
You should "mock" the inner objects that you use in your methods.
For example if you write unit tests for DataFacade->checkUserPresent, you should mock the getSomeDao field.
You have a lot of ways to do it, but basically you can make getSomeDao to be public field, or get it from the constructor. In your test class, override this field with mocked object.
After you invoke DataFacade->checkUserPresent method, assert that checkUserPresent() is called.
For exmaple if you have this class:
public class StudentsStore
{
private DbReader _db;
public StudentsStore(DbReader db)
{
_db = db;
}
public bool HasStudents()
{
var studentsCount = _db.GetStudentsCount();
if (studentsCount > 0)
return true;
else
return false;
}
}
And in your test method:
var mockedDb = mock(DbReader.class);
when(mockedDb.GetStudentsCount()).thenReturn(1);
var store = new StudentsSture(mockedDb);
assertEquals(true,store.HasStudents());
I have already had some difficulties on unit tests and I am trying to learn it while using a small project I currently am working on and I ran into this problem these two problems that I hope you can help me with
1- My project is an MVC project. At which level should my unit tests start? They should focus only on the business layer? Should they also test actions on my controllers?
2- I have a method that verifies an username format and then access the DB to check if it is available for use. The return is a boolean whether this username is available or not.
Would one create a unit test for such a method?
I would be interested on testing the format verification, but how would I check them without querying the DB? Also, if the formats are correct, but the username is already in use, I will get a false value, but the validation worked. I could decouple this method, but the DB verification should only happen if the format is correct, so they should somehow be tied.
How would someone with unit tests knowledge solve this issue. Or how would someone refactor this method to be able to test it?
I could create a stub for the DB access, but how would I attach it to my project on the user testing but detach it when running locally?
Thanks!
In your specific case, one easy thing you could do is decompose your verification method into 3 different methods: one to check formatting, one to check DB availability, and one to tie them both together. This would allow you to test each of the sub-functions in isolation.
In more complex scenarios, other techniques may be useful. In essence, this is where dependency injection and inversion of control come in handy (unfortunately, those phrases mean different things to different people, but getting the basic ideas is usually a good start).
Your goal should be to decouple the concept of "Check if this username is available" from the implementation of checking the DB for it.
So, instead of this:
public class Validation
{
public bool CheckUsername(string username)
{
bool isFormatValid = IsFormatValid(username);
return isFormatValid && DB.CheckUsernameAvailability(username);
}
}
You could do something like this:
public class Validation
{
public bool CheckUsername(string username,
IUsernameAvailabilityChecker checker)
{
bool isFormatValid = IsFormatValid(username);
return isFormatValid && checker.CheckUsernameAvailability(username);
}
}
And then, from your unit test code, you can create a custom IUsernameAvailabilityChecker which does whatever you want for testing purposes. On the other hand, the actual production code can use a different implementation of IUsernameAvailabilityChecker to actually query the database.
Keep in mind that there are many, many techniques to solve this kind of testing problem, and the examples I gave are simple and contrived.
Testing against outside services can be done using mocking. If you've done a good job using interfaces it's very easy to mock various parts of your application. These mocks can be injected into your unit and used like it would normally handle it.
You should start unit testing as soon as possible. If your application is not complete or code needed for testing is absent you can still test against some interface you can mock.
On a sidenote: Unit testing is about testing behavior and is not an effective way to find bugs. You will find bugs with testing but it should not be your goal.
For instance:
interface UserService {
public void setUserRepository(UserRepository userRepository);
public boolean isUsernameAvailable(String username);
}
class MyUserService implements UserService {
private UserRepository userRepository;
public vois setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public boolean isUsernameAvailable(String username) {
return userRepository.checkUsernameAvailability(username);
}
}
interface UserRepository {
public boolean checkUsernameAvailability(String username);
}
// The mock used for testing
class MockUserRepository {
public boolean checkUsernameAvailability(String username) {
if ("john".equals(username)) {
return false;
}
return true;
}
}
class MyUnitTest {
public void testIfUserNotAvailable() {
UserService service = new UserService();
service.setUserRepository(new MockUserRepository);
assertFalse(service.isUsernameAvailable('john')); // yep, it's in use
}
public void testIfUserAvailable() {
UserService service = new UserService();
service.setUserRepository(new MockUserRepository);
assertTrue(service.isUsernameAvailable('mary')); // yep, is available
}
}
I am probably missing something simple here....
I have the following method I want to unit test:
public bool In(Request request)
{
return ("Admin" == (string)request.Session["Type"]);
}
This proved less easy than I expected, because I can't find a way to properly set up a Request object to pass to the method.
Directly newing up a Request results in an object that is not session enabled, and my crude attempts with a makeshift ConfigurableBootstrapper implementation and module were quite unsuccessful.
(I found this blog post, but with no code to illustrate the explanation, I can't make much of it; I could also find no actual examples in the AppHarbify code.)
So, what would be the easiest/recommended way to get a Request object on which I can use Session?
Thanks!
Create an interface that wraps the Request. Something like..
public interface IRequestWrapper {
Session Session { get; set; }
}
The pass this interface instead of the actual implementation to the "In" method.
public bool In(IRequestWrapper request)
{
return ("Admin" == (string)request.Session["Type"]);
}
Now in your Unit Test you would create a fake implementation of IRequestWrapper that returns a Fake Session objtect?
var sut = new SomeClass();
var result = sut.In(new FakeRequest());
Of course the FakeRequest would implement IRequestWrapper and the Session object can be stubbed to return "Admin".
There are other ways to do this, for example, using a Mock/Isolation frameworks, i.e Moq
Hope this helps at least put you in the right direction.
My specific question is when the viewmodel constructor is modeled after the MVVM-Light examples, like this one
public MainViewModel()
{
if (IsInDesignMode)
{
BackgroundBrush = new SolidColorBrush(Colors.Orange);
}
else
{
Messenger.Default.Register<Brush>(
this,
true,
m => BackgroundBrush = m);
ShutdownCommand
= new RelayCommand(ShutdownService.RequestShutdown);
}
}
Should test this? What should I test? Looks like I should test if the class is registered to listen for a message, and if it wires up a ShutdownCommand. My current issue is that ShutdownCommand is setup and calls what it is supposed to call. I also don't quite get TDD yet, so maybe I'm just asking all the wrong questions.
You can test the behaviour of your MainViewModel when a Brush message is received.
You can also test that ShutdownCommand is not null.
Unit testing is about testing the public states, behaviors, and interactions of your objects.
If you simply set a private field in your constructor, what is there to test?
Don't bother unit-testing your simple accessors and mutators. That's just silly, and it doesn't help anyone.
I am using MVC 2 with Areas. To test routing, I am using MvcContrib.
This is the testing code:
[Test]
public void Home()
{
MvcApplication.RegisterRoutes(RouteTable.Routes);
"~/".ShouldMapTo<HomeController>(x => x.Login("Nps"));
}
I am not sure how to call routing definition that are stored in Areas.
Calling AreaRegistration.RegisterAllAreas() is not an option as it gives an exception.
Thanks
Revin
This is the way I do it which works for me
[Test]
public void VerifyRouteMapFor_Test_Area_TestController()
{
RouteTable.Routes.Clear();
var testAreaRegistration = new testAreaRegistration();
testAreaRegistration.RegisterArea(new AreaRegistrationContext(testAreaRegistration.AreaName, RouteTable.Routes));
"~/test/index".ShouldMapTo<testController>(x => x.Index());
}
Rather than calling RegisterAllAreas, you should call the AreaRegistration for that area you are testing. The RegisterAllAreas scans all the loaded assemblies and as a result does too much for a test. I would manually setup the test. If it still throughs and exception post it here or to the mvccontrib mailing list. I am sure that there are some cases where the TestHelper needs to be updated to support areas better. We have not added any specific area support to the test helpers yet.
For a unit test, perhaps it's best to just do the one area. But for an integration test, you'd want to test all the routes in the context, imo.