Search Results

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

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

  • Is this an idiomatic way to pass mocks into objects?

    - by Billy ONeal
    I'm a bit confused about passing in this mock class into an implementation class. It feels wrong to have all this explicitly managed memory flying around. I'd just pass the class by value but that runs into the slicing problem. Am I missing something here? Implementation: namespace detail { struct FileApi { virtual HANDLE CreateFileW( __in LPCWSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile ) { return ::CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } virtual void CloseHandle(HANDLE handleToClose) { ::CloseHandle(handleToClose); } }; } class File : boost::noncopyable { HANDLE hWin32; boost::scoped_ptr<detail::FileApi> fileApi; public: File( __in LPCWSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile, __in detail::FileApi * method = new detail::FileApi() ) { fileApi.reset(method); hWin32 = fileApi->CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } }; namespace detail { struct FileApi { virtual HANDLE CreateFileW( __in LPCWSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile ) { return ::CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } virtual void CloseHandle(HANDLE handleToClose) { ::CloseHandle(handleToClose); } }; } class File : boost::noncopyable { HANDLE hWin32; boost::scoped_ptr<detail::FileApi> fileApi; public: File( __in LPCWSTR lpFileName, __in DWORD dwDesiredAccess, __in DWORD dwShareMode, __in_opt LPSECURITY_ATTRIBUTES lpSecurityAttributes, __in DWORD dwCreationDisposition, __in DWORD dwFlagsAndAttributes, __in_opt HANDLE hTemplateFile, __in detail::FileApi * method = new detail::FileApi() ) { fileApi.reset(method); hWin32 = fileApi->CreateFileW(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } ~File() { fileApi->CloseHandle(hWin32); } }; Tests: namespace detail { struct MockFileApi : public FileApi { MOCK_METHOD7(CreateFileW, HANDLE(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE)); MOCK_METHOD1(CloseHandle, void(HANDLE)); }; } using namespace detail; using namespace testing; TEST(Test_File, OpenPassesArguments) { MockFileApi * api = new MockFileApi; EXPECT_CALL(*api, CreateFileW(Eq(L"BozoFile"), Eq(56), Eq(72), Eq(reinterpret_cast<LPSECURITY_ATTRIBUTES>(67)), Eq(98), Eq(102), Eq(reinterpret_cast<HANDLE>(98)))) .Times(1).WillOnce(Return(reinterpret_cast<HANDLE>(42))); File test(L"BozoFile", 56, 72, reinterpret_cast<LPSECURITY_ATTRIBUTES>(67), 98, 102, reinterpret_cast<HANDLE>(98), api); }

    Read the article

  • Castle Windsor Dependency Injection with MVC4

    - by Renso
    Problem:Installed MVC4 on my local and ran a MVC3 app and got an error where Castle Windsor was unable to resolve any controllers' constructor injections. It failed with "No component for supporting the service....".As soon as I uninstall MVC4 beta, the problem vanishes like magic?!I also tried to upgrade to NHibernate 3 and Castle and Castle Windsor to version 3 (from version 2), but since I use Rhino Commons, that is not possible as the Rhino Commons project looks like is no longer supported and requests to upgrade it to work with NHibernate version 3 two years ago has gone unanswered. The problem is that Rhino Commons (the older version) references a method in Castle version 2 that has been depreciated in version 3: "CreateContainer("windsor.boo")' threw an exception of type 'System.MissingMethodException."Hope this helps anyone else who runs into this issue. Btw I used NuGet package manager to install the correct packages so I know that is not the issue.

    Read the article

  • A TDD Journey: 3- Mocks vs. Stubs; Test Frameworks; Assertions; ReSharper Accelerators

    Test-Driven Development (TDD) involves the repetition of a very short development cycle that begins with an initially-failing test that defines the required functionality, and ends with producing the minimum amount of code to pass that test, and finally refactoring the new code. Michael Sorens continues his introduction to TDD that is more of a journey in six parts, by implementing the first tests and introducing the topics of Test doubles; Test Runners, Constraints and assertions

    Read the article

  • Fake It Easy On Yourself

    - by Lee Brandt
    I have been using Rhino.Mocks pretty much since I started being a mockist-type tester. I have been very happy with it for the most part, but a year or so ago, I got a glimpse of some tests using Moq. I thought the little bit I saw was very compelling. For a long time, I had been using: 1: var _repository = MockRepository.GenerateMock<IRepository>(); 2: _repository.Expect(repo=>repo.SomeCall()).Return(SomeValue); 3: var _controller = new SomeKindaController(_repository); 4:  5: ... some exercising code 6: _repository.AssertWasCalled(repo => repo.SomeCall()); I was happy with that syntax. I didn’t go looking for something else, but what I saw was: 1: var _repository = new Mock(); And I thought, “That looks really nice!” The code was very expressive and easier to read that the Rhino.Mocks syntax. I have gotten so used to the Rhino.Mocks syntax that it made complete sense to me, but to developers I was mentoring in mocking, it was sometimes to obtuse. SO I thought I would write some tests using Moq as my mocking tool. But I discovered something ugly once I got into it. The way Mocks are created makes Moq very easy to read, but that only gives you a Mock not the object itself, which is what you’ll need to pass to the exercising code. So this is what it ends up looking like: 1: var _repository = new Mock<IRepository>(); 2: _repository.SetUp(repo=>repo.SomeCall).Returns(SomeValue); 3: var _controller = new SomeKindaController(_repository.Object); 4: .. some exercizing code 5: _repository.Verify(repo => repo.SomeCall()); Two things jump out at me: 1) when I set up my mocked calls, do I set it on the Mock or the Mock’s “object”? and 2) What am I verifying on SomeCall? Just that it was called? that it is available to call? Dealing with 2 objects, a “Mock” and an “Object” made me have to consider naming conventions. Should I always call the mock _repositoryMock and the object _repository? So I went back to Rhino.Mocks. It is the most widely used framework, and show other how to use it is easier because there is one natural object to use, the _repository. Then I came across a blog post from Patrik Hägne, and that led me to a post about FakeItEasy. I went to the Google Code site and when I saw the syntax, I got very excited. Then I read the wiki page where Patrik stated why he wrote FakeItEasy, and it mirrored my own experience. So I began to play with it a bit. So far, I am sold. the syntax is VERY easy to read and the fluent interface is super discoverable. It basically looks like this: 1: var _repository = A.Fake<IRepository>(); 2: a.CallTo(repo=>repo.SomeMethod()).Returns(SomeValue); 3: var _controller = new SomeKindaController(_repository); 4: ... some exercising code 5: A.CallTo(() => _repository.SOmeMethod()).MustHaveHappened(); Very nice. But is it mature? It’s only been around a couple of years, so will I be giving up some thing that I use a lot because it hasn’t been implemented yet? I doesn’t seem so. As I read more examples and posts from Patrik, he has some pretty complex scenarios. He even has support for VB.NET! So if you are looking for a mocking framework that looks and feels very natural, try out FakeItEasy!

    Read the article

  • Bug unsubscribing from Ubuntu One Mobile

    - by rhino
    Hi guys, I have an Ubuntu One Mobile subscription, which I can see in my subscriptions page: one.ubuntu.com/account/subscription/756082 I no longer need my Ubuntu One Mobile subscription, so click the link to cancel the Mobile service subscription: one.ubuntu.com/account/cancel/756082/ Then confirm that request to cancel: one.ubuntu.com/account/cancel/756082/confirm/ But the process ends there showing a "Something has gone wrong page", and my subscription remains active :( The same problem occurred when I attempted the same a few weeks back, so not a temporary problem I'm thinking. Any input gratefully received. I would like to report this problem directly to the maintainer of this part of the Ubuntu site but cannot see how to do that.

    Read the article

  • Isometric Screen View to World View

    - by Sleepy Rhino
    I am having trouble working out the math to transform the screen coordinates to the Grid coordinates. The code below is how far I have got but it is totally wrong any help or resources to fix this issue would be great, had a complete mind block with this for some reason. private Point ScreenToIso(int mouseX, int mouseY) { int offsetX = WorldBuilder.STARTX; int offsetY = WorldBuilder.STARTY; Vector2 startV = new Vector2(offsetX, offsetY); int mapX = offsetX - mouseX; int mapY = offsetY - mouseY + (WorldBuilder.tileHeight / 2); mapY = -1 * (mapY / WorldBuilder.tileHeight); mapX = (mapX / WorldBuilder.tileHeight) + mapY; return new Point(mapX, mapY); }

    Read the article

  • Slow wireless about 1/3 bandwidth of wired from cable modem

    - by Rhino
    HP DV6000 Wireless G Broadcom Netgear WNDR3400 router properly configured. Windows laptops using wireless G and N are considerably faster than mine. 12.04 LTS, all restricted drivers and all up to date. 50Mbps wired and 9-21 Mbps wireless on Ubuntu. 00:14.0 Bridge [0680]: NVIDIA Corporation MCP51 Ethernet Controller [10de:0269] (rev a3) Subsystem: Hewlett-Packard Company Presario V6133CL [103c:30b7] Kernel driver in use: forcedeth 03:00.0 Network controller [0280]: Broadcom Corporation BCM4311 802.11a/b/g [14e4:4312] (rev 02) Subsystem: Hewlett-Packard Company Broadcom 802.11a/b/g WLAN [103c:1370] Kernel driver in use: wl

    Read the article

  • Isometric Collision Detection

    - by Sleepy Rhino
    I am having some issues with trying to detect collision of two isometric tile. I have tried plotting the lines between each point on the tile and then checking for line intercepts however that didn't work (probably due to incorrect formula) After looking into this for awhile today I believe I am thinking to much into it and there must be a easier way. I am not looking for code just some advise on the best way to achieve detection of overlap

    Read the article

  • Nmock2 and Event Expectations

    - by Kildareflare
    Im in the process of writing a test for a small application that follows the MVP pattern. Technically, I know I should have written the test before the code, but I needed to knock up a demo app quick smart and so im now going back to the test before moving on to the real development. In short I am attempting to test the presenter, however I cannot even get an empty test to run due to an Internal.ExpectationException. The exception is raised on a unexpected invocation of an event assignation. Here is the presenter class, public LBCPresenter(IView view, IModel model) { m_model = model; m_model.BatteryModifiedEvent += new EventHandler(m_model_BatteryModifiedEvent); } Model Interface public interface IModel { event EventHandler BatteryModifiedEvent; } And here is the test class, I can't see what im missing, ive told NMock to expect the event... [TestFixture] public class MVP_PresenterTester { private Mockery mocks; private IView _mockView; private IViewObserver _Presenter; private IModel _mockModel; [SetUp] public void SetUp() { mocks = new Mockery(); _mockView = mocks.NewMock<IView>(); _mockModel = mocks.NewMock<IModel>(); _Presenter = new LBCPresenter(_mockView, _mockModel); } [Test] public void TestClosingFormWhenNotDirty() { Expect.Once.On(_mockModel).EventAdd("BatteryModifiedEvent", NMock2.Is.Anything); //makes no difference if following line is commented out or not //mocks.VerifyAllExpectationsHaveBeenMet(); } } Every time I run the test I get the same expectation Exception. Any ideas?

    Read the article

  • Assembly installed into the GAC not showing up in Visual Studio

    - by yodaj007
    This sounds related to this question, but they aren't the same thing. That question had no assemblies showing up. Mine has everything except the specific one I installed. I'm hoping someone has a solution to this... am I doing something wrong? Or did I find some bug in VS? I am using Visual Studio 2010 Professional Beta 2 on Windows 7 Ultimate. I just downloaded Rhino Mocks and decided to install it into the GAC using the command-line utility GACUTIL. I then rebooted. Here you can see the assembly in my GAC (click to enlarge): And here is the list of assemblies available to me in Visual Studio: Here is the command prompt where I installed it, and then confirmed it: C:\Users\jason\Downloads>gacutil -i Rhino.Mocks.dll Microsoft (R) .NET Global Assembly Cache Utility. Version 4.0.21006.1 Copyright (c) Microsoft Corporation. All rights reserved. Assembly successfully added to the cache C:\Users\jason\Downloads>gacutil /l |grep -i rhino Rhino.Mocks, Version=3.6.0.0, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL

    Read the article

  • Creating method templates in Eclipse

    - by stevebot
    Is there any way to do the following in eclipse? Have eclipse template a method like the following public void test(){ // CREATE MOCKS // CREATE EXPECTATIONS // REPLAY MOCKS // VERIFY MOCKS } so then I could presumably just use intellisense and select an option like "createtest" and have it stub out a method with the comments similar to the above?My problem is that often myself and other developers I know forgot all the steps we need to follow to do what we dub as a valid unit test for our application. If I could template our test methods to stub out the comments above it would be a big help.

    Read the article

  • Mocking my custom dependencies with Spring

    - by Brabster
    Is is possible to declare mocks using some mocking framework for my own classes declaratively with Spring? I know there are some standard mocks available in Spring, but I'd like to be able to mock out my own classes declaratively too. Just to check I'm not going about this the wrong way: the idea is to have a pair of JUnit test and Spring config for each integration test I want to do, mocking everything except the specific integration aspect I'm testing (say I had a dependency on two different data services, test one at a time) and minimising the amount of repeated Java code specifying the mocks.

    Read the article

  • Returning a mock object from a mock object

    - by Songo
    I'm trying to return an object when mocking a parser class. This is the test code using PHPUnit 3.7 //set up the result object that I want to be returned from the call to parse method $parserResult= new ParserResult(); $parserResult->setSegment('some string'); //set up the stub Parser object $stubParser=$this->getMock('Parser'); $stubParser->expects($this->any()) ->method('parse') ->will($this->returnValue($parserResult)); //injecting the stub to my client class $fileHeaderParser= new FileWriter($stubParser); $output=$fileParser->writeStringToFile(); Inside my writeStringToFile() method I'm using $parserResult like this: writeStringToFile(){ //Some code... $parserResult=$parser->parse(); $segment=$parserResult->getSegment();//that's why I set the segment in the test. } Should I mock ParserResult in the first place, so that the mock returns a mock? Is it good design for mocks to return mocks? Is there a better approach to do this all?!

    Read the article

  • My website keeps crashing IE, can't debug

    - by Ninja rhino
    I have a website that suddenly started to crash internet explorer. The website loads and starts executing javascript but somewhere in there the machinery explodes. I don't even get a script error, it just crashes. I've tried to manually step through every single line of js with the built in debugger but then of course the problem doesn't occur. If i choose to debug the application when it crashes i see the following message. Unhandled exception at 0x6c5dedf5 in iexplore.exe: 0xC0000005: Access violation reading location 0x00000090. The top 5 items in the call stack looks like this VGX.dll!6c5dedf5() [Frames below may be incorrect and/or missing, no symbols loaded for VGX.dll] VGX.dll!6c594d70() VGX.dll!6c594f63() VGX.dll!6c595350() VGX.dll!6c58f5e3() mshtml.dll!6f88dd17() VGX.dll seems to be part of the vml renderer and i am in fact using VML. I'm not suprised because i've had so many problems with vml, attributes has to be set in specific order, sometimes you cant set attributes when you have elements attached to the dom or vice versa (everything undocumented btw) but then the problems can usually be reproduced when debugging but not now :( The problem also occurs in no plugin-mode. Is there a better approach than trial and error to solve this? Edit: Adding a console outputting every suspect modification to the DOM made the problem only occur sometimes. (the console is also implemented in javascript on the same page, i'm able to see the output even after a crash as the window is still visible) Apparently it seems to be some kind of race condition. I managed to track it down even further, and it seems to occur when you remove an object from the DOM too quickly after it's just been added. (most likely only for vml-elements with some special attribute, didn't try further) And it can't be fixed by adding a dead loop in front of removeChild(pretty bad solution anyway), the page has to be rendered by the browser once after the addChild before you can call removeChild. sigh

    Read the article

  • Robust Javascript parser in Java

    - by Misha Koshelev
    Dear All: I am looking for a robust Javascript parser written in Java - by which I mean a Javascript parser that is able to handle most real world Javascript. I am only interested in parsing Javascript, not in executing it. I have found Rhino: http://groups.google.com/group/mozilla.dev.tech.js-engine.rhino/browse_thread/thread/1eff23a8ee57b991 Am I missing anything? Is this the best solution? Thank you! Misha

    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

  • Integrating JavaScript Unit Tests with Visual Studio

    - by Stephen Walther
    Modern ASP.NET web applications take full advantage of client-side JavaScript to provide better interactivity and responsiveness. If you are building an ASP.NET application in the right way, you quickly end up with lots and lots of JavaScript code. When writing server code, you should be writing unit tests. One big advantage of unit tests is that they provide you with a safety net that enable you to safely modify your existing code – for example, fix bugs, add new features, and make performance enhancements -- without breaking your existing code. Every time you modify your code, you can execute your unit tests to verify that you have not broken anything. For the same reason that you should write unit tests for your server code, you should write unit tests for your client code. JavaScript is just as susceptible to bugs as C#. There is no shortage of unit testing frameworks for JavaScript. Each of the major JavaScript libraries has its own unit testing framework. For example, jQuery has QUnit, Prototype has UnitTestJS, YUI has YUI Test, and Dojo has Dojo Objective Harness (DOH). The challenge is integrating a JavaScript unit testing framework with Visual Studio. Visual Studio and Visual Studio ALM provide fantastic support for server-side unit tests. You can easily view the results of running your unit tests in the Visual Studio Test Results window. You can set up a check-in policy which requires that all unit tests pass before your source code can be committed to the source code repository. In addition, you can set up Team Build to execute your unit tests automatically. Unfortunately, Visual Studio does not provide “out-of-the-box” support for JavaScript unit tests. MS Test, the unit testing framework included in Visual Studio, does not support JavaScript unit tests. As soon as you leave the server world, you are left on your own. The goal of this blog entry is to describe one approach to integrating JavaScript unit tests with MS Test so that you can execute your JavaScript unit tests side-by-side with your C# unit tests. The goal is to enable you to execute JavaScript unit tests in exactly the same way as server-side unit tests. You can download the source code described by this project by scrolling to the end of this blog entry. Rejected Approach: Browser Launchers One popular approach to executing JavaScript unit tests is to use a browser as a test-driver. When you use a browser as a test-driver, you open up a browser window to execute and view the results of executing your JavaScript unit tests. For example, QUnit – the unit testing framework for jQuery – takes this approach. The following HTML page illustrates how you can use QUnit to create a unit test for a function named addNumbers(). <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Using QUnit</title> <link rel="stylesheet" href="http://github.com/jquery/qunit/raw/master/qunit/qunit.css" type="text/css" /> </head> <body> <h1 id="qunit-header">QUnit example</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <div id="qunit-fixture">test markup, will be hidden</div> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://github.com/jquery/qunit/raw/master/qunit/qunit.js"></script> <script type="text/javascript"> // The function to test function addNumbers(a, b) { return a+b; } // The unit test test("Test of addNumbers", function () { equals(4, addNumbers(1,3), "1+3 should be 4"); }); </script> </body> </html> This test verifies that calling addNumbers(1,3) returns the expected value 4. When you open this page in a browser, you can see that this test does, in fact, pass. The idea is that you can quickly refresh this QUnit HTML JavaScript test driver page in your browser whenever you modify your JavaScript code. In other words, you can keep a browser window open and keep refreshing it over and over while you are developing your application. That way, you can know very quickly whenever you have broken your JavaScript code. While easy to setup, there are several big disadvantages to this approach to executing JavaScript unit tests: You must view your JavaScript unit test results in a different location than your server unit test results. The JavaScript unit test results appear in the browser and the server unit test results appear in the Visual Studio Test Results window. Because all of your unit test results don’t appear in a single location, you are more likely to introduce bugs into your code without noticing it. Because your unit tests are not integrated with Visual Studio – in particular, MS Test -- you cannot easily include your JavaScript unit tests when setting up check-in policies or when performing automated builds with Team Build. A more sophisticated approach to using a browser as a test-driver is to automate the web browser. Instead of launching the browser and loading the test code yourself, you use a framework to automate this process. There are several different testing frameworks that support this approach: · Selenium – Selenium is a very powerful framework for automating browser tests. You can create your tests by recording a Firefox session or by writing the test driver code in server code such as C#. You can learn more about Selenium at http://seleniumhq.org/. LTAF – The ASP.NET team uses the Lightweight Test Automation Framework to test JavaScript code in the ASP.NET framework. You can learn more about LTAF by visiting the project home at CodePlex: http://aspnet.codeplex.com/releases/view/35501 jsTestDriver – This framework uses Java to automate the browser. jsTestDriver creates a server which can be used to automate multiple browsers simultaneously. This project is located at http://code.google.com/p/js-test-driver/ TestSwam – This framework, created by John Resig, uses PHP to automate the browser. Like jsTestDriver, the framework creates a test server. You can open multiple browsers that are automated by the test server. Learn more about TestSwarm by visiting the following address: https://github.com/jeresig/testswarm/wiki Yeti – This is the framework introduced by Yahoo for automating browser tests. Yeti uses server-side JavaScript and depends on Node.js. Learn more about Yeti at http://www.yuiblog.com/blog/2010/08/25/introducing-yeti-the-yui-easy-testing-interface/ All of these frameworks are great for integration tests – however, they are not the best frameworks to use for unit tests. In one way or another, all of these frameworks depend on executing tests within the context of a “living and breathing” browser. If you create an ASP.NET Unit Test then Visual Studio will launch a web server before executing the unit test. Why is launching a web server so bad? It is not the worst thing in the world. However, it does introduce dependencies that prevent your code from being tested in isolation. One of the defining features of a unit test -- versus an integration test – is that a unit test tests code in isolation. Another problem with launching a web server when performing unit tests is that launching a web server can be slow. If you cannot execute your unit tests quickly, you are less likely to execute your unit tests each and every time you make a code change. You are much more likely to fall into the pit of failure. Launching a browser when performing a JavaScript unit test has all of the same disadvantages as launching a web server when performing an ASP.NET unit test. Instead of testing a unit of JavaScript code in isolation, you are testing JavaScript code within the context of a particular browser. Using the frameworks listed above for integration tests makes perfect sense. However, I want to consider a different approach for creating unit tests for JavaScript code. Using Server-Side JavaScript for JavaScript Unit Tests A completely different approach to executing JavaScript unit tests is to perform the tests outside of any browser. If you really want to test JavaScript then you should test JavaScript and leave the browser out of the testing process. There are several ways that you can execute JavaScript on the server outside the context of any browser: RhinoRhino is an implementation of JavaScript written in Java. The Rhino project is maintained by the Mozilla project. Learn more about Rhino at http://www.mozilla.org/rhino/ V8 – V8 is the open-source Google JavaScript engine written in C++. This is the JavaScript engine used by the Chrome web browser. You can download V8 and embed it in your project by visiting http://code.google.com/p/v8/ JScript – JScript is the JavaScript Script Engine used by Internet Explorer (up to but not including Internet Explorer 9), Windows Script Host, and Active Server Pages. Internet Explorer is still the most popular web browser. Therefore, I decided to focus on using the JScript Script Engine to execute JavaScript unit tests. Using the Microsoft Script Control There are two basic ways that you can pass JavaScript to the JScript Script Engine and execute the code: use the Microsoft Windows Script Interfaces or use the Microsoft Script Control. The difficult and proper way to execute JavaScript using the JScript Script Engine is to use the Microsoft Windows Script Interfaces. You can learn more about the Script Interfaces by visiting http://msdn.microsoft.com/en-us/library/t9d4xf28(VS.85).aspx The main disadvantage of using the Script Interfaces is that they are difficult to use from .NET. There is a great series of articles on using the Script Interfaces from C# located at http://www.drdobbs.com/184406028. I picked the easier alternative and used the Microsoft Script Control. The Microsoft Script Control is an ActiveX control that provides a higher level abstraction over the Window Script Interfaces. You can download the Microsoft Script Control from here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d7e31492-2595-49e6-8c02-1426fec693ac After you download the Microsoft Script Control, you need to add a reference to it to your project. Select the Visual Studio menu option Project, Add Reference to open the Add Reference dialog. Select the COM tab and add the Microsoft Script Control 1.0. Using the Script Control is easy. You call the Script Control AddCode() method to add JavaScript code to the Script Engine. Next, you call the Script Control Run() method to run a particular JavaScript function. The reference documentation for the Microsoft Script Control is located at the MSDN website: http://msdn.microsoft.com/en-us/library/aa227633%28v=vs.60%29.aspx Creating the JavaScript Code to Test To keep things simple, let’s imagine that you want to test the following JavaScript function named addNumbers() which simply adds two numbers together: MvcApplication1\Scripts\Math.js function addNumbers(a, b) { return 5; } Notice that the addNumbers() method always returns the value 5. Right-now, it will not pass a good unit test. Create this file and save it in your project with the name Math.js in your MVC project’s Scripts folder (Save the file in your actual MVC application and not your MVC test application). Creating the JavaScript Test Helper Class To make it easier to use the Microsoft Script Control in unit tests, we can create a helper class. This class contains two methods: LoadFile() – Loads a JavaScript file. Use this method to load the JavaScript file being tested or the JavaScript file containing the unit tests. ExecuteTest() – Executes the JavaScript code. Use this method to execute a JavaScript unit test. Here’s the code for the JavaScriptTestHelper class: JavaScriptTestHelper.cs   using System; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using MSScriptControl; namespace MvcApplication1.Tests { public class JavaScriptTestHelper : IDisposable { private ScriptControl _sc; private TestContext _context; /// <summary> /// You need to use this helper with Unit Tests and not /// Basic Unit Tests because you need a Test Context /// </summary> /// <param name="testContext">Unit Test Test Context</param> public JavaScriptTestHelper(TestContext testContext) { if (testContext == null) { throw new ArgumentNullException("TestContext"); } _context = testContext; _sc = new ScriptControl(); _sc.Language = "JScript"; _sc.AllowUI = false; } /// <summary> /// Load the contents of a JavaScript file into the /// Script Engine. /// </summary> /// <param name="path">Path to JavaScript file</param> public void LoadFile(string path) { var fileContents = File.ReadAllText(path); _sc.AddCode(fileContents); } /// <summary> /// Pass the path of the test that you want to execute. /// </summary> /// <param name="testMethodName">JavaScript function name</param> public void ExecuteTest(string testMethodName) { dynamic result = null; try { result = _sc.Run(testMethodName, new object[] { }); } catch { var error = ((IScriptControl)_sc).Error; if (error != null) { var description = error.Description; var line = error.Line; var column = error.Column; var text = error.Text; var source = error.Source; if (_context != null) { var details = String.Format("{0} \r\nLine: {1} Column: {2}", source, line, column); _context.WriteLine(details); } } throw new AssertFailedException(error.Description); } } public void Dispose() { _sc = null; } } }     Notice that the JavaScriptTestHelper class requires a Test Context to be instantiated. For this reason, you can use the JavaScriptTestHelper only with a Visual Studio Unit Test and not a Basic Unit Test (These are two different types of Visual Studio project items). Add the JavaScriptTestHelper file to your MVC test application (for example, MvcApplication1.Tests). Creating the JavaScript Unit Test Next, we need to create the JavaScript unit test function that we will use to test the addNumbers() function. Create a folder in your MVC test project named JavaScriptTests and add the following JavaScript file to this folder: MvcApplication1.Tests\JavaScriptTests\MathTest.js /// <reference path="JavaScriptUnitTestFramework.js"/> function testAddNumbers() { // Act var result = addNumbers(1, 3); // Assert assert.areEqual(4, result, "addNumbers did not return right value!"); }   The testAddNumbers() function takes advantage of another JavaScript library named JavaScriptUnitTestFramework.js. This library contains all of the code necessary to make assertions. Add the following JavaScriptnitTestFramework.js to the same folder as the MathTest.js file: MvcApplication1.Tests\JavaScriptTests\JavaScriptUnitTestFramework.js var assert = { areEqual: function (expected, actual, message) { if (expected !== actual) { throw new Error("Expected value " + expected + " is not equal to " + actual + ". " + message); } } }; There is only one type of assertion supported by this file: the areEqual() assertion. Most likely, you would want to add additional types of assertions to this file to make it easier to write your JavaScript unit tests. Deploying the JavaScript Test Files This step is non-intuitive. When you use Visual Studio to run unit tests, Visual Studio creates a new folder and executes a copy of the files in your project. After you run your unit tests, your Visual Studio Solution will contain a new folder named TestResults that includes a subfolder for each test run. You need to configure Visual Studio to deploy your JavaScript files to the test run folder or Visual Studio won’t be able to find your JavaScript files when you execute your unit tests. You will get an error that looks something like this when you attempt to execute your unit tests: You can configure Visual Studio to deploy your JavaScript files by adding a Test Settings file to your Visual Studio Solution. It is important to understand that you need to add this file to your Visual Studio Solution and not a particular Visual Studio project. Right-click your Solution in the Solution Explorer window and select the menu option Add, New Item. Select the Test Settings item and click the Add button. After you create a Test Settings file for your solution, you can indicate that you want a particular folder to be deployed whenever you perform a test run. Select the menu option Test, Edit Test Settings to edit your test configuration file. Select the Deployment tab and select your MVC test project’s JavaScriptTest folder to deploy. Click the Apply button and the Close button to save the changes and close the dialog. Creating the Visual Studio Unit Test The very last step is to create the Visual Studio unit test (the MS Test unit test). Add a new unit test to your MVC test project by selecting the menu option Add New Item and selecting the Unit Test project item (Do not select the Basic Unit Test project item): The difference between a Basic Unit Test and a Unit Test is that a Unit Test includes a Test Context. We need this Test Context to use the JavaScriptTestHelper class that we created earlier. Enter the following test method for the new unit test: [TestMethod] public void TestAddNumbers() { var jsHelper = new JavaScriptTestHelper(this.TestContext); // Load JavaScript files jsHelper.LoadFile("JavaScriptUnitTestFramework.js"); jsHelper.LoadFile(@"..\..\..\MvcApplication1\Scripts\Math.js"); jsHelper.LoadFile("MathTest.js"); // Execute JavaScript Test jsHelper.ExecuteTest("testAddNumbers"); } This code uses the JavaScriptTestHelper to load three files: JavaScripUnitTestFramework.js – Contains the assert functions. Math.js – Contains the addNumbers() function from your MVC application which is being tested. MathTest.js – Contains the JavaScript unit test function. Next, the test method calls the JavaScriptTestHelper ExecuteTest() method to execute the testAddNumbers() JavaScript function. Running the Visual Studio JavaScript Unit Test After you complete all of the steps described above, you can execute the JavaScript unit test just like any other unit test. You can use the keyboard combination CTRL-R, CTRL-A to run all of the tests in the current Visual Studio Solution. Alternatively, you can use the buttons in the Visual Studio toolbar to run the tests: (Unfortunately, the Run All Impacted Tests button won’t work correctly because Visual Studio won’t detect that your JavaScript code has changed. Therefore, you should use either the Run Tests in Current Context or Run All Tests in Solution options instead.) The results of running the JavaScript tests appear side-by-side with the results of running the server tests in the Test Results window. For example, if you Run All Tests in Solution then you will get the following results: Notice that the TestAddNumbers() JavaScript test has failed. That is good because our addNumbers() function is hard-coded to always return the value 5. If you double-click the failing JavaScript test, you can view additional details such as the JavaScript error message and the line number of the JavaScript code that failed: Summary The goal of this blog entry was to explain an approach to creating JavaScript unit tests that can be easily integrated with Visual Studio and Visual Studio ALM. I described how you can use the Microsoft Script Control to execute JavaScript on the server. By taking advantage of the Microsoft Script Control, we were able to execute our JavaScript unit tests side-by-side with all of our other unit tests and view the results in the standard Visual Studio Test Results window. You can download the code discussed in this blog entry from here: http://StephenWalther.com/downloads/Blog/JavaScriptUnitTesting/JavaScriptUnitTests.zip Before running this code, you need to first install the Microsoft Script Control which you can download from here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d7e31492-2595-49e6-8c02-1426fec693ac

    Read the article

  • Verbosity Isn’t Always a Bad Thing

    - by PSteele
    There was a message posted to the Rhino.Mocks forums yesterday about verifying a single parameter of a method that accepted 5 parameters.  The code looked like this:   [TestMethod] public void ShouldCallTheAvanceServiceWithTheAValidGuid() { _sut.Send(_sampleInput); _avanceInterface.AssertWasCalled(x => x.SendData( Arg<Guid>.Is.Equal(Guid.Empty), Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything, Arg<string>.Is.Anything)); } Not the prettiest code, but it does work. I was going to reply that he could use the “GetArgumentsForCallsMadeOn” method to pull out an array that would contain all of the arguments.  A quick check of “args[0]” would be all that he needed.  But then Tim Barcz replied with the following: Just to help allay your fears a bit...this verbosity isn't always a bad thing.  When I read the code, based on the syntax you have used I know that for this particular test no parameters matter except the first...extremely useful in my opinion. An excellent point!  We need to make sure our unit tests are as clear as our code. Technorati Tags: Rhino.Mocks,Unit Testing

    Read the article

  • Should mock objects for tests be created at a high or low level

    - by Danack
    When creating unit tests for those other objects, what is the best way to create mock objects that provide data to other objects. Should they be created at a 'high level' and intercept the calls as soon as possible, or should they be done at a 'low level' and so make as much as the real code still be called? e.g. I'm writing a test for some code that requires a NoteMapper object that allows Notes to be loaded from the DB. class NoteMapper { function getNote($sqlQueryFactory, $noteID) { // Create an SQL query from $sqlQueryFactory // Run that SQL // if null // return null // else // return new Note($dataFromSQLQuery) } } I could either mock this object at a high level by creating a mock NoteMapper object, so that there are no calls to the SQL at all e.g. class MockNoteMapper { function getNote($sqlQueryFactory, $noteID) { //$mockData = {'Test Note title', "Test note text" } // return new Note($mockData); } } Or I could do it at a very low level, by creating a MockSQLQueryFactory that instead of actually querying the database just provides mock data back, and passing that to the current NoteMapper object. It seems that creating mocks at a high level would be easier in the short term, but that in the long term doing it at a low level would be more powerful and possibly allow more automation of tests e.g. by recording data in an out of a DB and then replaying that data for tests. Is there a recommended way of creating mocks? Are there any hard and fast rules about which are better, or should they both be used where appropriate?

    Read the article

  • How can I force maven to use my mock version of dependencies during the test phase.

    - by Jayd16
    Hi, so I have a Java application with a that accesses some web services. I want to mock out the appropriate classes so I can just use a few hard coded request/responses and I want maven to seamlessly use them during the tests and ignore them during the final build. I want maven2 to: 1)compile my mock classes 2)compile the main classes that depend on the mocked code 3)run tests 4)recompile any main classes with the real dependencies, not my mocks 5)finish up the maven install Ideally I want to just name my mock classes the same as my main class and just keep them in src/test/mocks or something. I'm kind of new to maven and so far it looks like maven will only compile the src/main and then src/test but I'm hoping I can have my way. Any ideas?

    Read the article

  • Review: Backbone.js Testing

    - by george_v_reilly
    Title: Backbone.js Testing Author: Ryan Roemer Rating: $stars(4.5) Publisher: Packt Copyright: 2013 ISBN: 178216524X Pages: 168 Keywords: programming, testing, javascript, backbone, mocha, chai, sinon Reading period: October 2013 Backbone.js Testing is a short, dense introduction to testing JavaScript applications with three testing libraries, Mocha, Chai, and Sinon.JS. Although the author uses a sample application of a personal note manager written with Backbone.js throughout the book, much of the material would apply to any JavaScript client or server framework. Mocha is a test framework that can be executed in the browser or by Node.js, which runs your tests. Chai is a framework-agnostic TDD/BDD assertion library. Sinon.JS provides standalone test spies, stubs and mocks for JavaScript. They complement each other and the author does a good job of explaining when and how to use each. I've written a lot of tests in Python (unittest and mock, primarily) and C# (NUnit), but my experience with JavaScript unit testing was both limited and years out of date. The JavaScript ecosystem continues to evolve rapidly, with new browser frameworks and Node packages springing up everywhere. JavaScript has some particular challenges in testing—notably, asynchrony and callbacks. Mocha, Chai, and Sinon meet those challenges, though they can't take away all the pain. The author describes how to test Backbone models, views, and collections; dealing with asynchrony; provides useful testing heuristics, including isolating components to reduce dependencies; when to use stubs and mocks and fake servers; and test automation with PhantomJS. He does not, however, teach you Backbone.js itself; for that, you'll need another book. There are a few areas which I thought were dealt with too lightly. There's no real discussion of Test-driven_development or Behavior-driven_development, which provide the intellectual foundations of much of the book. Nor does he have much to say about testability and how to make legacy code more testable. The sample Notes app has plenty of testing seams (much of this falls naturally out of the architecture of Backbone); other apps are not so lucky. The chapter on automation is extremely terse—it could be expanded into a very large book!—but it does provide useful indicators to many areas for exploration. I learned a lot from this book and I have no hesitation in recommending it. Disclosure: Thanks to Ryan Roemer and Packt for a review copy of this book.

    Read the article

  • Tomcat uninstall problems

    - by Deepak
    Hi, I am using "apt-get remove tomcat6" to remove tomcat.It gives this outout and tomcat still running on my system: Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: seamonkey-gnome-support ocaml-base-nox libghc6-hsql-prof libgmp3-dev libffi-dev libtool libghc6-hsql-dev libgmpxx4ldbl ghc6-prof camlp4 ghc6 ledit ocaml-interp rhino libltdl-dev ocaml-nox Use 'apt-get autoremove' to remove them. The following packages will be REMOVED: tomcat6 tomcat6-admin tomcat6-examples 0 upgraded, 0 newly installed, 3 to remove and 1 not upgraded. After this operation, 2,400kB disk space will be freed. Do you want to continue [Y/n]? y Segmentation fault deepak@kalpna-desktop:~$ apt-get remove tomcat6 Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: seamonkey-gnome-support ocaml-base-nox libghc6-hsql-prof libgmp3-dev libffi-dev libtool libghc6-hsql-dev libgmpxx4ldbl ghc6-prof camlp4 ghc6 ledit ocaml-interp rhino libltdl-dev ocaml-nox Use 'apt-get autoremove' to remove them. The following packages will be REMOVED: tomcat6 tomcat6-admin tomcat6-examples 0 upgraded, 0 newly installed, 3 to remove and 1 not upgraded. After this operation, 2,400kB disk space will be freed. Do you want to continue [Y/n]? y Segmentation fault What is the way to re-install tomcat on ubuntu. Regards D

    Read the article

  • How to mock an SqlDataReader using Moq - Update

    - by Simon G
    Hi, I'm new to moq and setting up mocks so i could do with a little help. Title says it all really - how do I mock up an SqlDataReader using Moq? Thanks Update After further testing this is what I have so far: private IDataReader MockIDataReader() { var moq = new Mock<IDataReader>(); moq.Setup( x => x.Read() ).Returns( true ); moq.Setup( x => x.Read() ).Returns( false ); moq.SetupGet<object>( x => x["Char"] ).Returns( 'C' ); return moq.Object; } private class TestData { public char ValidChar { get; set; } } private TestData GetTestData() { var testData = new TestData(); using ( var reader = MockIDataReader() ) { while ( reader.Read() ) { testData = new TestData { ValidChar = reader.GetChar( "Char" ).Value }; } } return testData; } The issue you is when I do reader.Read in my GetTestData() method its always empty. I need to know how to do something like reader.Stub( x => x.Read() ).Repeat.Once().Return( true ) as per the rhino mock example: http://stackoverflow.com/questions/1792984/mocking-a-datareader-and-getting-a-rhino-mocks-exceptions-expectationviolationexc

    Read the article

  • Delphi Mock Wizard

    - by Todd
    Let me preface this by saying I'm fairly new to Unit Testing, Mocks, Stubs, Etc... I've installed Delphi-Mock-Wizard. When I select a unit and "Generate Mock", a new unit is created but it's very basic and not anything what I understand Mocks to be. unit Unit1; (** WARNING - AUTO-GENERATED MOCK! Change this unit if you want to, but be aware that any changes you make will be lost if you regenerate the mock object (for instance, if the interface changes). My advice is to create a descendent class of your auto-generated mock - in a different unit - and override things there. That way you get to keep them. Also, the auto-generate code is not yet smart enough to generate stubs for inherited interfaces. In that case, change your mock declaration to inherit from a mock implementation that implements the missing interface. This, unfortunately, is a violation of the directive above. I'm working on it. You may also need to manually change the unit name, above. Another thing I am working on. **) interface uses PascalMock, TestInterfaces; type IThingy = interface; implementation end. Looking at the source there seems to be quite a bit commented out. I'm wondering, has anyone gotten this to work? My IDE is D2010. Thanks.

    Read the article

  • nhibernate error recovery

    - by Berryl
    I downloaded Rhino Security today and started going through some of the tests. Several that run perfectly in isolation start getting errors after one that purposely raises an exception runs though. Here is that test: [Test] public void EntitesGroup_CanCreate() { var group = _authorizationRepository.CreateEntitiesGroup("Accounts"); _session.Flush(); _session.Evict(group); var fromDb = _session.Get<EntitiesGroup>(group.Id); Assert.NotNull(fromDb); Assert.That(fromDb.Name, Is.EqualTo(group.Name)); } And here are the tests and error messages that fail: [Test] public void User_CanSave() { var ayende = new User {Name = "ayende"}; _session.Save(ayende); _session.Flush(); _session.Evict(ayende); var fromDb = _session.Get<User>(ayende.Id); Assert.That(fromDb, Is.Not.Null); Assert.That(ayende.Name, Is.EqualTo(fromDb.Name)); } ----> System.Data.SQLite.SQLiteException : Abort due to constraint violation column Name is not unique [Test] public void UsersGroup_CanCreate() { var group = _authorizationRepository.CreateUsersGroup("Admininstrators"); _session.Flush(); _session.Evict(group); var fromDb = _session.Get<UsersGroup>(group.Id); Assert.NotNull(fromDb); Assert.That(fromDb.Name, Is.EqualTo(group.Name)); } failed: NHibernate.AssertionFailure : null id in Rhino.Security.Tests.User entry (don't flush the Session after an exception occurs) Does anyone see how I can reset the state of the in memory SQLite db after the first test? I changed the code to use nunit instead of xunit so maybe that is part of the problem here as well. Cheers, Berryl

    Read the article

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