Search Results

Search found 182 results on 8 pages for 'rhino'.

Page 4/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • MVC UI with Mock Controllers?

    - by Jaimal Chohan
    I'm working with Aspnet MVC 2 (R2) and at the same time playing about with the whole alt.net stack. One of this things I would like to be able todo is basically write my Views, and be able to interact with them without having to write the controller logic. E.g. I have a view that displays a list of orders and I can click on an order which redirects to another view where I can edit it, but I don't want to get into the nitty gritty of writing the code to actually get a list of orders, or update an existing ordes. I want to do so I can write UI tests in WaitN/AOT/Selenium without having to worry about whats happening underneath, and also It would help drive my controller logic on a need basis as opposed to guess work based of of the supplied screenshots How do you guys accomplish this atm? Can you provide links ot useful blog posts/tools/framework/articles with information on how to accomplish this p.s. I primarly use Rhino Mocks & NUnit but can happliy change to other tools if they support the above better.

    Read the article

  • Attempted to read or write protected memory

    - by Interfector
    I have a sample ASP.NET MVC 3 web application that is following Jonathan McCracken's Test-Drive Asp.NET MVC (great book , by the way) and I have stumbled upon a problem. Note that I'm using MVCContrib, Rhino and NUnit. [Test] public void ShouldSetLoggedInUserToViewBag() { var todoController = new TodoController(); var builder = new TestControllerBuilder(); builder.InitializeController(todoController); builder.HttpContext.User = new GenericPrincipal(new GenericIdentity("John Doe"), null); Assert.That(todoController.Index().AssertViewRendered().ViewData["UserName"], Is.EqualTo("John Doe")); } The code above always throws this error: System.AccessViolationException : Attempted to read or write protected memory. This is often an indication that other memory is corrupt. The controller action code is the following: [HttpGet] public ActionResult Index() { ViewData.Model = Todo.ThingsToBeDone; ViewBag.UserName = HttpContext.User.Identity.Name; return View(); } From what I have figured out, the app seems to crash because of the two assignements in the controller action. However, I cannot see how there are wrong!? Can anyone help me pinpoint the solution to this problem. Thank you.

    Read the article

  • 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

  • What is the best testing pattern for checking that parameters are being used properly?

    - by Joseph
    I'm using Rhino Mocks to try to verify that when I call a certain method, that the method in turn will properly group items and then call another method. Something like this: //Arrange var bucketsOfFun = new BucketGame(); var balls = new List<IBall> { new Ball { Color = Color.Red }, new Ball { Color = Color.Blue }, new Ball { Color = Color.Yellow }, new Ball { Color = Color.Orange }, new Ball { Color = Color.Orange } }; //Act bucketsOfFun.HaveFunWithBucketsAndBalls(balls); //Assert ??? Here is where the trouble begins for me. My method is doing something like this: public void HaveFunWithBucketsAndBalls(IList<IBall> balls) { //group all the balls together according to color var blueBalls = GetBlueBalls(balls); var redBalls = GetRedBalls(balls); // you get the idea HaveFunWithABucketOfBalls(blueBalls); HaveFunWithABucketOfBalls(redBalls); // etc etc with all the different colors } public void HaveFunWithABucketOfBalls(IList<IBall> colorSpecificBalls) { //doing some stuff here that i don't care about //for the test i'm writing right now } What I want to assert is that each time I call HaveFunWithABucketOfBalls that I'm calling it with a group of 1 red ball, then 1 blue ball, then 1 yellow ball, then 2 orange balls. If I can assert that behavior then I can verify that the method is doing what I want it to do, which is grouping the balls properly. Any ideas of what the best testing pattern for this would be?

    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

  • Need help mocking a ASP.NET Controller in RhinoMocks

    - by Pure.Krome
    Hi folks, I'm trying to mock up a fake ASP.NET Controller. I don't have any concrete controllers, so I was hoping to just mock a Controller and it will work. This is what I have, currently. _fakeRequestBase = MockRepository.GenerateMock<HttpRequestBase>(); _fakeRequestBase.Stub(x => x.HttpMethod).Return("GET"); _fakeContextBase = MockRepository.GenerateMock<HttpContextBase>(); _fakeContextBase.Stub(x => x.Request).Return(_fakeRequestBase); var controllerContext = new ControllerContext(_fakeContextBase, new RouteData(), MockRepository.GenerateMock<ControllerBase>()); _fakeController = MockRepository.GenerateMock<Controller>(); _fakeController.Stub(x => x.ControllerContext).Return(controllerContext); Everything works except the last line, which throws a runtime error and is asking me for some Rhino.Mocks source code or something (which I don't have). See how I'm trying to mock up an abstract Controller - is that allowed? Can someone help me?

    Read the article

  • Mocking objects with complex Lambda Expressions as parameters

    - by iCe
    Hi there, I´m encountering this problem trying to mock some objects that receive complex lambda expressions in my projects. Mostly with with proxy objects that receive this type of delegate: Func<Tobj, Fun<TParam1, TParam2, TResult>> I have tried to use Moq as well as RhinoMocks to acomplish mocking those types of objects, however both fail. (Moq fails with NotSupportedException, and in RhinoMocks simpy does not satisgy expectation). This is simplified example of what I´m trying to do: I have a Calculator object that does calculations: public class Calculator { public Calculator() { } public int Add(int x, int y) { var result = x + y; return result; } public int Substract(int x, int y) { var result = x - y; return result; } } I need to validate parameters on every method in the Calculator class, so to keep with the Single Responsability principle, I create a validator class. I wire everything up using a Proxy class, that prevents having duplicate code: public class CalculatorProxy : CalculatorExample.ICalculatorProxy { private ILimitsValidator _validator; public CalculatorProxy(Calculator _calc, ILimitsValidator _validator) { this.Calculator = _calc; this._validator = _validator; } public int Operation(Func&lt;Calculator, Func&lt;int, int, int&gt;&gt; operation, int x, int y) { _validator.ValidateArgs(x, y); var calcMethod = operation(this.Calculator); var result = calcMethod(x, y); _validator.ValidateResult(result); return result; } public Calculator Calculator { get; private set; } } Now, I´m testing a component that does use the CalculatorProxy, so I want to mock it, for example using Rhino Mocks: [TestMethod] public void ParserWorksWithCalcultaroProxy() { var calculatorProxyMock = MockRepository.GenerateMock&lt;ICalculatorProxy&gt;(); calculatorProxyMock.Expect(x =&gt; x.Calculator).Return(_calculator); calculatorProxyMock.Expect(x =&gt; x.Operation(c =&gt; c.Add, 2, 2)).Return(4); var mathParser = new MathParser(calculatorProxyMock); mathParser.ProcessExpression("2 + 2"); calculatorProxyMock.VerifyAllExpectations(); } However I cannot get it to work! Any ideas about how this can be done? Thanks a lot!

    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

  • How to test if raising an event results in a method being called conditional on value of parameters

    - by MattC
    I'm trying to write a unit test that will raise an event on a mock object which my test class is bound to. What I'm keen to test though is that when my test class gets it's eventhandler called it should only call a method on certain values of the eventhandlers parameters. My test seems to pass even if I comment the code that calls ProcessPriceUpdate(price); I'm in VS2005 so no lambdas please :( So... public delegate void PriceUpdateEventHandler(decimal price); public interface IPriceInterface{ event PriceUpdateEventHandler PriceUpdate; } public class TestClass { IPriceInterface priceInterface = null; TestClass(IPriceInterface priceInterface) { this.priceInterface = priceInterface; } public void Init() { priceInterface.PriceUpdate += OnPriceUpdate; } public void OnPriceUpdate(decimal price) { if(price > 0) ProcessPriceUpdate(price); } public void ProcessPriceUpdate(decimal price) { //do something with price } } And my test so far :s public void PriceUpdateEvent() { MockRepository mock = new MockRepository(); IPriceInterface pi = mock.DynamicMock<IPriceInterface>(); TestClass test = new TestClass(pi); decimal prc = 1M; IEventRaiser raiser; using (mock.Record()) { pi.PriceUpdate += null; raiser = LastCall.IgnoreArguments().GetEventRaiser(); Expect.Call(delegate { test.ProcessPriceUpdate(prc); }).Repeat.Once(); } using (mock.Playback()) { test.Init(); raiser.Raise(prc); } }

    Read the article

  • Do we really need isolation frameworks to create stubs?

    - by Sandbox
    I have read this: http://martinfowler.com/articles/mocksArentStubs.html My concepts about a stub and a mock are clear. I understand the need of isolation frameworks like moq, rhinomocks and like to create a mock object. As mocks, participate in actual verfication of expectations. But why do we need these frameworks to create stubs. I would rather prefer rolling out a hand created stub and use it in various fixtures.

    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

  • 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

  • What is wrong with Stubs for unit testing?

    - by MatthewMartin
    I just watched this funny YouTube Video about unit testing (it's Hitler with fake subtitles chewing out his team for not doing good unit tests--skip it if you're humor impaired) where stubs get roundly criticized. But I don't understand what wrong with stubs. I haven't started using a mocking framework and I haven't started feeling the pain from not using one. Am I in for a world a hurt sometime down the line, having chosen handwritten stubs and fakes instead of mocks (like Rhinomock etc)? (using Fowler's taxonomy) What are the considerations for picking between a mock and handwritten stub?

    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

  • 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

  • RhinoMocks: how to test if method was called when using PartialMock

    - by epitka
    I have a clas that is something like this public class MyClass { public virtual string MethodA(Command cmd) { //some code here} public void MethodB(SomeType obj) { // do some work MethodA(command); } } I mocked MyClass as PartialMock (mocks.PartialMock<MyClass>) and I setup expectation for MethodA var cmd = new Command(); //set the cmd to expected state Expect.Call(MyClass.MethodA(cmd)).Repeat.Once(); Problem is that MethodB calls actual implementation of MethodA instead of mocking it up. I must be doing something wrong (not very experienced with RhinoMocks). How do I force it to mock MetdhodA? Here is the actual code: var cmd = new SetBaseProductCoInsuranceCommand(); cmd.BaseProduct = planBaseProduct; var insuredType = mocks.DynamicMock<InsuredType>(); Expect.Call(insuredType.Code).Return(InsuredTypeCode.AllInsureds); cmd.Values.Add(new SetBaseProductCoInsuranceCommand.CoInsuranceValues() { CoInsurancePercent = 0, InsuredType = insuredType, PolicySupplierType = ppProvider }); Expect.Call(() => service.SetCoInsurancePercentages(cmd)).Repeat.Once(); mocks.ReplayAll(); //act service.DefaultCoInsurancesFor(planBaseProduct); //assert service.AssertWasCalled(x => x.SetCoInsurancePercentages(cmd),x=>x.Repeat.Once());

    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

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >