Search Results

Search found 2240 results on 90 pages for 'assert redirected to'.

Page 8/90 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • javaf, problem...plz help someone...urgent [closed]

    - by innovative_aj
    i have made a word guessing game, when i click myButton to check if the guessed word is right or wrong, ball1 is moved into the "container" if its right, i want that when i click the button again and if the typed word is right, the 2nd ball should move into the container too... means one ball per correct answer...plz help me someone and provide me with the code that i can implement, its quite urgent... controller class coding /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package project3; import java.net.URL; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.StackPane; import javafx.scene.shape.Circle; /** * FXML Controller class * * @xxx */ public class MyFxmlController implements Initializable { @FXML // fx:id="ball1" private Circle ball1; // Value injected by FXMLLoader @FXML // fx:id="ball2" private Circle ball2; // Value injected by FXMLLoader @FXML // fx:id="ball3" private Circle ball3; // Value injected by FXMLLoader @FXML // fx:id="ball4" private Circle ball4; // Value injected by FXMLLoader @FXML // fx:id="container" private Circle container; // Value injected by FXMLLoader @FXML // fx:id="myButton" private Button myButton; // Value injected by FXMLLoader @FXML // fx:id="myLabel1" private Label myLabel1; // Value injected by FXMLLoader @FXML // fx:id="myLabel2" private Label myLabel2; // Value injected by FXMLLoader @FXML // fx:id="pane" private StackPane pane; // Value injected by FXMLLoader @FXML // fx:id="txt" private TextField txt; // Value injected by FXMLLoader @Override // This method is called by the FXMLLoader when initialization is complete public void initialize(URL fxmlFileLocation, ResourceBundle resources) { assert ball1 != null : "fx:id=\"ball1\" was not injected: check your FXML file 'MyFxml.fxml'."; assert ball2 != null : "fx:id=\"ball2\" was not injected: check your FXML file 'MyFxml.fxml'."; assert ball3 != null : "fx:id=\"ball3\" was not injected: check your FXML file 'MyFxml.fxml'."; assert ball4 != null : "fx:id=\"ball4\" was not injected: check your FXML file 'MyFxml.fxml'."; assert container != null : "fx:id=\"container\" was not injected: check your FXML file 'MyFxml.fxml'."; assert myButton != null : "fx:id=\"myButton\" was not injected: check your FXML file 'MyFxml.fxml'."; assert myLabel1 != null : "fx:id=\"myLabel1\" was not injected: check your FXML file 'MyFxml.fxml'."; assert myLabel2 != null : "fx:id=\"myLabel2\" was not injected: check your FXML file 'MyFxml.fxml'."; assert pane != null : "fx:id=\"pane\" was not injected: check your FXML file 'MyFxml.fxml'."; assert txt != null : "fx:id=\"txt\" was not injected: check your FXML file 'MyFxml.fxml'."; // initialize your logic here: all @FXML variables will have been injected myButton.setOnAction(new EventHandler<ActionEvent>(){ @Override public void handle(ActionEvent event) { int count = 0; String guessed=txt.getText(); boolean result; result=MyCode.check(guessed); if(result) { ball1.setTranslateX(600); ball1.setTranslateY(250-container.getRadius()); //ball2.setTranslateX(600); // ball2.setTranslateY(250-container.getRadius()); } else System.out.println("wrong"); } }); } } word guessing logic public class MyCode { static String x="Netbeans"; static String y[]={"net","beans","neat","beat","bet"}; //static int counter; // public MyCode() { // counter++; //} static boolean check(String guessed) { int count=0; boolean result=false; //counter++; //System.out.println("turns"+counter); for(count=0;count<5;count++) { if(guessed.equals(y[count])) { result=true; break; } } if(result) System.out.println("Right"); else System.out.println("Wrong"); return result; } }

    Read the article

  • dynamic page caching- show redirected html cache page or show the dynamic page?

    - by i need help
    would like your comments. Eg: When user first visit www.testing.com/productdetailpage.asp I will use caching- store the whole page into productdetailpage.html When the user go to reopen productdetailpage.asp, user will be redirected to www.testing.com/productdetailpage.html It means they will see productdetailpage.html, not .asp Is this a good way? Any implication in terms of SEO and other part? Will it be better to read datas from .html into .asp and show the final page as .asp all the time?

    Read the article

  • [Facebook Graph API - Android] I want to know the HTTPSConnection redirected to which URL?

    - by Mohammad Abdelaziz
    I am building an application that uses the Facebook Graph API. To get the access token I should send the following request https://graph.facebook.com/oauth/authorize? client_id=...& redirect_uri=http://www.example.com/callback It redirects to the redirect_uri with the code to be used as access token. How can I capture that the HttpsURLConnection is redirected and how to get the code? Is it possible or I need to have server that gets the access token?

    Read the article

  • How to stop going to redirected URL in Google App Engine with Python?

    - by user1762586
    I'm using urlfetch from google app engine, but it keeps going to the redirected final page even though I use: result = urlfetch.fetch(classUrl, payload=None, method=urlfetch.GET, headers={}, allow_truncated=False, follow_redirects=False) E.g. if classUrl was a searched term in Google (https://www.google.com/search?q=setInstanceFollowRedirects()+python&oq=setInstanceFollowRedirects()+python&sugexp=chrome,mod=0&sourceid=chrome&ie=UTF-8) it would redirect me to www.google.com How do I stop this redirection? Thanks!

    Read the article

  • Does GCC have a built-in compile time assert?

    - by VladLosev
    Our existing compile-time assert implementation is based on negative array index, and it provides poor diagnostic output on GCC. C++0x's static_assert is a very nice feature, and the diagnostic output it provides is much better. I know GCC has already implemented some C++0x features. Does anyone know if static_assert is among them and if it is then since what GCC version?

    Read the article

  • What is the difference between panic and an assert?

    - by acidzombie24
    Go doesn't provide assertions. They are undeniably convenient, but our experience has been that programmers use them as a crutch to avoid thinking about proper error handling and reporting. However it has print and println which does panic like print, aborts execution after printing panicln like println, aborts execution after printing Isnt that the same thing as an assert? Why would they claim the above but have panic? i can see it leading to the same problems but adding an error msg to the end of it which can easily be abused. Am i missing something?

    Read the article

  • SharePoint 2007: Moving main site, to be a subsite - How can urls be redirected/changed?

    - by program247365
    The setup: SharePoint 2007 (MOSS Enterprise) on WINSVR03/IIS6 One site collection, with one access mapping (http://mainsite) currently I'm moving the main SharePoint site, in our one site collection, to be a subsite in a new site collection. I'm using SharePoint Content Deployment Wizard to complete this task (http://spdeploymentwizard.codeplex.com/). The Question So the main site http://mainsite being moved has many subsites, etc. I want to be sure that urls like this: http://mainsite/subsite/doclib/doc1.docx map to and redirect to the new url: http://newsite/mainsite/subsite/doclib/doc1.docx ? And furthermore: I'm aware of this - http://rdacollaboration.codeplex.com/releases/view/28073 , however is it IIS7 only? That'd wouldn't work for me. Looking at this question - http://serverfault.com/questions/107537/dealing-with-moved-documents-and-sites-in-sharepoint is the only one I see that is similar. Would an IIS redirect of http://mainsite to http://newsite/mainsite work only for the root url?

    Read the article

  • Why is cron mailing me program output even though I've redirected to /dev/null?

    - by Server Fault
    I'm trying to restart a system process through cron and getting emailed the startup output of the process. I thought redirecting STDOUT and SDTERR to /dev/null would "silence" the output but alas, this has not work. How can I get cron to silently restart this service? crontab entry: 0 6 * * * service sympa stop &>/dev/null; service sympa start &> /dev/null sample output from restart email: Stopping Sympa bounce manager bounced ...done. * Stopping Sympa task manager task_manager ...done. * Stopping Sympa mailing list archive manager archived ...done. * Stopping Sympa mailing list manager sympa ...done. ... waiting Prototype mismatch: sub Lock::LOCK_SH () vs none at /home/sympa/bin/Lock.pm line 38. Constant subroutine LOCK_SH redefined at /home/sympa/bin/Lock.pm line 38. Prototype mismatch: sub Lock::LOCK_EX () vs none at /home/sympa/bin/Lock.pm line 39. Constant subroutine LOCK_EX redefined at /home/sympa/bin/Lock.pm line 39. Prototype mismatch: sub Lock::LOCK_NB () vs none at /home/sympa/bin/Lock.pm line 40. Constant subroutine LOCK_NB redefined at /home/sympa/bin/Lock.pm line 40.

    Read the article

  • jQuery AJAX request (Rails 3) gets redirected and returns empty message body (only with SSL)!

    - by elsurudo
    I'm trying to do a manual jQuery AJAX request the following way: $("#user_plan_id").change(function() { $("#plan_container").load('/plans/' + this.value); }); I have the "rails.js" file included in my header, and a "<%= csrf_meta_tag %". I see from my log that the request IS getting to the server (although without the authenticity token... does rails.js even do this?), but the response is a 302 (Found) rather than 200, and no data actually gets rendered. Any ideas? Edit: I now see that the first request redirects, and the proper partial gets rendered on the redirect. However, the 2nd response's body (on the client-side) is still empty. I'm guessing jQuery uses the first response and doesn't have a listener set up for the redirect. How do I get around this? Also, another note: the page doing the requesting is an HTTPS page. Here is what my log says: Started GET "/plans/221168073" for 127.0.0.1 at Tue Jun 15 01:24:06 -0400 2010 Processing by PlansController#show as HTML Parameters: {"id"=>"221168073"} DEPRECATION WARNING: Using #request_uri is deprecated. Use fullpath instead. (called from ensure_proper_protocol at /Users/ernestsurudo/Sites/vidfolia/vendor/plugins/ssl_requirement/lib/ssl_requirement.rb:57) Redirected to http://vidfolia.com/plans/221168073 Completed 302 Found in 1ms It turns out that if I turn off SSL requirement for that page, it works! I still have no idea why, though. So I suppose my question is: what is the workaround?

    Read the article

  • jQuery AJAX request (Rails 3) gets redirected and returns empty message body!

    - by elsurudo
    I'm trying to do a manual jQuery AJAX request the following way: $("#user_plan_id").change(function() { $("#plan_container").load('/plans/' + this.value); }); I have the "rails.js" file included in my header, and a "<%= csrf_meta_tag %". I see from my log that the request IS getting to the server (although without the authenticity token... does rails.js even do this?), but the response is a 302 (Found) rather than 200, and no data actually gets rendered. Any ideas? Edit: I now see that the first request redirects, and the proper partial gets rendered on the redirect. However, the 2nd response's body (on the client-side) is still empty. I'm guessing jQuery uses the first response and doesn't have a listener set up for the redirect. How do I get around this? Also, another note: the page doing the requesting is an HTTPS page. Here is what my log says: Started GET "/plans/221168073" for 127.0.0.1 at Tue Jun 15 01:24:06 -0400 2010 Processing by PlansController#show as HTML Parameters: {"id"=>"221168073"} DEPRECATION WARNING: Using #request_uri is deprecated. Use fullpath instead. (called from ensure_proper_protocol at /Users/ernestsurudo/Sites/vidfolia/vendor/plugins/ssl_requirement/lib/ssl_requirement.rb:57) Redirected to http://vidfolia.com/plans/221168073 Completed 302 Found in 1ms Perhaps it has something to do with the deprecation warning?

    Read the article

  • RoR routing problem. Calling custom action, but getting redirected to show action

    - by conorgil
    I am working on a project in ruby on rails and I am having a very difficult time with a basic problem. I am trying to call a custom action in one of my controllers, but the request is somehow getting redirected to the default 'show' action and I cannot figure out why. link in edit.html.erb: <%= link_to 'Mass Text Entry', :action=>"create_or_add_food_item_from_text" %> Error from development.log: ActiveRecord::RecordNotFound (Couldn't find Menu with ID=create_or_add_food_item_from_text): app/controllers/menus_controller.rb:20:in `show' routes.rb file: ActionController::Routing::Routes.draw do |map| map.resources :nutrition_objects map.resources :preference_objects map.resources :institutions map.resources :locations map.resources :menus map.resources :food_items map.resources :napkins map.resources :users map.resource :session, :controller => 'session' map.root :controller=>'pages', :action=>'index' map.about '/about', :controller=>'pages', :action=>'about' map.contact '/contact', :controller=>'pages', :action=>'contact' map.home '/home', :controller=>'pages', :action=>'index' map.user_home '/user/home', :controller=>'rater', :action=>'index' map.user_napkins '/user/napkins', :controller=>'rater', :action=>'view_napkins' map.user_preferences '/user/preferences',:controller=>'rater', :action=>'preferences' map.blog '/blog', :controller=>'pages', :action=>'blog' map.signup '/signup', :controller=>'users', :action=>'new' map.login '/login', :controller=>'session', :action=>'new' map.logout '/logout', :controller=>'session', :action=>'destroy' # Install the default routes as the lowest priority. map.connect ':controller/:action' map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end Menus_controller.rb: class MenusController < ApplicationController ... def create_or_add_food_item_from_text end ... end create_or_add_food_item_from_text.html.erb simply has a div to show a form with a text box in it. I have the rest of my app working fine, but this is stumping me. Any help is appreciated.

    Read the article

  • Doing your first mock with JustMock

    - by mehfuzh
    In this post, i will start with a  more traditional mocking example that  includes a fund transfer scenario between two different currency account using JustMock.Our target interface that we will be mocking looks similar to: public interface ICurrencyService {     float GetConversionRate(string fromCurrency, string toCurrency); } Moving forward the SUT or class that will be consuming the  service and will be invoked by user [provided that the ICurrencyService will be passed in a DI style] looks like: public class AccountService : IAccountService         {             private readonly ICurrencyService currencyService;               public AccountService(ICurrencyService currencyService)             {                 this.currencyService = currencyService;             }               #region IAccountService Members               public void TransferFunds(Account from, Account to, float amount)             {                 from.Withdraw(amount);                 float conversionRate = currencyService.GetConversionRate(from.Currency, to.Currency);                 float convertedAmount = amount * conversionRate;                 to.Deposit(convertedAmount);             }               #endregion         }   As, we can see there is a TransferFunds action implemented from IAccountService  takes in a source account from where it withdraws some money and a target account to where the transfer takes place using the provided conversion rate. Our first step is to create the mock. The syntax for creating your instance mocks is pretty much same and  is valid for all interfaces, non-sealed/sealed concrete instance classes. You can pass in additional stuffs like whether its an strict mock or not, by default all the mocks in JustMock are loose, you can use it as default valued objects or stubs as well. ICurrencyService currencyService = Mock.Create<ICurrencyService>(); Using JustMock, setting up your expectations and asserting them always goes with Mock.Arrang|Assert and this is pretty much same syntax no matter what type of mocking you are doing. Therefore,  in the above scenario we want to make sure that the conversion rate always returns 2.20F when converting from GBP to CAD. To do so we need to arrange in the following way: Mock.Arrange(() => currencyService.GetConversionRate("GBP", "CAD")).Returns(2.20f).MustBeCalled(); Here, I have additionally marked the mock call as must. That means it should be invoked anywhere in the code before we do Mock.Assert, we can also assert mocks directly though lamda expressions  but the more general Mock.Assert(mocked) will assert only the setups that are marked as "MustBeCalled()”. Now, coming back to the main topic , as we setup the mock, now its time to act on it. Therefore, first we create our account service class and create our from and to accounts respectively. var accountService = new AccountService(currencyService);   var canadianAccount = new Account(0, "CAD"); var britishAccount = new Account(0, "GBP"); Next, we add some money to the GBP  account: britishAccount.Deposit(100); Finally, we do our transfer by the following: accountService.TransferFunds(britishAccount, canadianAccount, 100); Once, everything is completed, we need to make sure that things were as it is we have expected, so its time for assertions.Here, we first do the general assertions: Assert.Equal(0, britishAccount.Balance); Assert.Equal(220, canadianAccount.Balance); Following, we do our mock assertion,  as have marked the call as “MustBeCalled” it will make sure that our mock is actually invoked. Moreover, we can add filters like how many times our expected mock call has occurred that will be covered in coming posts. Mock.Assert(currencyService); So far, that actually concludes our  first  mock with JustMock and do stay tuned for more. Enjoy!!

    Read the article

  • C# error casting from double to int32

    - by orfix
    using NUF = NUnit.Framework; [NUF.Test]public void DifferentCastingTest() { NUF.Assert.That((int)0.499999D, NUF.Is.EqualTo(0)); NUF.Assert.That((int)0.500000D, NUF.Is.EqualTo(0)); // !!! row 1 NUF.Assert.That((int)1.499999D, NUF.Is.EqualTo(1)); NUF.Assert.That((int)1.500000D, NUF.Is.EqualTo(1)); // !!! row 2 NUF.Assert.That(System.Convert.ToInt32(0.499999D), NUF.Is.EqualTo(0)); NUF.Assert.That(System.Convert.ToInt32(0.500000D), NUF.Is.EqualTo(0)); // !!! NUF.Assert.That(System.Convert.ToInt32(1.499999D), NUF.Is.EqualTo(1)); NUF.Assert.That(System.Convert.ToInt32(1.500000D), NUF.Is.EqualTo(2)); //!!! row 3 } The same double value (1.5D) is converted in different way by casting and Convert.ToInt32 (see row 2 and 3), and two double with same mantissa (0.5 and 1.5) is rounded in different mode (see row 1 and 2). Is it a bug?

    Read the article

  • SQL University: Database testing and refactoring tools and examples

    - by Mladen Prajdic
    This is a post for a great idea called SQL University started by Jorge Segarra also famously known as SqlChicken on Twitter. It’s a collection of blog posts on different database related topics contributed by several smart people all over the world. So this week is mine and we’ll be talking about database testing and refactoring. In 3 posts we’ll cover: SQLU part 1 - What and why of database testing SQLU part 2 - What and why of database refactoring SQLU part 3 - Database testing and refactoring tools and examples This is the third and last part of the series and in it we’ll take a look at tools we can test and refactor with plus some an example of the both. Tools of the trade First a few thoughts about how to go about testing a database. I'm firmily against any testing tools that go into the database itself or need an extra database. Unit tests for the database and applications using the database should all be in one place using the same technology. By using database specific frameworks we fragment our tests into many places and increase test system complexity. Let’s take a look at some testing tools. 1. NUnit, xUnit, MbUnit All three are .Net testing frameworks meant to unit test .Net application. But we can test databases with them just fine. I use NUnit because I’ve always used it for work and personal projects. One day this might change. So the thing to remember is to be flexible if something better comes along. All three are quite similar and you should be able to switch between them without much problem. 2. TSQLUnit As much as this framework is helpful for the non-C# savvy folks I don’t like it for the reason I stated above. It lives in the database and thus fragments the testing infrastructure. Also it appears that it’s not being actively developed anymore. 3. DbFit I haven’t had the pleasure of trying this tool just yet but it’s on my to-do list. From what I’ve read and heard Gojko Adzic (@gojkoadzic on Twitter) has done a remarkable job with it. 4. Redgate SQL Refactor and Apex SQL Refactor Neither of these refactoring tools are free, however if you have hardcore refactoring planned they are worth while looking into. I’ve only used the Red Gate’s Refactor and was quite impressed with it. 5. Reverting the database state I’ve talked before about ways to revert a database to pre-test state after unit testing. This still holds and I haven’t changed my mind. Also make sure to read the comments as they are quite informative. I especially like the idea of setting up and tearing down the schema for each test group with NHibernate. Testing and refactoring example We’ll take a look at the simple schema and data test for a view and refactoring the SELECT * in that view. We’ll use a single table PhoneNumbers with ID and Phone columns. Then we’ll refactor the Phone column into 3 columns Prefix, Number and Suffix. Lastly we’ll remove the original Phone column. Then we’ll check how the view behaves with tests in NUnit. The comments in code explain the problem so be sure to read them. I’m assuming you know NUnit and C#. T-SQL Code C# test code USE tempdbGOCREATE TABLE PhoneNumbers( ID INT IDENTITY(1,1), Phone VARCHAR(20))GOINSERT INTO PhoneNumbers(Phone)SELECT '111 222333 444' UNION ALLSELECT '555 666777 888'GO-- notice we don't have WITH SCHEMABINDINGCREATE VIEW vPhoneNumbersAS SELECT * FROM PhoneNumbersGO-- Let's take a look at what the view returns -- If we add a new columns and rows both tests will failSELECT *FROM vPhoneNumbers GO -- DoesViewReturnCorrectColumns test will SUCCEED -- DoesViewReturnCorrectData test will SUCCEED -- refactor to split Phone column into 3 partsALTER TABLE PhoneNumbers ADD Prefix VARCHAR(3)ALTER TABLE PhoneNumbers ADD Number VARCHAR(6)ALTER TABLE PhoneNumbers ADD Suffix VARCHAR(3)GO-- update the new columnsUPDATE PhoneNumbers SET Prefix = LEFT(Phone, 3), Number = SUBSTRING(Phone, 5, 6), Suffix = RIGHT(Phone, 3)GO-- remove the old columnALTER TABLE PhoneNumbers DROP COLUMN PhoneGO-- This returns unexpected results!-- it returns 2 columns ID and Phone even though -- we don't have a Phone column anymore.-- Notice that the data is from the Prefix column-- This is a danger of SELECT *SELECT *FROM vPhoneNumbers -- DoesViewReturnCorrectColumns test will SUCCEED -- DoesViewReturnCorrectData test will FAIL -- for a fix we have to call sp_refreshview -- to refresh the view definitionEXEC sp_refreshview 'vPhoneNumbers'-- after the refresh the view returns 4 columns-- this breaks the input/output behavior of the database-- which refactoring MUST NOT doSELECT *FROM vPhoneNumbers -- DoesViewReturnCorrectColumns test will FAIL -- DoesViewReturnCorrectData test will FAIL -- to fix the input/output behavior change problem -- we have to concat the 3 columns into one named PhoneALTER VIEW vPhoneNumbersASSELECT ID, Prefix + ' ' + Number + ' ' + Suffix AS PhoneFROM PhoneNumbersGO-- now it works as expectedSELECT *FROM vPhoneNumbers -- DoesViewReturnCorrectColumns test will SUCCEED -- DoesViewReturnCorrectData test will SUCCEED -- clean upDROP VIEW vPhoneNumbersDROP TABLE PhoneNumbers [Test]public void DoesViewReturnCoorectColumns(){ // conn is a valid SqlConnection to the server's tempdb // note the SET FMTONLY ON with which we return only schema and no data using (SqlCommand cmd = new SqlCommand("SET FMTONLY ON; SELECT * FROM vPhoneNumbers", conn)) { DataTable dt = new DataTable(); dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection)); // test returned schema: number of columns, column names and data types Assert.AreEqual(dt.Columns.Count, 2); Assert.AreEqual(dt.Columns[0].Caption, "ID"); Assert.AreEqual(dt.Columns[0].DataType, typeof(int)); Assert.AreEqual(dt.Columns[1].Caption, "Phone"); Assert.AreEqual(dt.Columns[1].DataType, typeof(string)); }} [Test]public void DoesViewReturnCorrectData(){ // conn is a valid SqlConnection to the server's tempdb using (SqlCommand cmd = new SqlCommand("SELECT * FROM vPhoneNumbers", conn)) { DataTable dt = new DataTable(); dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection)); // test returned data: number of rows and their values Assert.AreEqual(dt.Rows.Count, 2); Assert.AreEqual(dt.Rows[0]["ID"], 1); Assert.AreEqual(dt.Rows[0]["Phone"], "111 222333 444"); Assert.AreEqual(dt.Rows[1]["ID"], 2); Assert.AreEqual(dt.Rows[1]["Phone"], "555 666777 888"); }}   With this simple example we’ve seen how a very simple schema can cause a lot of problems in the whole application/database system if it doesn’t have tests. Imagine what would happen if some outside process would depend on that view. It would get wrong data and propagate it silently throughout the system. And that is not good. So have tests at least for the crucial parts of your systems. And with that we conclude the Database Testing and Refactoring week at SQL University. Hope you learned something new and enjoy the learning weeks to come. Have fun!

    Read the article

  • Writing Unit Tests for an ASP.NET MVC Action Method that handles Ajax Request and Normal Request

    - by shiju
    In this blog post, I will demonstrate how to write unit tests for an ASP.NET MVC action method, which handles both Ajax request and normal HTTP Request. I will write a unit test for specifying the behavior of an Ajax request and will write another unit test for specifying the behavior of a normal HTTP request. Both Ajax request and normal request will be handled by a single action method. So the ASP.NET MVC action method will be execute HTTP Request object’s IsAjaxRequest method for identifying whether it is an Ajax request or not. So we have to create mock object for Request object and also have to make as a Ajax request from the unit test for verifying the behavior of an Ajax request. I have used NUnit and Moq for writing unit tests. Let me write a unit test for a Ajax request Code Snippet [Test] public void Index_AjaxRequest_Returns_Partial_With_Expense_List() {     // Arrange       Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);     //Add XMLHttpRequest request header     request.Setup(req => req["X-Requested-With"]).         Returns("XMLHttpRequest");       IEnumerable<Expense> fakeExpenses = GetMockExpenses();     expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as PartialViewResult;     // Assert     Assert.AreEqual("_ExpenseList", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories");         }   In the above unit test, we are calling Index action method of a controller named ExpenseController, which will returns a PartialView named _ExpenseList, if it is an Ajax request. We have created mock object for HTTPContextBase and setup XMLHttpRequest request header for Request object’s X-Requested-With for making it as a Ajax request. We have specified the ControllerContext property of the controller with mocked object HTTPContextBase. Code Snippet controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller); Let me write a unit test for a normal HTTP method Code Snippet [Test] public void Index_NormalRequest_Returns_Index_With_Expense_List() {     // Arrange               Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);       IEnumerable<Expense> fakeExpenses = GetMockExpenses();       expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as ViewResult;     // Assert     Assert.AreEqual("Index", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model         as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories"); }   In the above unit test, we are not specifying the XMLHttpRequest request header for Request object’s X-Requested-With, so that it will be normal HTTP Request. If this is a normal request, the action method will return a ViewResult with a view template named Index. The below is the implementation of Index action method Code Snippet public ActionResult Index(DateTime? startDate, DateTime? endDate) {     //If date is not passed, take current month's first and last date     DateTime dtNow;     dtNow = DateTime.Today;     if (!startDate.HasValue)     {         startDate = new DateTime(dtNow.Year, dtNow.Month, 1);         endDate = startDate.Value.AddMonths(1).AddDays(-1);     }     //take last date of start date's month, if end date is not passed     if (startDate.HasValue && !endDate.HasValue)     {         endDate = (new DateTime(startDate.Value.Year,             startDate.Value.Month, 1)).AddMonths(1).AddDays(-1);     }     var expenses = expenseRepository.GetMany(         exp => exp.Date >= startDate && exp.Date <= endDate);     //if request is Ajax will return partial view     if (Request.IsAjaxRequest())     {         return PartialView("_ExpenseList", expenses);     }     //set start date and end date to ViewBag dictionary     ViewBag.StartDate = startDate.Value.ToShortDateString();     ViewBag.EndDate = endDate.Value.ToShortDateString();     //if request is not ajax     return View("Index",expenses); }   The index action method will returns a PartialView named _ExpenseList, if it is an Ajax request and will returns a View named Index if it is a normal request. Source Code The source code has been taken from my EFMVC app which can download from here

    Read the article

  • Is it safe to assert a functions return type?

    - by wb
    This question is related to this question. I have several models stored in a collection. I loop through the collection and validate each field. Based on the input, a field can either be successful, have an error or a warning. Is it safe to unit test each decorator and assert that the type of object returned is what you would expect based on the given input? I could perhaps see this being an issue for a language with function return types since my validation function can return one of 3 types. This is the code I'm fiddling with: <!-- #include file = "../lib/Collection.asp" --> <style type="text/css"> td { padding: 4px; } td.error { background: #F00F00; } td.warning { background: #FC0; } </style> <% Class UserModel Private m_Name Private m_Age Private m_Height Public Property Let Name(value) m_Name = value End Property Public Property Get Name() Name = m_Name End Property Public Property Let Age(value) m_Age = value End Property Public Property Get Age() Age = m_Age End Property Public Property Let Height(value) m_Height = value End Property Public Property Get Height() Height = m_Height End Property End Class Class NameValidation Private m_Name Public Function Init(name) m_Name = name End Function Public Function Validate() Dim validationObject If Len(m_Name) < 5 Then Set validationObject = New ValidationError Else Set validationObject = New ValidationSuccess End If validationObject.CellValue = m_Name Set Validate = validationObject End Function End Class Class AgeValidation Private m_Age Public Function Init(age) m_Age = age End Function Public Function Validate() Dim validationObject If m_Age < 18 Then Set validationObject = New ValidationError ElseIf m_Age = 18 Then Set validationObject = New ValidationWarning Else Set validationObject = New ValidationSuccess End If validationObject.CellValue = m_Age Set Validate = validationObject End Function End Class Class HeightValidation Private m_Height Public Function Init(height) m_Height = height End Function Public Function Validate() Dim validationObject If m_Height > 400 Then Set validationObject = New ValidationError ElseIf m_Height = 324 Then Set validationObject = New ValidationWarning Else Set validationObject = New ValidationSuccess End If validationObject.CellValue = m_Height Set Validate = validationObject End Function End Class Class ValidationError Private m_CSSClass Private m_CellValue Public Property Get CSSClass() CSSClass = "error" End Property Public Property Let CellValue(value) m_CellValue = value End Property Public Property Get CellValue() CellValue = m_CellValue End Property End Class Class ValidationWarning Private m_CSSClass Private m_CellValue Public Property Get CSSClass() CSSClass = "warning" End Property Public Property Let CellValue(value) m_CellValue = value End Property Public Property Get CellValue() CellValue = m_CellValue End Property End Class Class ValidationSuccess Private m_CSSClass Private m_CellValue Public Property Get CSSClass() CSSClass = "" End Property Public Property Let CellValue(value) m_CellValue = value End Property Public Property Get CellValue() CellValue = m_CellValue End Property End Class Class ModelValidator Public Function ValidateModel(model) Dim modelValidation : Set modelValidation = New CollectionClass ' Validate name Dim name : Set name = New NameValidation name.Init model.Name modelValidation.Add name ' Validate age Dim age : Set age = New AgeValidation age.Init model.Age modelValidation.Add age ' Validate height Dim height : Set height = New HeightValidation height.Init model.Height modelValidation.Add height Dim validatedProperties : Set validatedProperties = New CollectionClass Dim modelVal For Each modelVal In modelValidation.Items() validatedProperties.Add modelVal.Validate() Next Set ValidateModel = validatedProperties End Function End Class Dim modelCollection : Set modelCollection = New CollectionClass Dim user1 : Set user1 = New UserModel user1.Name = "Mike" user1.Age = 12 user1.Height = 32 modelCollection.Add user1 Dim user2 : Set user2 = New UserModel user2.Name = "Phil" user2.Age = 18 user2.Height = 432 modelCollection.Add user2 Dim user3 : Set user3 = New UserModel user3.Name = "Michele" user3.Age = 32 user3.Height = 324 modelCollection.Add user3 ' Validate all models in the collection Dim modelValue Dim validatedModels : Set validatedModels = New CollectionClass For Each modelValue In modelCollection.Items() Dim objModelValidator : Set objModelValidator = New ModelValidator validatedModels.Add objModelValidator.ValidateModel(modelValue) Next %> <table> <tr> <td>Name</td> <td>Age</td> <td>Height</td> </tr> <% Dim r, c For Each r In validatedModels.Items() %><tr><% For Each c In r.Items() %><td class="<%= c.CSSClass %>"><%= c.CellValue %></td><% Next %></tr><% Next %> </table> Thank you.

    Read the article

  • Testing Entity Framework applications, pt. 3: NDbUnit

    - by Thomas Weller
    This is the third of a three part series that deals with the issue of faking test data in the context of a legacy app that was built with Microsoft's Entity Framework (EF) on top of an MS SQL Server database – a scenario that can be found very often. Please read the first part for a description of the sample application, a discussion of some general aspects of unit testing in a database context, and of some more specific aspects of the here discussed EF/MSSQL combination. Lately, I wondered how you would ‘mock’ the data layer of a legacy application, when this data layer is made up of an MS Entity Framework (EF) model in combination with a MS SQL Server database. Originally, this question came up in the context of how you could enable higher-level integration tests (automated UI tests, to be exact) for a legacy application that uses this EF/MSSQL combo as its data store mechanism – a not so uncommon scenario. The question sparked my interest, and I decided to dive into it somewhat deeper. What I've found out is, in short, that it's not very easy and straightforward to do it – but it can be done. The two strategies that are best suited to fit the bill involve using either the (commercial) Typemock Isolator tool or the (free) NDbUnit framework. The use of Typemock was discussed in the previous post, this post now will present the NDbUnit approach... NDbUnit is an Apache 2.0-licensed open-source project, and like so many other Nxxx tools and frameworks, it is basically a C#/.NET port of the corresponding Java version (DbUnit namely). In short, it helps you in flexibly managing the state of a database in that it lets you easily perform basic operations (like e.g. Insert, Delete, Refresh, DeleteAll)  against your database and, most notably, lets you feed it with data from external xml files. Let's have a look at how things can be done with the help of this framework. Preparing the test data Compared to Typemock, using NDbUnit implies a totally different approach to meet our testing needs.  So the here described testing scenario requires an instance of an SQL Server database in operation, and it also means that the Entity Framework model that sits on top of this database is completely unaffected. First things first: For its interactions with the database, NDbUnit relies on a .NET Dataset xsd file. See Step 1 of their Quick Start Guide for a description of how to create one. With this prerequisite in place then, the test fixture's setup code could look something like this: [TestFixture, TestsOn(typeof(PersonRepository))] [Metadata("NDbUnit Quickstart URL",           "http://code.google.com/p/ndbunit/wiki/QuickStartGuide")] [Description("Uses the NDbUnit library to provide test data to a local database.")] public class PersonRepositoryFixture {     #region Constants     private const string XmlSchema = @"..\..\TestData\School.xsd";     #endregion // Constants     #region Fields     private SchoolEntities _schoolContext;     private PersonRepository _personRepository;     private INDbUnitTest _database;     #endregion // Fields     #region Setup/TearDown     [FixtureSetUp]     public void FixtureSetUp()     {         var connectionString = ConfigurationManager.ConnectionStrings["School_Test"].ConnectionString;         _database = new SqlDbUnitTest(connectionString);         _database.ReadXmlSchema(XmlSchema);         var entityConnectionStringBuilder = new EntityConnectionStringBuilder         {             Metadata = "res://*/School.csdl|res://*/School.ssdl|res://*/School.msl",             Provider = "System.Data.SqlClient",             ProviderConnectionString = connectionString         };         _schoolContext = new SchoolEntities(entityConnectionStringBuilder.ConnectionString);         _personRepository = new PersonRepository(this._schoolContext);     }     [FixtureTearDown]     public void FixtureTearDown()     {         _database.PerformDbOperation(DbOperationFlag.DeleteAll);         _schoolContext.Dispose();     }     ...  As you can see, there is slightly more fixture setup code involved if your tests are using NDbUnit to provide the test data: Because we're dealing with a physical database instance here, we first need to pick up the test-specific connection string from the test assemblies' App.config, then initialize an NDbUnit helper object with this connection along with the provided xsd file, and also set up the SchoolEntities and the PersonRepository instances accordingly. The _database field (an instance of the INdUnitTest interface) will be our single access point to the underlying database: We use it to perform all the required operations against the data store. To have a flexible mechanism to easily insert data into the database, we can write a helper method like this: private void InsertTestData(params string[] dataFileNames) {     _database.PerformDbOperation(DbOperationFlag.DeleteAll);     if (dataFileNames == null)     {         return;     }     try     {         foreach (string fileName in dataFileNames)         {             if (!File.Exists(fileName))             {                 throw new FileNotFoundException(Path.GetFullPath(fileName));             }             _database.ReadXml(fileName);             _database.PerformDbOperation(DbOperationFlag.InsertIdentity);         }     }     catch     {         _database.PerformDbOperation(DbOperationFlag.DeleteAll);         throw;     } } This lets us easily insert test data from xml files, in any number and in a  controlled order (which is important because we eventually must fulfill referential constraints, or we must account for some other stuff that imposes a specific ordering on data insertion). Again, as with Typemock, I won't go into API details here. - Unfortunately, there isn't too much documentation for NDbUnit anyway, other than the already mentioned Quick Start Guide (and the source code itself, of course) - a not so uncommon problem with smaller Open Source Projects. Last not least, we need to provide the required test data in xml form. A snippet for data from the People table might look like this, for example: <?xml version="1.0" encoding="utf-8" ?> <School xmlns="http://tempuri.org/School.xsd">   <Person>     <PersonID>1</PersonID>     <LastName>Abercrombie</LastName>     <FirstName>Kim</FirstName>     <HireDate>1995-03-11T00:00:00</HireDate>   </Person>   <Person>     <PersonID>2</PersonID>     <LastName>Barzdukas</LastName>     <FirstName>Gytis</FirstName>     <EnrollmentDate>2005-09-01T00:00:00</EnrollmentDate>   </Person>   <Person>     ... You can also have data from various tables in one single xml file, if that's appropriate for you (but beware of the already mentioned ordering issues). It's true that your test assembly may end up with dozens of such xml files, each containing quite a big amount of text data. But because the files are of very low complexity, and with the help of a little bit of Copy/Paste and Excel magic, this appears to be well manageable. Executing some basic tests Here are some of the possible tests that can be written with the above preparations in place: private const string People = @"..\..\TestData\School.People.xml"; ... [Test, MultipleAsserts, TestsOn("PersonRepository.GetNameList")] public void GetNameList_ListOrdering_ReturnsTheExpectedFullNames() {     InsertTestData(People);     List<string> names =         _personRepository.GetNameList(NameOrdering.List);     Assert.Count(34, names);     Assert.AreEqual("Abercrombie, Kim", names.First());     Assert.AreEqual("Zheng, Roger", names.Last()); } [Test, MultipleAsserts, TestsOn("PersonRepository.GetNameList")] [DependsOn("RemovePerson_CalledOnce_DecreasesCountByOne")] public void GetNameList_NormalOrdering_ReturnsTheExpectedFullNames() {     InsertTestData(People);     List<string> names =         _personRepository.GetNameList(NameOrdering.Normal);     Assert.Count(34, names);     Assert.AreEqual("Alexandra Walker", names.First());     Assert.AreEqual("Yan Li", names.Last()); } [Test, TestsOn("PersonRepository.AddPerson")] public void AddPerson_CalledOnce_IncreasesCountByOne() {     InsertTestData(People);     int count = _personRepository.Count;     _personRepository.AddPerson(new Person { FirstName = "Thomas", LastName = "Weller" });     Assert.AreEqual(count + 1, _personRepository.Count); } [Test, TestsOn("PersonRepository.RemovePerson")] public void RemovePerson_CalledOnce_DecreasesCountByOne() {     InsertTestData(People);     int count = _personRepository.Count;     _personRepository.RemovePerson(new Person { PersonID = 33 });     Assert.AreEqual(count - 1, _personRepository.Count); } Not much difference here compared to the corresponding Typemock versions, except that we had to do a bit more preparational work (and also it was harder to get the required knowledge). But this picture changes quite dramatically if we look at some more demanding test cases: Ok, and what if things are becoming somewhat more complex? Tests like the above ones represent the 'easy' scenarios. They may account for the biggest portion of real-world use cases of the application, and they are important to make sure that it is generally sound. But usually, all these nasty little bugs originate from the more complex parts of our code, or they occur when something goes wrong. So, for a testing strategy to be of real practical use, it is especially important to see how easy or difficult it is to mimick a scenario which represents a more complex or exceptional case. The following test, for example, deals with the case that there is some sort of invalid input from the caller: [Test, MultipleAsserts, TestsOn("PersonRepository.GetCourseMembers")] [Row(null, typeof(ArgumentNullException))] [Row("", typeof(ArgumentException))] [Row("NotExistingCourse", typeof(ArgumentException))] public void GetCourseMembers_WithGivenVariousInvalidValues_Throws(string courseTitle, Type expectedInnerExceptionType) {     var exception = Assert.Throws<RepositoryException>(() =>                                 _personRepository.GetCourseMembers(courseTitle));     Assert.IsInstanceOfType(expectedInnerExceptionType, exception.InnerException); } Apparently, this test doesn't need an 'Arrange' part at all (see here for the same test with the Typemock tool). It acts just like any other client code, and all the required business logic comes from the database itself. This doesn't always necessarily mean that there is less complexity, but only that the complexity happens in a different part of your test resources (in the xml files namely, where you sometimes have to spend a lot of effort for carefully preparing the required test data). Another example, which relies on an underlying 1-n relationship, might be this: [Test, MultipleAsserts, TestsOn("PersonRepository.GetCourseMembers")] public void GetCourseMembers_WhenGivenAnExistingCourse_ReturnsListOfStudents() {     InsertTestData(People, Course, Department, StudentGrade);     List<Person> persons = _personRepository.GetCourseMembers("Macroeconomics");     Assert.Count(4, persons);     Assert.ForAll(         persons,         @p => new[] { 10, 11, 12, 14 }.Contains(@p.PersonID),         "Person has none of the expected IDs."); } If you compare this test to its corresponding Typemock version, you immediately see that the test itself is much simpler, easier to read, and thus much more intention-revealing. The complexity here lies hidden behind the call to the InsertTestData() helper method and the content of the used xml files with the test data. And also note that you might have to provide additional data which are not even directly relevant to your test, but are required only to fulfill some integrity needs of the underlying database. Conclusion The first thing to notice when comparing the NDbUnit approach to its Typemock counterpart obviously deals with performance: Of course, NDbUnit is much slower than Typemock. Technically,  it doesn't even make sense to compare the two tools. But practically, it may well play a role and could or could not be an issue, depending on how much tests you have of this kind, how often you run them, and what role they play in your development cycle. Also, because the dataset from the required xsd file must fully match the database schema (even in parts that otherwise wouldn't be relevant to you), it can be quite cumbersome to be in a team where different people are working with the database in parallel. My personal experience is – as already said in the first part – that Typemock gives you a better development experience in a 'dynamic' scenario (when you're working in some kind of TDD-style, you're oftentimes executing the tests from your dev box, and your database schema changes frequently), whereas the NDbUnit approach is a good and solid solution in more 'static' development scenarios (when you need to execute the tests less frequently or only on a separate build server, and/or the underlying database schema can be kept relatively stable), for example some variations of higher-level integration or User-Acceptance tests. But in any case, opening Entity Framework based applications for testing requires a fair amount of resources, planning, and preparational work – it's definitely not the kind of stuff that you would call 'easy to test'. Hopefully, future versions of EF will take testing concerns into account. Otherwise, I don't see too much of a future for the framework in the long run, even though it's quite popular at the moment... The sample solution A sample solution (VS 2010) with the code from this article series is available via my Bitbucket account from here (Bitbucket is a hosting site for Mercurial repositories. The repositories may also be accessed with the Git and Subversion SCMs - consult the documentation for details. In addition, it is possible to download the solution simply as a zipped archive – via the 'get source' button on the very right.). The solution contains some more tests against the PersonRepository class, which are not shown here. Also, it contains database scripts to create and fill the School sample database. To compile and run, the solution expects the Gallio/MbUnit framework to be installed (which is free and can be downloaded from here), the NDbUnit framework (which is also free and can be downloaded from here), and the Typemock Isolator tool (a fully functional 30day-trial is available here). Moreover, you will need an instance of the Microsoft SQL Server DBMS, and you will have to adapt the connection strings in the test projects App.config files accordingly.

    Read the article

  • mod_rewrite apache

    - by Peter
    is there any way to hide redirected url, here is what I think: RewriteEngine On RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^(.*)$ http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://%{HTTP_HOST}%{REQUEST_URI}&force So the long redirected url http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://%{HTTP_HOST}%{REQUEST_URI} to something shorter like /mintedomain.com/track/ It is possible? Adrian edit: Andrew: This is a stats software Mint (haveamint.com) with File Download tracker plugin. The File Download tracker works in this way: in .htaccess every file (zip, rar, txt,...) is redirected to the tracker.php file (because the stats): http://mydomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://%{HTTP_HOST}%{REQUEST_URI} So the redirected url look like this for a zip file: http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://mydomain/downloads/apple.zip This redirected URL is very long and ugly. The best for me would be to redirect this redirected URL to something shorter URL: example: http://mydomain.com/track/downloads/apple.zip.. So the http://mydomain.com/track would be the http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php

    Read the article

  • Mod_rewrite shortening url .htaccess

    - by Peter
    is there any way to hide redirected url, here is what I think: RewriteEngine On RewriteCond %{REQUEST_FILENAME} -f RewriteRule ^(.*)$ http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://%{HTTP_HOST}%{REQUEST_URI}&force So the long redirected url http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://%{HTTP_HOST}%{REQUEST_URI} to something shorter like /mintedomain.com/track/ It is possible? Adrian edit: Andrew: This is a stats software Mint (haveamint.com) with File Download tracker plugin. The File Download tracker works in this way: in .htaccess every file (zip, rar, txt,...) is redirected to the tracker.php file (because the stats): http://mydomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://%{HTTP_HOST}%{REQUEST_URI} So the redirected url look like this for a zip file: http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php?url=http://mydomain/downloads/apple.zip This redirected URL is very long and ugly. The best for me would be to redirect this redirected URL to something shorter URL: example: http://mydomain.com/track/downloads/apple.zip.. So the http://mydomain.com/track would be the http://minteddomain.com/mint/pepper/tillkruess/downloads/tracker.php

    Read the article

  • regular expression and escaping

    - by pstanton
    Sorry if this has been asked, my search brought up many off topic posts. I'm trying to convert wildcards from a user defined search string (wildcard is "*") to postgresql like wildcard "%". I'd like to handle escaping so that "%" => "\%" and "\*" => "*" I know i could replace \* with something else prior to replacing * and then swap it back, but i'd prefer not to and instead only convert * using a pattern that selects it when not proceeded by \. String convertWildcard(String like) { like = like.replaceAll("%", "\\%"); like = like.replaceAll("\\*", "%"); return like; } Assert.assertEquals("%", convertWildcard("*")); Assert.assertEquals("\%", convertWildcard("%")); Assert.assertEquals("*", convertWildcard("\*")); // FAIL Assert.assertEquals("a%b", convertWildcard("a*b")); Assert.assertEquals("a\%b", convertWildcard("a%b")); Assert.assertEquals("a*b", convertWildcard("a\*b")); // FAIL ideas welcome.

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >