w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
httpcontext.current.server.mappath and unit testing
You need to abstract out the loading of the XML file. Such as; class WebContentLocator : IContentLocator{ public string GetPath(string relativePath) { return HttpContext.Current.Server.MapPath(relativePath); } } class TestContentLocator : IContentLocator{ string _contentRoot; public TestContentLocator() { _contentRoot = ConfigurationManager.AppSettings["ContentRoot"]; } public string GetPath(string relativePath) { return Path.Combine(_contentRoot, relativePath.Replace("~", string.empty); } } interface IContentLocator { string GetPath(string relativePath); } and in your test inject the TestContentLocator into the code that is doing the XML loading, which would by default be using the WebContentLocator. Fds.ReadXml(_content

Categories : Asp Net Mvc

httpcontext current server mappath shows c:inetpubwwwroot when the current location is somewhere else
Use Server.MapPath("~"), which returns the physical path of the root of your application. The Server.MapPath("/") you are using, returns the physical path of the root of the domain.

Categories : Asp Net Mvc

Unit testing controller using MOQ . How to mock httpcontext
You should mock the HttpContext. I wrote this helper to do this kind of things public static Mock<HttpContextBase> MockControllerContext(bool authenticated, bool isAjaxRequest) { var request = new Mock<HttpRequestBase>(); request.SetupGet(r => r.HttpMethod).Returns("GET"); request.SetupGet(r => r.IsAuthenticated).Returns(authenticated); request.SetupGet(r => r.ApplicationPath).Returns("/"); request.SetupGet(r => r.ServerVariables).Returns((NameValueCollection)null); request.SetupGet(r => r.Url).Returns(new Uri("http://localhost/app", UriKind.Absolute)); if (isAjaxRequest) request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection { { "X-Requested-With", "XMLHttpRequest" } }); var server = new Mock<HttpServerUtilityBase

Categories : Asp Net Mvc

Mocking internal classes with Moq for unit testing
You could make internals visible to Moq by adding InternalsVisibleToAttribute in your project's assembly.cs, like this: [InternalsVisibleTo("DynamicProxyGenAssembly2")] Why "DynamicProxyGenAssembly2" and not "Moq"? It's the name of dynamic assembly created to contain dynamically generated proxy types (all of this is handled by yet another library, Castle's DynamicProxy) which is used by Moq. So you expose types to dynamic proxy assembly, not to Moq itself. But, what's the point of mocking class if there's no overridable member? You won't mock anything and all calls will use actual implementation. Your second solution, I guess I could create an interface (say "IClassB") that ClassB implements, inject that into ClassA, and mock the interface instead. is what I would normally do. It

Categories : Unit Testing

Unit testing the viewmodels and mocking the dependencies
I'm currently using jasmine to unit test my viewmodels. With Jasmine you have an HTML page that executes all your ViewModels. It allows you to mock out functions. The page I linked to, contains a complete description of what you can do with Jasmine. Example: var dataService = Require("services/dataService"); spyOn(dataService , 'returnSomething').andReturn("something"); // execute the system under test here expect(dataService.returnSomething).toHaveBeenCalled();

Categories : Knockout Js

Unit testing real server data exchange?
For instance: I can't find a way to instantiate a view model that would need this interfaces: IChatService, IMvxMessenger, IDataService, ISettingsService Generally this would be done using Mock implementations and then calling the ViewModel constructor directly with those Mocks. I'm having a really hard time figuring out how I can initialize the MMVMCross framework In order to initialise the IoC part of the framework you can use the MvxIoCSupportingTest helper class -https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Test/Cirrious.MvvmCross.Test.Core/MvxIoCSupportingTest.cs If you then need additional parts of the framework, then generally you should mock these in some way. For example, see how navigation is mocked in these two articles: http://blog.fire-development.co

Categories : Unit Testing

500 internal server error on asp.net page caused probably by server.MapPath
The problem is you're trying to save to the App_Data folder - this folder is only available to actual code. You cannot write to it by default, you also cannot output its contents to your website. The App_Data is specifically meant for Data only - such as XML & Database files - see here for more info: MSDN App_Data folder So, even if you managed to save a file into app_data you would not be able to display it - you would receive an unauthorized access error message. To fix, change this: HttpContext.Current.Server.MapPath("~/App_Data/setP") to something like this HttpContext.Current.Server.MapPath("~/uploadImages/setP") Essentially give yourself a different folder to upload to. Update Following from the comments it seems you are getting the A Generic error occurred in GDI+...

Categories : Asp Net

Storing Credentials in Authentication Server made using Java libraries for unit testing
Store a user name as the plain text. Store a user password in the hashed way using SA256 or SHA512 For each user generate salt that will be used for hashing of the password for the user and store it in DB (each user has its own salt). During authentication hash the password that you get from a user in the plain text using the same salt and compare to the stored password.

Categories : Java

ASP.net file upload from a non server - issue with Server.MapPath?
You wrongly getting file name. You should use below code string filename = Path.GetFileName(FileUploadControl.FileName); Of course change control name to your own. Please See: http://msdn.microsoft.com/en-us/library/aa479405.aspx

Categories : Asp Net

Using Server.MapPath() to generate img src, not working
APP_Data is a restricted folder intended for Datasources such as Database only. ASP.Net will not deliver a file in here - try it by going to the URL for that image directly (I.E www.mysite/App_Data/5/62.jpg ) and you will see the error message HTTP Error 403 - Forbidden. Put your images in a folder outside of this and you will be fine, such as a folder in the root Called Images

Categories : Asp Net

Using Server.MapPath to save a file
You can access it through the current context HttpContext.Current.Server.MapPath("~/App_Data/stored"); to get the full file path : var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/stored"), package.Id + ".zip");

Categories : Asp Net

Server.MapPath() with IIS URL Rewrite Module 2.0
I was looking for the same thing so I gave it a try in a test app. It appears that Server.MapPath() does not acknowledge URL Rewrite Module rules. Here is how I tested using an empty web project (Razor syntax): Rewrite rule: <system.webServer> <rewrite> <rules> <rule name="Rewrite rule1 for test1"> <match url="^test1(.*)" /> <action type="Rewrite" url="{R:1}" appendQueryString="true" /> </rule> </rules> </rewrite> </system.webServer> cshtml: <p> The URL for this page is @Request.Url.AbsoluteUri . <br /> MapPath of /test1 is @Server.MapPath("~/test1") <br /> MapPath of / is @Server.MapPath("~/") </p> I

Categories : Iis

Unit test - httpcontext is null, websecurity.CurrentUserId not being populated either
The reason that you're getting 0 back when you hard code 1 is because of this line: Mock<IWebSecurityWrapper> mockWSW = new Mock<IWebSecurityWrapper>(); The version of the IWebSecurityWrapper you're getting is a mock (since you injected it as such). Adding mockSW.Setup(x=>x.CurrentUserId).Returns(1); Should get you what you need. Since we're now telling the mock to return 1 when asked for the CurrentUserId The reason HttpContextFactory didn't work is because the HttpContextFactory implementations I've seen deal with properties on the controller and I suspect your dependency on HttpContext was inside the WebSecurity class itself, hence why you need the wrapper.

Categories : Asp Net Mvc

Why won't File.copy work with Server.MapPath
Server.MapPath is a secure method, and requires that you have AspEnableParentPaths set to true for your application. http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx

Categories : Asp Net

How we Redirect one Page to AnotherPage with Server.MapPath
you don't need MapPath here, since you have relative path you can directly call Response.Redirect Response.Redirect("~/ReportPage.aspx"); Server.MapPath will return physical path of given file. For example when we need to read TEXT file inside root folder var lines = File.ReadAllLines(Server.MapPath("~/temp.txt")); But in your case no need of a Server.MapPath

Categories : C#

Cannot use Server.MapPath to access a external file
Server.MapPath works only with files that are inside the website and is used by specifying a relative location: string configFile = Server.MapPath("~/App_Data/config.xml.config"); If you want to access a file from some other location you will have to manually provide the absolute path to it: string configFile = @"c:worksome_folderconfig.xml.config";

Categories : C#

What using directive do I use for Server.MapPath in a separate .cs file in WebMatrix?
You can assign the Server property to a variable to save a bit of typing: var server = HttpContext.Current.Server; var file = server.MapPath("~/SomeDirectory/Somefile"); To answer the question posed in the title of your post - the using directive you need in the class file is System.Web: using System.Web; I don't know of any "cheat sheet" as such. Experience and a growing familiarity with MSDN help, as does Resharper if you can afford it and have the full version of Visual Studio.

Categories : C#

Mocking in Unit Tests
Well for the AddCategory method, I think you really only need two mocks, one for the ValidationService, and one for the CategoryRepository, because the other dependencies aren't exercised in that function and therefore are irrelevant (the story might be different of course if your ctor throws on null arguments but in this case I think you are OK - albeit you might consider adding these checks in the future :) Anyway, being pedantic, I'd nearly be inclined to write two (or more - maybe one for null input to verify it throws or returns false or whatever) "unit" tests for this function; One to verify that given an invalid category, the function returns false, One to verify that given a valid category, the function calls Add on the CategoryRepository dependency. So it would look like th

Categories : Unit Testing

C# Unit Test Mocking using Moq.dll
Use It.IsAny<Employee> to setup Save method parameter a.Setup(s => s.Save(It.IsAny<Employee>())).Returns(true).Verifiable(); The reason why your test not working is because you have two different employee instances - one for mock setup, and one which is passed to SaveEmployeeData method call. By default those instances will be compared by reference. Moq waits for Save method call with employee instance, which have reference 13 (e.g). But you are passing another employee with reference 42. Thus setup is never invoked. You have two more options override Equals and GetHashCode methods of Employee class. Thus Moq will compare employees not by reference, but by business data. use exactly same instance of employee both for mock setup and SaveEmployeeData method call (prefera

Categories : C#

Server.MapPath returning a path with a folder that doesn’t exists
I don't believe MapPath guarantees that a path exists, it just tacks your virtual path to the context path. I think your problem is that you're using HttpContext.Current.Server.MapPath try using HttpContext.Current.Request.MapPath

Categories : Dotnet

Is there any testing tool/framework for unit testing of Oracle ADF bounded task flow?
What sort of testing are you looking to undertake? Functional, stress/load? Looks to Selenium or Oracle Application Test Suite (OATS) for functional. Look to OATS or Apache JMeter as options for stress/load. The advantage of OATS over other options is it has intelligence built in to understand the ADF framework.

Categories : Unit Testing

Unit-testing and Integration Testing for Large or Medium-Complexity System Models in SIMULINK
I would look into Simulink Design Verifier and Simulink Verification&Validation. Specifically, they offer features such as automated test generation and coverage analysis, which I think are applicable to your problem. As a side note... With regards to the matlab unit-testing framework which you mentioned in your post, this is basically a MATLAB implementation of the xUnit framework. So it obviously comes in handy if you want to be able to apply xUnit design patterns to tests of MATLAB code. The framework can be used to write tests for a Simulink model, but keep in mind that you have to be able to write the tests in MATLAB code. So this just means making use of the Simulink command-line interface (e.g. commands like set_param and sim) to setup and exercise your model, then use th

Categories : Unit Testing

When and why should I switch from functional Selenium testing to unit testing in a Django web app?
I'm using both selenium and unit tests right now, and here are some of my thoughts: Unit test run faster than selenium scenario tests. Unit tests are easier to write then selenium scenario tests. Unit tests are much more granular than selenium scenario tests. Unit tests are less brittle than selenium scenario tests. My selenium tests tend to run in a matter of minutes (they are several pages long) as compared to unit tests which are designed to run in less than a second. I have to spend a lot of time setting up the environment for a specific selenium test and then run it, and then check that the entire environment is in the right state. To test even a slightly different scenario, say, what happens if someone enters a bad value for one field, I have to start over from scratch. Unit tes

Categories : Django

Testing (not unit testing) private method correctness
This is the academia approach for all first year classes at the University of Waterloo, I imagine a similar approach is taken in the real world (my first co-op is 2014 so I don't know just yet). I find it very useful but it takes some time. If you create a class (henceforth mentioned as a module) then you need you create an associative driver module for each class. This driver file will consist of all your tests: testing edge cases and expected input to ensure your function(s) from your module behave as expected. Each driver module will have a main method and for your testing you will need to change the scope of your function from private to public (or call them all in the constructor). Keep in mind we are programming in C and driver modules are much easier to make without changing scope

Categories : C#

Unit testing - implementing equals only to facilitate testing
Uniutils has a perfect reflection equals method you can use for unit testing. This way your production code remains clear from all this test stuff. public class User { private long id; private String first; private String last; public User(long id, String first, String last) { this.id = id; this.first = first; this.last = last; } } Later in test: User user1 = new User(1, "John", "Doe"); User user2 = new User(1, "John", "Doe"); assertReflectionEquals(user1, user2); If you're using Mockito it has it's own means to do the same thing: Mockito.verify(userDeleter).delete(Mockito.refEq(user));

Categories : Java

Testing & Mocking Services with Rspec
It's hard to be specific, since you've not provided your Transaction class code, but at a high level, here's what I'd recommend: Do not use FactoryGirl or Devise helpers - ideally, you're writing a unit test for this class, so you don't want any external dependencies. Stub out any model instances you're dealing with - which is what you've done with account. Stub out any external classes being used within the service (such as Business), and if you're creating instances of those from the classes, then they're doubles too. Here's a vague example with no real implementation: require './app/services/transaction' describe Transaction do let(:transaction) { Transaction.new account, :foo => 'bar' } let(:account) { double 'Account', :confirmed? => true } let(:business) { do

Categories : Ruby On Rails

WCF Service Method - Refactoring for Unit Test and Mocking
You need to be able to swap out any 'services' (classes that you new up in a method or fields in the class) which connect to other systems (database, email server etc) so you need to create interfaces for the classes and inject the correct implementation at runtime and in your unit test, you can create mock or fake implementations for testing purposes. A good start would be to define an interface for: JobManager EmailSchedulerTrace SuppressionManager You also might need to move the functionality of your static methods on Email GetEmailByName GetConsumerId if they encapsulate database access or any other service which you cannot isolate.

Categories : Wcf

Mocking azure blob storage in unit tests
The Storage Library doesn't have an interface to use for mocking, so if you wanted to really mock this out I think you have two options: Create an interface yourself and hide the interaction with the storage library behind a class of your own. Then use your interface for the mocked tests. This is something I've done a lot of in the past, trying to abstract the use of the storage library away from the rest of the app. Of course, you can do this abstraction in your own code, or the storage library is out on GitHub. You could fork it and start adding interfaces to make the mocking easier. I think you'd have less work to just create an interface in your own code and a concrete implementation that did the necessary work to interact with the storage sub system for the things specific to

Categories : Unit Testing

Mocking HttpActionContext.ActionArguments when testing Web.Api ActionFilter
According to the AspNetWebStack source code, actionContext.ActionArguments is just a simple Dictionary. It is therefore pretty trivial to insert a key value pair into it. I would just do something like actionContext.ActionArguments[key] = value; in the arrange part of the unit test. Hope that helps

Categories : C#

CakePHP Controller Testing: Mocking $this->referer()
You aren't mocking any methods This line $this->Controller = $this->generate('Users'); Only generates a test controller, you aren't specifying any methods to mock. To specify that some controller methods need to be mocked refer to the documentation: $Posts = $this->generate('Users', array( 'methods' => array( 'referer' ), ... )); The expectation is never triggered Before asking this question, you probably had an internal conversation a bit like: "why is it saying that my expectation is never called? I'll just use $this->any() and ignore it.." Don't use $this->any() unless it really doesn't matter if the mocked method is called at all. Looking at the controller code, you're expecting it to be called exactly once - so instead use $this->once():

Categories : Cakephp

ember.js unit testing and integration testing
To run the test from just one JS file, specify the file name in the "files" array of your karma config file. Here's a sample config file I used recently. My example runs 2 js files for the test portion (the last 2 in the list), but you could easily just do one. Bryan

Categories : Ember Js

Mocking Angular module dependencies in Jasmine unit tests
Here's what I figured out: I wasn't loading any 'angular-table' modules in my karma.conf.js file, hence the error. This was intentional at first as I wanted to test the 'events' module without the actual table module. I was able to easily mock the 'angular-table' module by creating a new file in my test folder called 'mocks/angular-table.js' and added the following code: /mocks/angular-table.js 'use-strict'; angular.module('angular-table', []); I added this file to my karma.conf.js file, along with the real 'events' module I wanted to test: karma.conf.js ... files = [ JASMINE, JASMINE_ADAPTER, 'scripts/libs/angular.js', 'scripts/libs/angular-mocks.js', 'scripts/events.js', // this is the real module. 'scripts/mocks/*.js', //loads all custom mocks. 'scri

Categories : Unit Testing

Unit test Flask view mocking out celery tasks
I tried also any @patch decorator and it didn't work And I found mock in setUp like: import unittest from mock import patch from mock import MagicMock class TestLaunchTask(unittest.TestCase): def setUp(self): self.patcher_1 = patch('app.views.launch_task') mock_1 = self.patcher_1.start() launch_task = MagicMock() launch_task.as_string = MagicMock(return_value = 'test') mock_1.return_value = launch_task def tearDown(self): self.patcher_1.stop()

Categories : Python

Grails Testing with Spock - Which Mocking Framework Select?
When you are using spock framework for testing, then try to leverage the options and styles provided by the framework itself. Spock framework helps in achieving a BDD [Behavioral Design Development]. By behavior I meant, you can tightly couple the business acceptance scenario to the development cycle. I tried to get your test case written in Spock as it can be re-written as: @TestFor(MyController) class MyControllerSpec extends ControllerSpec { void "test service method in called once and only once"(){ //Defines the behavior of setup setup: "Only one invocation of service method" def myService = Mock(MyService){ //Make sure serviceMethod is called only once from the controller //Beauty of Spock is that you can test the c

Categories : Testing

Testing a fragment (Android), mocking getActivity() call
I have employed this hack: // Needed because Fragment.mActivity is package-private package android.support.v4.app; public class FragmentInjector { public static void injectActivity(Fragment fragment, FragmentActivity fragmentActivity) { fragment.mActivity = fragmentActivity; } } Alternatively you could employ reflection to change the value of fragment.mActivity. I don't know of any other way.

Categories : Android

Best Practice for mocking system date and Location in Objective C unit tests
The traditional solution to this sort of problem is Dependency Injection, which helps drive Separation of Concerns. The job of the SeasonService is to determine what season it is based on the latitude and month. Determining/storing the latitude and month should probably should be the responsibility of other classes. Depending on your system's requirements, this could be achieved either through construction parameters or method parameters. Either way would allow you to mock out a specific month or latitude directly instead of resorting to category tricks. Constructor injection: - initWithLatitudeProvider:id<LatitudeProvider> latitudeProvider andMonthProvider:id<MonthProvider> monthProvider { // set ivars or properties } - (t_Season)currentSeason { // Get

Categories : Objective C

Play Framework 2 scala specs2 mockito, how do I write a mocking unit test
After a lot of googling and hair pulling I came up with the following package test import org.specs2.mutable._ import play.api.test._ import play.api.test.Helpers._ import org.specs2.mock._ import org.mockito.Matchers class ToTest { def go(a:String) = { "other" } } class MockSpec extends Specification with Mockito { "Mock" should { "work" in { //assemble val m = mock[ToTest] m.go(anyString) returns "tested" //act val result = m.go("test") //assert result must equalTo("tested") there was one(m).go(Matchers.eq("test")) } } }

Categories : Unit Testing

Unit testing of a unit of Application
The mappedBy attribute value must be the name of a field, on the other side of the association, which contains the mapping of this bidirectional association. So instead of @OneToMany(cascade = CascadeType.ALL,orphanRemoval = true,mappedBy = "VoucherType") private final List<Voucher> vouchers = new ArrayList<Voucher>(); you should have @OneToMany(cascade = CascadeType.ALL,orphanRemoval = true,mappedBy = "voucherTypeId") private final List<Voucher> vouchers = new ArrayList<Voucher>(); Instead of OneToMany(cascade = CascadeType.ALL,orphanRemoval = true,mappedBy = "VoucherCategory") private final List<VoucherType> voucherTypes = new ArrayList<VoucherType>(); you should have OneToMany(cascade = CascadeType.ALL,orphanRemoval = true,mappedBy = "v

Categories : Spring

StreamReader Server.MapPath - Physical path given, virtual path expected
MapPath translates paths starting from ~ to full local path. Does not look like you need it in your code. If the file is supposed to be at fixed place all the time, open in directly by full path. If it is relative to site root, then use something like Server.MapPath("~/status.txt")

Categories : C#

Unit testing of DAO
The idea of using mock objects to perform your unit testing strikes me as peculiar as all you are doing is testing your mock objects instead of your real ones. If you think you need to use mock objects to emulate database access then your entire architecture is wrong. I personally build all my software using the 3-Tier Architecture where I can have as many objects as I like in the Business layer, but only 1 object in the Data Access layer. Thus if I wanted to exchange real database access with dummy database access where would I make the change? All 200+ objects in my Business layer, or just the 1 object in the Data Access layer? Why should I then implement a mechanism to change every object within my application when all I really need to do is change one? Controllers are meant to

Categories : Unit Testing



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.