Search Results

Search found 299 results on 12 pages for 'rhino mocks 3 5'.

Page 5/12 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Scripting for JAVA - a problem to solve

    - by Parhs
    Hello.. I had no luck to find a good way to achieve the following: suppose i let the user to write a condition using javascript INS5 || ASTO.valueBetween(10,210) ... etc.... I tried to find a way to get the variables name...from JAVA... Rhino library didnt help a lot... However i found that handling exceptions i could get all the identifiers! Everything is great but one little problem..... How teh heck i can replace these identifiers with the numeric id of each var ? eg INS to be _234 ASTO to be _331 ? I want to to this replace because the name may change... I could do it using a replace but i know that this isnt easy because... 1) replacing _23 with MPLAH may replace also _234...(this could be fixed with regexp somehow..) 2)what if _23 is in a comment section ? rare to happen but possible /* _23 fdsafd ktl */ it should be replaced... 3)what if is a name of a function ??? _32() {} rare but shouldnt be replaced 4) what if it is enclosed in "" or ''??? And i am sure that there should me a lot more cases..... any ideas ? thank yoyu for your time

    Read the article

  • User preferences using SQL and JavaScript

    - by Shyam
    Hi, I am using Server Side JavaScript - yes, I am actually using Server Side JavaScript. To complexify things even more, I use Oracle as a backend database (10g). With some crazy XSLT and mutant-like HTML generation, I can build really fancy web forms - yes, I am aware of Rails and other likewise frameworks and I choose the path of horror instead. I have no JQuery or other fancy framework at my disposal, just plain ol' JavaScript that should be supported by the underlying engine called Mozilla Rhino. Yes, it is insane and I love it. So, I have a bunch of tables at my disposal and some of them are filled with associative keys that link to values. As I am a people pleaser, I want to add some nifty user-preference driven solutions. My users have all an unique user_id and this user_id is available during the entire session. My initial idea is to have a user preference table, where I have "three" columns: user_id, feature and pref_string. Using a delimiter, such as : or - (haven't thought about a suitable one yet), I could like store a bunch of preferences as a list and store its elements inside an array using the .split-method (similar like the PHP-explode function). The feature column could be like the table name or some identifier for the "feature" i want to link preferences too. I hate hardcoding objects, especially as I want to be able to back these up and reuse this functionality application-wide. Of course I would love better ideas, just keep in mind I cannot just add a library that easily. These preferences could be like "joined" to the table, so I can query it and use its values. I hope it doesn't sounds too complex, because well.. its basically something really simple I need. Thanks!

    Read the article

  • JavaScript window object element properties

    - by Timothy
    A coworker showed me the following code and asked me why it worked. <span id="myspan">Do you like my hat?</span> <script type="text/javascript"> var spanElement = document.getElementById("myspan"); alert("Here I am! " + spanElement.innerHTML + "\n" + myspan.innerHTML); </script> I explained that a property is attached to the window object with the name of the element's id when the browser parses the document which then contains a reference to the appropriate dom node. It's sort of as if window.myspan = document.getElementById("myspan") is called behind the scenes as the page is being rendered. The ensuing discussion we had raised a few of questions: The window object and most of the DOM are not part of the official JavaScript/ECMA standards, but is the above behavior documented in any other official literature, perhaps browser-related? The above works in a browser (at least the main contenders) because there is a window object, but fails in something like rhino. Is writing code that relys on this considered bad practice because it makes too many assumptions about the execution environment? Are there any browsers in which the above would fail, or is this considered standard behavior across the board? Does anyone here know the answers to those questions and would be willing to enlighten me? I tried a quick internet search, but I admit I'm not sure how to even properly phrase the query. Pointers to references and documentation are welcome.

    Read the article

  • How to invoke WPF Dispatcher in Nunit?

    - by Reporting Avatar
    I want to test an application which renders a text block with a data field value. I would like to get the actual width and actual height, once the rendering completes. Everything works fine. The problem came first, when I tried to test the application. I'm unable to invoke the dispatcher from the test project. Following is the code. this.Loaded += (s, e) => { TextBlock textBlock1 = new TextBlock(); //// Text block value is assigned from data base field. textBlock1.Text = strValueFromDataBaseField; //// Setting the wrap behavior. textBlock1.TextWrapping = TextWrapping.WrapWithOverflow; //// Adding the text block to the layout canvas. this.layoutCanvas.Children.Add(textBlock1); this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { //// After rendering the text block with the data base field value. Measuring the actual width and height. this.TextBlockActualWidth = textBlock1.ActualWidth; this.TextBlockActualHeight = textBlock1.ActualHeight; //// Other calculations based on the actual widht and actual height. } )); }; I've just started using the NUnit. So, please help me. Thanks

    Read the article

  • RhinoMocks AAA Syntax

    - by Bill Campbell
    Hi, I've spent a good part of the day trying to figure out why a simple RhinoMocks test doesn't return the value I'm setting in the return. I'm sure that I'm just missing something really simple but I can't figure it out. Here's my test: [TestMethod] public void CopyvRAFiles_ShouldCallCopyvRAFiles_ShouldReturnTrue2() { FileInfo fi = new FileInfo(@"c:\Myprogram.txt"); FileInfo[] myFileInfo = new FileInfo[2]; myFileInfo[0] = fi; myFileInfo[1] = fi; var mockSystemIO = MockRepository.GenerateMock<ISystemIO>(); mockSystemIO.Stub(x => x.GetFilesForCopy("c:")).Return(myFileInfo); mockSystemIO.Expect(y => y.FileCopyDateCheck(@"c:\Myprogram.txt", @"c:\Myprogram.txt")).Return("Test"); CopyFiles copy = new CopyFiles(mockSystemIO); List<string> retValue = copy.CopyvRAFiles("c:", "c:", new AdminWindowViewModel(vRASharedData)); mockSystemIO.VerifyAllExpectations(); } I have an interface for my SystemIO class I'm passing in a mock for that to my CopyFiles class. I'm setting an expectation on my FileCopyDatCheck method and saying that it should Return("Test"). When I step through the code, it returns a null insteaed. Any ideas what I'm missing here? Here's my CopyFiles class Method: public List<string> CopyvRAFiles(string currentDirectoryPath, string destPath, AdminWindowViewModel adminWindowViewModel) { string fileCopied; List<string> filesCopied = new List<string>(); try { sysIO.CreateDirectoryIfNotExist(destPath); FileInfo[] files = sysIO.GetFilesForCopy(currentDirectoryPath); if (files != null) { foreach (FileInfo file in files) { fileCopied = sysIO.FileCopyDateCheck(file.FullName, destPath + file.Name); filesCopied.Add(fileCopied); } } //adminWindowViewModel.CheckFilesThatRequireSystemUpdate(filesCopied); return filesCopied; } catch (Exception ex) { ExceptionPolicy.HandleException(ex, "vRAClientPolicy"); Console.WriteLine("{0} Exception caught.", ex); ShowErrorMessageDialog(ex); return null; } } I would think that "fileCopied" would have the Return value set by the Expect. The GetFilesForCopy returns the two files in myFileInfo. Please Help. :) thanks in advance!

    Read the article

  • How to write a test for accounts controller for forms authenticate

    - by Anil Ali
    Trying to figure out how to adequately test my accounts controller. I am having problem testing the successful logon scenario. Issue 1) Am I missing any other tests.(I am testing the model validation attributes separately) Issue 2) Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() and Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() test are not passing. I have narrowed it down to the line where i am calling _membership.validateuser(). Even though during my mock setup of the service i am stating that i want to return true whenever validateuser is called, the method call returns false. Here is what I have gotten so far AccountController.cs [HandleError] public class AccountController : Controller { private IMembershipService _membershipService; public AccountController() : this(null) { } public AccountController(IMembershipService membershipService) { _membershipService = membershipService ?? new AccountMembershipService(); } [HttpGet] public ActionResult LogOn() { return View(); } [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (_membershipService.ValidateUser(model.UserName,model.Password)) { if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Overview"); } ModelState.AddModelError("*", "The user name or password provided is incorrect."); } return View(model); } } AccountServices.cs public interface IMembershipService { bool ValidateUser(string userName, string password); } public class AccountMembershipService : IMembershipService { public bool ValidateUser(string userName, string password) { throw new System.NotImplementedException(); } } AccountControllerFacts.cs public class AccountControllerFacts { public static AccountController GetAccountControllerForLogonSuccess() { var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>(); var controller = new AccountController(membershipServiceStub); membershipServiceStub .Stub(x => x.ValidateUser("someuser", "somepass")) .Return(true); return controller; } public static AccountController GetAccountControllerForLogonFailure() { var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>(); var controller = new AccountController(membershipServiceStub); membershipServiceStub .Stub(x => x.ValidateUser("someuser", "somepass")) .Return(false); return controller; } public class LogOn { [Fact] public void Get_ReturnsViewResultWithDefaultViewName() { // Arrange var controller = GetAccountControllerForLogonSuccess(); // Act var result = controller.LogOn(); // Assert Assert.IsType<ViewResult>(result); Assert.Empty(((ViewResult)result).ViewName); } [Fact] public void Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() { // Arrange var controller = GetAccountControllerForLogonSuccess(); var user = new LogOnModel(); // Act var result = controller.LogOn(user, null); var redirectresult = (RedirectToRouteResult) result; // Assert Assert.IsType<RedirectToRouteResult>(result); Assert.Equal("Overview", redirectresult.RouteValues["controller"]); Assert.Equal("Index", redirectresult.RouteValues["action"]); } [Fact] public void Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() { // Arrange var controller = GetAccountControllerForLogonSuccess(); var user = new LogOnModel(); // Act var result = controller.LogOn(user, "someurl"); var redirectResult = (RedirectResult) result; // Assert Assert.IsType<RedirectResult>(result); Assert.Equal("someurl", redirectResult.Url); } [Fact] public void Put_ReturnsViewIfInvalidModelState() { // Arrange var controller = GetAccountControllerForLogonFailure(); var user = new LogOnModel(); controller.ModelState.AddModelError("*","Invalid model state."); // Act var result = controller.LogOn(user, "someurl"); var viewResult = (ViewResult) result; // Assert Assert.IsType<ViewResult>(result); Assert.Empty(viewResult.ViewName); Assert.Same(user,viewResult.ViewData.Model); } [Fact] public void Put_ReturnsViewIfLogonFailed() { // Arrange var controller = GetAccountControllerForLogonFailure(); var user = new LogOnModel(); // Act var result = controller.LogOn(user, "someurl"); var viewResult = (ViewResult) result; // Assert Assert.IsType<ViewResult>(result); Assert.Empty(viewResult.ViewName); Assert.Same(user,viewResult.ViewData.Model); Assert.Equal(false,viewResult.ViewData.ModelState.IsValid); } } }

    Read the article

  • When using a mocking framework and MSPEC where do you set your stubs

    - by Kev Hunter
    I am relatively new to using MSpec and as I write more and more tests it becomes obvious to reduce duplication you often have to use a base class for your setup as per Rob Conery's article I am happy with using the AssertWasCalled method to verify my expectations, but where do you set up a stub's return value, I find it useful to set the context in the base class injecting my dependencies but that (I think) means that I need to set my stubs up in the Because delegate which just feels wrong. Is there a better approach I am missing?

    Read the article

  • How to use the AAA syntax to do an AssertWasCalled but ignore arguments

    - by Toran Billups
    I'm using the new AAA syntax and wanted to know the syntax to do the below and have the mock ignore the agruments. mockAccount.AssertWasCalled(account = account.SetPassword("dsfdslkj")); I think the below is how I would do this with the record/ replay model but I wanted to see if this could be done with AAA using 3.6 mockAccount.Expect(account = account.SetPassword("sdfdsf")).IgnoreArguments(); mockAccount.VerifyAllExpectations(); Thank you in advance

    Read the article

  • Mocking View with RhinoMocks

    - by blu
    We are using MVP (Supervising Controller) for ASP.NET WebForms with 3.5 SP1. What is the preferred way to check the value of a view property that only has the a set operation with RhinoMocks? Here is what we have so far: var service = MockRepository.GenerateStub<IFooService>(); // stub some data for the method used in OnLoad in the presenter var view = MockRepository.GenerateMock<IFooView>(); var presenter = new FooPresenter(view, service); view.Raise(v => v.Load += null, this, EventArgs.Empty); Assert.IsTrue(view.Bars.Count == 10); // there is no get on Bars Should we use Expects or another way, any input would be great. Thanks Update based on Darin Dimitrov's reply. var bars = new List<Bar>() { new Bar() { BarId = 1 } }; var fooService = MockRepository.GenerateStub<IFooService>(); // this is called in OnLoad in the Presenter fooService.Stub(x => x.GetBars()).Return(bars); var view = MockRepository.GenerateMock<IFooView>(); var presenter = new FooPresenter(view, fooService); view.Raise(v => v.Load += null, this, EventArgs.Empty); view.AssertWasCalled(x => x.Bars = bars); // this does not pass This doesn't work. Should I be testing it this way or is there a better way?

    Read the article

  • Rhinomocks DynamicMock question

    - by epitka
    My dynamic mock behaves as Parial mock, meaning it executes the actual code when called. Here are the ways I tried it var mockProposal = _mockRepository.DynamicMock<BidProposal>(); SetupResult.For(mockProposal.CreateMarketingPlan(null, null, null)).IgnoreArguments().Repeat.Once().Return( copyPlan); //Expect.Call(mockProposal.CreateMarketingPlan(null, null, null)).IgnoreArguments().Repeat.Once().Return( // copyPlan); // mockProposal.Expect(x => x.CreateMarketingPlan(null, null, null)).IgnoreArguments().Return(copyPlan).Repeat.Once(); Instead of just returning what I expect it runs the code in the method CreateMarketingPlan Here is the error: System.NullReferenceException: Object reference not set to an instance of an object. at Policy.Entities.MarketingPlan.SetMarketingPlanName(MarketingPlanDescription description) in MarketingPlan.cs: line 76 at Policy.Entities.MarketingPlan.set_MarketingPlanDescription(MarketingPlanDescription value) in MarketingPlan.cs: line 91 at Policy.Entities.MarketingPlan.Create(PPOBenefits ppoBenefits, MarketingPlanDescription marketingPlanDescription, MarketingPlanType marketingPlanType) in MarketingPlan.cs: line 23 at Policy.Entities.BidProposal.CreateMarketingPlan(PPOBenefits ppoBenefits, MarketingPlanDescription marketingPlanDescription, MarketingPlanType marketingPlanType) in BidProposal.cs: line 449 at Tests.Policy.Services.MarketingPlanCopyServiceTests.can_copy_MarketingPlan_with_all_options() in MarketingPlanCopyServiceTests.cs: line 32 Update: I figured out what it was. Method was not "virtual" so it could not be mocked because non-virtual methods cannot be proxied.

    Read the article

  • Mock dll methods for unit tests

    - by sanjeev40084
    I am trying to write a unit test for a method, which has a call to method from dll. Is there anyway i can mock the dll methods so that i can unit test? public string GetName(dllobject, int id) { var eligibileEmp = dllobject.GetEligibleEmp(id); <---------trying to mock this method if(eligibleEmp.Equals(empValue) { .......... } }

    Read the article

  • Error using MVCContrib TestHelper

    - by Brian McCord
    While trying to implement the second answer to a previous question, I am receiving an error. I have implemented the methods just as the post shows, and the first three work properly. The fourth one (HomeController_Delete_Action_Handler_Should_Redirect_If_Model_Successfully_Delete) gives this error: Could not find a parameter named 'controller' in the result's Values collection. If I change the code to: actual .AssertActionRedirect() .ToAction("Index"); it works properly, but I don't like the "magic string" in there and prefer to use the lambda method that the other poster used. My controller method looks like this: [HttpPost] public ActionResult Delete(State model) { try { if( model == null ) { return View( model ); } _stateService.Delete( model ); return RedirectToAction("Index"); } catch { return View( model ); } } What am I doing wrong?

    Read the article

  • Can someone please clarify my understanding of a mock's Verify concept?

    - by Pure.Krome
    Hi folks, I'm playing around with some unit tests and mocking. I'm trying to verify that some code, in my method, has been called. I don't think I understand the Verify part of mocking right, because I can only ever Verify main method .. which is silly because that is what I Act upon anyways. I'm trying to test that my logic is working - so I thought I use Verify to see that certain steps in the method have been reached and enacted upon. Lets use this example to highlight what I am doing wrong. public interface IAuthenticationService { bool Authenticate(string username, string password); SignOut(); } public class FormsAuthenticationService : IAuthenticationService { public bool Authenticate(string username, string password) { var user = _userService.FindSingle(x => x.UserName == username); if (user == null) return false; // Hash their password. var hashedPassword = EncodePassword(password, user.PasswordSalt); if (!hashedPassword.Equals(password, StringComparison.InvariantCulture)) return false; FormsAuthentication.SetAuthCookie(userName, true); return true; } } So now, I wish to verify that EncodePassword was called. FormsAuthentication.SetAuthCookie(..) was called. Now, I don't care about the implimentations of both of those. And more importantly, I do not want to test those methods. That has to be handled elsewhere. What I though I should do is Verify that those methods were called and .. if possible ... an expected result was returned. Is this the correct understanding of what 'Verify' means with mocking? If so, can someone show me how I can do this. Preferable with moq but i'm happy with anything. Cheers :)

    Read the article

  • What is the purpose of unit testing an interface repository

    - by ahsteele
    I am unit testing an ICustomerRepository interface used for retrieving objects of type Customer. As a unit test what value am I gaining by testing the ICustomerRepository in this manner? Under what conditions would the below test fail? For tests of this nature is it advisable to do tests that I know should fail? i.e. look for id 4 when I know I've only placed 5 in the repository I am probably missing something obvious but it seems the integration tests of the class that implements ICustomerRepository will be of more value. [TestClass] public class CustomerTests : TestClassBase { private Customer SetUpCustomerForRepository() { return new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" }, new Login { LoginCustId = 5, LoginName = "tdude2" } } }; } [TestMethod] public void CanGetCustomerById() { // arrange var customer = SetUpCustomerForRepository(); var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetById(5)).Return(customer); // assert Assert.AreEqual(customer, repository.GetById(5)); } } Test Base Class public class TestClassBase { protected T Stub<T>() where T : class { return MockRepository.GenerateStub<T>(); } } ICustomerRepository and IRepository public interface ICustomerRepository : IRepository<Customer> { IList<Customer> FindCustomers(string q); Customer GetCustomerByDifID(string difId); Customer GetCustomerByLogin(string loginName); } public interface IRepository<T> { void Save(T entity); void Save(List<T> entity); bool Save(T entity, out string message); void Delete(T entity); T GetById(int id); ICollection<T> FindAll(); }

    Read the article

  • Argument constraints in RhinoMock methods

    - by Khash
    I am mocking a repository that should have 1 entity in it for the test scenario. The repository has to return this entity based on a known id and return nothing when other ids are passed in. I have tried doing something like this: _myRepository.Expect(item => item.Find(knownId)).Return(knownEntity); _myRepository.Expect(item => item.Find(Arg<Guid>.Is.Anything)).Return(null); It seems however the second line is overriding the first and the repository always returns null. I don't want to mock all the different possible IDs asked (they could go up to hundreds) when the test scenario is only concerned with the value of one Id.

    Read the article

  • Why Create Mock Objects?

    - by Chris
    During a recent interview I was asked why one would want to create mock objects. My answer went something like, "Take a database--if you're writing test code, you may not want that test hooked up live to the production database where actual operations will be performed." Judging by response, my answer clearly was not what the interviewer was looking for. What's a better answer?

    Read the article

  • Fancy box and youtube video problems

    - by shinjuo
    I have some fancy box photos and a youtube video, but when the fancy box picture opens the youtube video sits in front of it? Any ideas? Here is a snippet of my code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> <!-- var newwindow; function newWindow(url) { newwindow=window.open(url,'name','height=600,width=625'); if (window.focus) {newwindow.focus()} } // --> </script> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>onco Construction and Supply - Rhino Shield</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="fancybox/jquery.mousewheel-3.0.2.pack.js"></script> <script type="text/javascript" src="fancybox/jquery.fancybox-1.3.1.js"></script> <link rel="stylesheet" type="text/css" href="fancybox/jquery.fancybox-1.3.1.css" media="screen" /> <link rel="stylesheet" type="text/css" href="../style3.css" media="screen" /> <script type="text/javascript"> $(document).ready(function() { $("a[rel=example_group]").fancybox({ 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'titlePosition' : 'over', 'titleFormat' : function(title, currentArray, currentIndex, currentOpts) { return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>'; } }); }); </script> <style type="text/css"> .commercial { position: absolute; left:205px; top:1175px; width:327px; height:auto; } .pictures { position: absolute; left: 50px; top: 1090px; width: 750px; height: auto; text-align: center; } </style> </head> <body> <div class="pictures"> <a rel="example_group" href="images/rhino/1.jpg"> <img src="images/rhino/small/1.jpg" alt=""/></a> <a rel="example_group" href="images/rhino/2.jpg"> <img src="images/rhino/small/2.jpg" alt=""/></a> <a rel="example_group" href="images/rhino/3.jpg"> <img src="images/rhino/small/3.jpg" alt=""/></a> <a rel="example_group" href="images/rhino/4.jpg"> <img src="images/rhino/small/4.jpg" alt=""/></a> <a rel="example_group" href="images/rhino/5.jpg"> <img src="images/rhino/small/5.jpg" alt=""/></a> <a rel="example_group" href="images/rhino/6.jpg"> <img src="images/rhino/small/6.jpg" alt=""/></a> </div> <div class="commercial"> <object width="445" height="364"><param name="movie" value="http://www.youtube.com/v/Mw3gLivJkg0&hl=en_US&fs=1&rel=0&color1=0x2b405b&color2=0x6b8ab6&border=1"></param> <param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="http://www.youtube.com/v/Mw3gLivJkg0&hl=en_US&fs=1&rel=0&color1=0x2b405b&color2=0x6b8ab6&border=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="445" height="364"> </embed> </object> </div> </body> </html>

    Read the article

  • Binding a Java Integer to JavaScriptEngine doesn't work

    - by rplantiko
    To see how binding Java objects to symbols in a dynamic language works, I wrote the following spike test, binding a java.lang.Integer to the symbol i to be changed in JavaScript: @Test public void bindToLocalVariable() throws ScriptException { javax.script.ScriptEngineManager sem = new javax.script.ScriptEngineManager(); javax.script.ScriptEngine engine = sem.getEngineByName("JavaScript"); Integer i = new Integer(17); engine.put( "i", i ); engine.eval( "i++;" ); // Now execute JavaScript assertEquals( 18, i.intValue() ); } Unfortunately, I get a failure. java.lang.AssertionError: expected:<18> but was:<17> JavaScript knows the symbol i (otherwise it would have thrown a ScriptException which is not the case), but the increment operation i++ is not performed on the original Integer object. Any explanations?

    Read the article

  • Fix internal links in JS

    - by FB55
    I just created a script which extracts the article out of a webpage via server-side JS. (If your interested: it's used for http://pipes.yahoo.com/fb55/expandr .) I just got a little problem with internal links. Some pages include links like: /subfolder/subpage.html What I would need to do is fixing them and setting there root, like this: protocol://secondlevel.firstlevel/subfolder/subpage.html I'm using E4X for processing the page. I don't want to show my current creepy try, it's buggy and slow. Does anybody have a solution for me?

    Read the article

  • Using javax.script or Rhino to run javascript in Java with browser context (e.g. envjs)?

    - by Shane
    I am trying to run Protovis javascript from a Java program using javax.script: ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); engine.eval(new java.io.FileReader("protovis-d3.1.js")); In order to run this, the JavaScript engine needs to have all the context of a web browser. The best option for this seems to be envjs. Unfortunately it seems that the version of Rhino included in the JVM isn't up to date and doesn't include everything that's necessary for envjs. Has anyone had any success working with a browser context from javax.script, or am I missing something? This is related to this question: "Can I create a ‘window’ object for javascript running in the Java6 Rhino Script Engine".

    Read the article

  • Include Method Extension for IObjectSet What about the mocks?

    Eager loading with Entity Framework depends on the special ObjectQuery.Include method. We’ve had that from Day 1 (first version of ef). Now we use ObjectSets in EF4 which inherit from ObjectQuery (thereby inheriting Include) and also implement IObjectSet. IObjectSet allows us to break the queries apart from ObjectQuery and ObjectContext so we can write persistent ignorant, testable code. But IObjectSet doesn’t come with the Include method and you have to create an extension method to...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Using mocks to set up object even if you will not be mocking any behavior or verifying any interaction with it?

    - by smp7d
    When building a unit test, is it appropriate to use a mocking tool to assist you in setting up an object even if you will not be mocking any behavior or verifying any interaction with that object? Here is a simple example in pseudo-code: //an object we actually want to mock Object someMockedObject = Mock(Object.class); EqualityChecker checker = new EqualityChecker(someMockedObject); //an object we are mocking only to avoid figuring out how to instantiate or //tying ourselves to some constructor that may be removed in the future ComplicatedObject someObjectThatIsHardToInstantiate = Mock(ComplicatedObject.class); //set the expectation on the mock When(someMockedObject).equals(someObjectThatIsHardToInstantiate).return(false); Assert(equalityChecker.check(someObjectThatIsHardToInstantiate)).isFalse(); //verify that the mock was interacted with properly Verify(someMockedObject).equals(someObjectThatIsHardToInstantiate).oneTime(); Is it appropriate to mock ComplicatedObject in this scenario?

    Read the article

  • Informed TDD &ndash; Kata &ldquo;To Roman Numerals&rdquo;

    - by Ralf Westphal
    Originally posted on: http://geekswithblogs.net/theArchitectsNapkin/archive/2014/05/28/informed-tdd-ndash-kata-ldquoto-roman-numeralsrdquo.aspxIn a comment on my article on what I call Informed TDD (ITDD) reader gustav asked how this approach would apply to the kata “To Roman Numerals”. And whether ITDD wasn´t a violation of TDD´s principle of leaving out “advanced topics like mocks”. I like to respond with this article to his questions. There´s more to say than fits into a commentary. Mocks and TDD I don´t see in how far TDD is avoiding or opposed to mocks. TDD and mocks are orthogonal. TDD is about pocess, mocks are about structure and costs. Maybe by moving forward in tiny red+green+refactor steps less need arises for mocks. But then… if the functionality you need to implement requires “expensive” resource access you can´t avoid using mocks. Because you don´t want to constantly run all your tests against the real resource. True, in ITDD mocks seem to be in almost inflationary use. That´s not what you usually see in TDD demonstrations. However, there´s a reason for that as I tried to explain. I don´t use mocks as proxies for “expensive” resource. Rather they are stand-ins for functionality not yet implemented. They allow me to get a test green on a high level of abstraction. That way I can move forward in a top-down fashion. But if you think of mocks as “advanced” or if you don´t want to use a tool like JustMock, then you don´t need to use mocks. You just need to stand the sight of red tests for a little longer ;-) Let me show you what I mean by that by doing a kata. ITDD for “To Roman Numerals” gustav asked for the kata “To Roman Numerals”. I won´t explain the requirements again. You can find descriptions and TDD demonstrations all over the internet, like this one from Corey Haines. Now here is, how I would do this kata differently. 1. Analyse A demonstration of TDD should never skip the analysis phase. It should be made explicit. The requirements should be formalized and acceptance test cases should be compiled. “Formalization” in this case to me means describing the API of the required functionality. “[D]esign a program to work with Roman numerals” like written in this “requirement document” is not enough to start software development. Coding should only begin, if the interface between the “system under development” and its context is clear. If this interface is not readily recognizable from the requirements, it has to be developed first. Exploration of interface alternatives might be in order. It might be necessary to show several interface mock-ups to the customer – even if that´s you fellow developer. Designing the interface is a task of it´s own. It should not be mixed with implementing the required functionality behind the interface. Unfortunately, though, this happens quite often in TDD demonstrations. TDD is used to explore the API and implement it at the same time. To me that´s a violation of the Single Responsibility Principle (SRP) which not only should hold for software functional units but also for tasks or activities. In the case of this kata the API fortunately is obvious. Just one function is needed: string ToRoman(int arabic). And it lives in a class ArabicRomanConversions. Now what about acceptance test cases? There are hardly any stated in the kata descriptions. Roman numerals are explained, but no specific test cases from the point of view of a customer. So I just “invent” some acceptance test cases by picking roman numerals from a wikipedia article. They are supposed to be just “typical examples” without special meaning. Given the acceptance test cases I then try to develop an understanding of the problem domain. I´ll spare you that. The domain is trivial and is explain in almost all kata descriptions. How roman numerals are built is not difficult to understand. What´s more difficult, though, might be to find an efficient solution to convert into them automatically. 2. Solve The usual TDD demonstration skips a solution finding phase. Like the interface exploration it´s mixed in with the implementation. But I don´t think this is how it should be done. I even think this is not how it really works for the people demonstrating TDD. They´re simplifying their true software development process because they want to show a streamlined TDD process. I doubt this is helping anybody. Before you code you better have a plan what to code. This does not mean you have to do “Big Design Up-Front”. It just means: Have a clear picture of the logical solution in your head before you start to build a physical solution (code). Evidently such a solution can only be as good as your understanding of the problem. If that´s limited your solution will be limited, too. Fortunately, in the case of this kata your understanding does not need to be limited. Thus the logical solution does not need to be limited or preliminary or tentative. That does not mean you need to know every line of code in advance. It just means you know the rough structure of your implementation beforehand. Because it should mirror the process described by the logical or conceptual solution. Here´s my solution approach: The arabic “encoding” of numbers represents them as an ordered set of powers of 10. Each digit is a factor to multiply a power of ten with. The “encoding” 123 is the short form for a set like this: {1*10^2, 2*10^1, 3*10^0}. And the number is the sum of the set members. The roman “encoding” is different. There is no base (like 10 for arabic numbers), there are just digits of different value, and they have to be written in descending order. The “encoding” XVI is short for [10, 5, 1]. And the number is still the sum of the members of this list. The roman “encoding” thus is simpler than the arabic. Each “digit” can be taken at face value. No multiplication with a base required. But what about IV which looks like a contradiction to the above rule? It is not – if you accept roman “digits” not to be limited to be single characters only. Usually I, V, X, L, C, D, M are viewed as “digits”, and IV, IX etc. are viewed as nuisances preventing a simple solution. All looks different, though, once IV, IX etc. are taken as “digits”. Then MCMLIV is just a sum: M+CM+L+IV which is 1000+900+50+4. Whereas before it would have been understood as M-C+M+L-I+V – which is more difficult because here some “digits” get subtracted. Here´s the list of roman “digits” with their values: {1, I}, {4, IV}, {5, V}, {9, IX}, {10, X}, {40, XL}, {50, L}, {90, XC}, {100, C}, {400, CD}, {500, D}, {900, CM}, {1000, M} Since I take IV, IX etc. as “digits” translating an arabic number becomes trivial. I just need to find the values of the roman “digits” making up the number, e.g. 1954 is made up of 1000, 900, 50, and 4. I call those “digits” factors. If I move from the highest factor (M=1000) to the lowest (I=1) then translation is a two phase process: Find all the factors Translate the factors found Compile the roman representation Translation is just a look-up. Finding, though, needs some calculation: Find the highest remaining factor fitting in the value Remember and subtract it from the value Repeat with remaining value and remaining factors Please note: This is just an algorithm. It´s not code, even though it might be close. Being so close to code in my solution approach is due to the triviality of the problem. In more realistic examples the conceptual solution would be on a higher level of abstraction. With this solution in hand I finally can do what TDD advocates: find and prioritize test cases. As I can see from the small process description above, there are two aspects to test: Test the translation Test the compilation Test finding the factors Testing the translation primarily means to check if the map of factors and digits is comprehensive. That´s simple, even though it might be tedious. Testing the compilation is trivial. Testing factor finding, though, is a tad more complicated. I can think of several steps: First check, if an arabic number equal to a factor is processed correctly (e.g. 1000=M). Then check if an arabic number consisting of two consecutive factors (e.g. 1900=[M,CM]) is processed correctly. Then check, if a number consisting of the same factor twice is processed correctly (e.g. 2000=[M,M]). Finally check, if an arabic number consisting of non-consecutive factors (e.g. 1400=[M,CD]) is processed correctly. I feel I can start an implementation now. If something becomes more complicated than expected I can slow down and repeat this process. 3. Implement First I write a test for the acceptance test cases. It´s red because there´s no implementation even of the API. That´s in conformance with “TDD lore”, I´d say: Next I implement the API: The acceptance test now is formally correct, but still red of course. This will not change even now that I zoom in. Because my goal is not to most quickly satisfy these tests, but to implement my solution in a stepwise manner. That I do by “faking” it: I just “assume” three functions to represent the transformation process of my solution: My hypothesis is that those three functions in conjunction produce correct results on the API-level. I just have to implement them correctly. That´s what I´m trying now – one by one. I start with a simple “detail function”: Translate(). And I start with all the test cases in the obvious equivalence partition: As you can see I dare to test a private method. Yes. That´s a white box test. But as you´ll see it won´t make my tests brittle. It serves a purpose right here and now: it lets me focus on getting one aspect of my solution right. Here´s the implementation to satisfy the test: It´s as simple as possible. Right how TDD wants me to do it: KISS. Now for the second equivalence partition: translating multiple factors. (It´a pattern: if you need to do something repeatedly separate the tests for doing it once and doing it multiple times.) In this partition I just need a single test case, I guess. Stepping up from a single translation to multiple translations is no rocket science: Usually I would have implemented the final code right away. Splitting it in two steps is just for “educational purposes” here. How small your implementation steps are is a matter of your programming competency. Some “see” the final code right away before their mental eye – others need to work their way towards it. Having two tests I find more important. Now for the next low hanging fruit: compilation. It´s even simpler than translation. A single test is enough, I guess. And normally I would not even have bothered to write that one, because the implementation is so simple. I don´t need to test .NET framework functionality. But again: if it serves the educational purpose… Finally the most complicated part of the solution: finding the factors. There are several equivalence partitions. But still I decide to write just a single test, since the structure of the test data is the same for all partitions: Again, I´m faking the implementation first: I focus on just the first test case. No looping yet. Faking lets me stay on a high level of abstraction. I can write down the implementation of the solution without bothering myself with details of how to actually accomplish the feat. That´s left for a drill down with a test of the fake function: There are two main equivalence partitions, I guess: either the first factor is appropriate or some next. The implementation seems easy. Both test cases are green. (Of course this only works on the premise that there´s always a matching factor. Which is the case since the smallest factor is 1.) And the first of the equivalence partitions on the higher level also is satisfied: Great, I can move on. Now for more than a single factor: Interestingly not just one test becomes green now, but all of them. Great! You might say, then I must have done not the simplest thing possible. And I would reply: I don´t care. I did the most obvious thing. But I also find this loop very simple. Even simpler than a recursion of which I had thought briefly during the problem solving phase. And by the way: Also the acceptance tests went green: Mission accomplished. At least functionality wise. Now I´ve to tidy up things a bit. TDD calls for refactoring. Not uch refactoring is needed, because I wrote the code in top-down fashion. I faked it until I made it. I endured red tests on higher levels while lower levels weren´t perfected yet. But this way I saved myself from refactoring tediousness. At the end, though, some refactoring is required. But maybe in a different way than you would expect. That´s why I rather call it “cleanup”. First I remove duplication. There are two places where factors are defined: in Translate() and in Find_factors(). So I factor the map out into a class constant. Which leads to a small conversion in Find_factors(): And now for the big cleanup: I remove all tests of private methods. They are scaffolding tests to me. They only have temporary value. They are brittle. Only acceptance tests need to remain. However, I carry over the single “digit” tests from Translate() to the acceptance test. I find them valuable to keep, since the other acceptance tests only exercise a subset of all roman “digits”. This then is my final test class: And this is the final production code: Test coverage as reported by NCrunch is 100%: Reflexion Is this the smallest possible code base for this kata? Sure not. You´ll find more concise solutions on the internet. But LOC are of relatively little concern – as long as I can understand the code quickly. So called “elegant” code, however, often is not easy to understand. The same goes for KISS code – especially if left unrefactored, as it is often the case. That´s why I progressed from requirements to final code the way I did. I first understood and solved the problem on a conceptual level. Then I implemented it top down according to my design. I also could have implemented it bottom-up, since I knew some bottom of the solution. That´s the leaves of the functional decomposition tree. Where things became fuzzy, since the design did not cover any more details as with Find_factors(), I repeated the process in the small, so to speak: fake some top level, endure red high level tests, while first solving a simpler problem. Using scaffolding tests (to be thrown away at the end) brought two advantages: Encapsulation of the implementation details was not compromised. Naturally private methods could stay private. I did not need to make them internal or public just to be able to test them. I was able to write focused tests for small aspects of the solution. No need to test everything through the solution root, the API. The bottom line thus for me is: Informed TDD produces cleaner code in a systematic way. It conforms to core principles of programming: Single Responsibility Principle and/or Separation of Concerns. Distinct roles in development – being a researcher, being an engineer, being a craftsman – are represented as different phases. First find what, what there is. Then devise a solution. Then code the solution, manifest the solution in code. Writing tests first is a good practice. But it should not be taken dogmatic. And above all it should not be overloaded with purposes. And finally: moving from top to bottom through a design produces refactored code right away. Clean code thus almost is inevitable – and not left to a refactoring step at the end which is skipped often for different reasons.   PS: Yes, I have done this kata several times. But that has only an impact on the time needed for phases 1 and 2. I won´t skip them because of that. And there are no shortcuts during implementation because of that.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >