Search Results

Search found 2706 results on 109 pages for 'jason mock'.

Page 10/109 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How do I mock/fake/replace/stub a base class at unit-test time in C#?

    - by MatthewMartin
    UPDATE: I've changed the wording of the question. Previously it was a yes/no question about if a base class could be changed at runtime. I may be working on mission impossible here, but I seem to be getting close. I want to extend a ASP.NET control, and I want my code to be unit testable. Also, I'd like to be able to fake behaviors of a real Label (namely things like ID generation, etc), which a real Label can't do in an nUnit host. Here a working example that makes assertions on something that depends on a real base class and something that doesn't-- in a more realistic unit test, the test would depend on both --i.e. an ID existing and some custom behavior. Anyhow the code says it better than I can: public class LabelWrapper : Label //Runtime //public class LabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } //Ugh, now I have to test FakeLabelWrapper public class FakeLabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } [TestFixture] public class UnitTest { [Test] public void Test() { //Wish this was LabelWrapper label = new LabelWrapper(new FakeBase()) LabelWrapper label = new LabelWrapper(); //FakeLabelWrapper label = new FakeLabelWrapper(); label.Text = "ToUpper"; Assert.AreEqual("TOUPPER",label.Text); StringWriter stringWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(stringWriter); label.RenderControl(writer); Assert.AreEqual(1,label.ID); Assert.AreEqual("<span>TOUPPER</span>", stringWriter.ToString()); } } public class FakeLabel { virtual public string Text { get; set; } public void RenderControl(TextWriter writer) { writer.Write("<span>" + Text + "</span>"); } } //System Under Test internal class LabelLogic { internal string ProcessGetText(string value) { return value.ToUpper(); } internal string ProcessSetText(string value) { return value.ToUpper(); } }

    Read the article

  • Is there a way to set the value of $? in a mock in Ruby?

    - by rleber
    I am testing some scripts that interface with system commands. Their logic depends on the return code of the system commands, i.e. the value of $?. So, as a simplified example, the script might say: def foo(command) output=`#{command}` if $?==0 'succeeded' else 'failed' end end In order to be able to test these methods properly, I would like to be able to stub out the Kernel backquote call, and set $? to an arbitrary value, to see if I get appropriate behavior from the logic in the method after the backquote call. I can't figure out a way to do this. (In case it matters, I'm testing using Test::Unit and Mocha.)

    Read the article

  • Using Moq to Validate Separate Invocations with Distinct Arguments

    - by Thermite
    I'm trying to validate the values of arguments passed to subsequent mocked method invocations (of the same method), but cannot figure out a valid approach. A generic example follows: public class Foo { [Dependency] public Bar SomeBar { get; set; } public void SomeMethod() { this.SomeBar.SomeOtherMethod("baz"); this.SomeBar.SomeOtherMethod("bag"); } } public class Bar { public void SomeOtherMethod(string input) { } } public class MoqTest { [TestMethod] public void RunTest() { Mock<Bar> mock = new Mock<Bar>(); Foo f = new Foo(); mock.Setup(m => m.SomeOtherMethod(It.Is<string>("baz"))); mock.Setup(m => m.SomeOtherMethod(It.Is<string>("bag"))); // this of course overrides the first call f.SomeMethod(); mock.VerifyAll(); } } Using a Function in the Setup might be an option, but then it seems I'd be reduced to some sort of global variable to know which argument/iteration I'm verifying. Maybe I'm overlooking the obvious within the Moq framework?

    Read the article

  • Library to fake intermittent failures according to tester-defined policy?

    - by crosstalk
    I'm looking for a library that I can use to help mock a program component that works only intermittently - usually, it works fine, but sometimes it fails. For example, suppose I need to read data from a file, and my program has to avoid crashing or hanging when a read fails due to a disk head crash. I'd like to model that by having a mock data reader function that returns mock data 90% of the time, but hangs or returns garbage otherwise. Or, if I'm stress-testing my full program, I could turn on debugging code in my real data reader module to make it return real data 90% of the time and hang otherwise. Now, obviously, in this particular example I could just code up my mock manually to test against a random() routine. However, I was looking for a system that allows implementing any failure policy I want, including: Fail randomly 10% of the time Succeed 10 times, fail 4 times, repeat Fail semi-randomly, such that one failure tends to be followed by a burst of more failures Any policy the tester wants to define Furthermore, I'd like to be able to change the failure policy at runtime, using either code internal to the program under test, or external knobs or switches (though the latter can be implemented with the former). In pig-Java, I'd envision a FailureFaker interface like so: interface FailureFaker { /** Return true if and only if the mocked operation succeeded. Implementors should override this method with versions consistent with their failure policy. */ public boolean attempt(); } And each failure policy would be a class implementing FailureFaker; for example there would be a PatternFailureFaker that would succeed N times, then fail M times, then repeat, and a AlwaysFailFailureFaker that I'd use temporarily when I need to simulate, say, someone removing the external hard drive my data was on. The policy could then be used (and changed) in my mock object code like so: class MyMockComponent { FailureFaker faker; public void doSomething() { if (faker.attempt()) { // ... } else { throw new RuntimeException(); } } void setFailurePolicy (FailureFaker policy) { this.faker = policy; } } Now, this seems like something that would be part of a mocking library, so I wouldn't be surprised if it's been done before. (In fact, I got the idea from Steve Maguire's Writing Solid Code, where he discusses this exact idea on pages 228-231, saying that such facilities were common in Microsoft code of that early-90's era.) However, I'm only familiar with EasyMock and jMockit for Java, and neither AFAIK have this function, or something similar with different syntax. Hence, the question: Do such libraries as I've described above exist? If they do, where have you found them useful? If you haven't found them useful, why not?

    Read the article

  • RSpec mocking a nested model in Rails - ActionController problem

    - by emson
    Hi All I am having a problem in RSpec when my mock object is asked for a URL by the ActionController. The URL is a Mock one and not a correct resource URL. I am running RSpec 1.3.0 and Rails 2.3.5 Basically I have two models. Where a subject has many notes. class Subject < ActiveRecord::Base validates_presence_of :title has_many :notes end class Note < ActiveRecord::Base validates_presence_of :title belongs_to :subject end My routes.rb file nests these two resources as such: ActionController::Routing::Routes.draw do |map| map.resources :subjects, :has_many => :notes end The NotesController.rb file looks like this: class NotesController < ApplicationController # POST /notes # POST /notes.xml def create @subject = Subject.find(params[:subject_id]) @note = @subject.notes.create!(params[:note]) respond_to do |format| format.html { redirect_to(@subject) } end end end Finally this is my RSpec spec which should simply post my mocked objects to the NotesController and be executed... which it does: it "should create note and redirect to subject without javascript" do # usual rails controller test setup here subject = mock(Subject) Subject.stub(:find).and_return(subject) notes_proxy = mock('association proxy', { "create!" => Note.new }) subject.stub(:notes).and_return(notes_proxy) post :create, :subject_id => subject, :note => { :title => 'note title', :body => 'note body' } end The problem is that when the RSpec post method is called. The NotesController correctly handles the Mock Subject object, and create! the new Note object. However when the NoteController#Create method tries to redirect_to I get the following error: NoMethodError in 'NotesController should create note and redirect to subject without javascript' undefined method `spec_mocks_mock_url' for #<NotesController:0x1034495b8> Now this is caused by a bit of Rails trickery that passes an ActiveRecord object (@subject, in our case, which isn't ActiveRecord but a Mock object), eventually to url_for who passes all the options to the Rails' Routing, which then determines the URL. My question is how can I mock Subject so that the correct options are passed so that I my test passes. I've tried passing in :controller = 'subjects' options but no joy. Is there some other way of doing this? Thanks...

    Read the article

  • IE6 the last three characters in a div are being repeated else where in the page? really weird

    - by Jason
    Hey, Basically i have an issues (in IE6) where the last three characters of a line of text in a div are being repeated further down the page even though they are only in the HTML once. http://www.disturbmedia.com/jason/test/ please see the numbers in black, its always the last three characters that get repeated, so strange. I have never seen this before, its only in IE6? Anyone have any info?! Am super confused as to how this is happening. Thanks Jason

    Read the article

  • After passing a reference to an method, any mods using that reference are not visible outside the me

    - by Jason
    I am passing the reference of name to *mod_name*, I modify the referenced object from within the method but the change is not visible outside of the method, if I am referring to the same object from all locations how come the value is different depending on where I reference it? name = "Jason" puts name.object_id #19827274 def mod_name(name) puts name.object_id #19827274 name = "JasonB" end puts name.object_id #19827274 puts name #Jason String might be a bad example, but I get the same result even if I use a Fixnum.

    Read the article

  • Which Folders To Include In backup?

    - by Jason
    I'm quite new to Ubuntu and want to create a backup. I'm really not sure what files and folders to include so that if I restore my system it will be as it is now. I can't seem to find good details of this anywhere. Hopefully someone could help me with this. Is it possible to backup everything as it is now so in the event of a system restore I don't have to reinstall programs and settings? Thanks, Jason

    Read the article

  • Silverlight Cream for May 02, 2010 -- #854

    - by Dave Campbell
    In this Issue: Michael Washington, Jason Young(-2-, -3-), Phil Middlemiss, Jeremy Likness, Victor Gaudioso, Kunal Chowdhury, Antoni Dol, and Jacek Ciereszko(-2-). Shoutout: Victor Gaudioso has aggregated All of My Silverlight Video Tutorials in One Place (revised again 05.02.10) From SilverlightCream.com: Unit Testing A Silverlight 'Simplified MVVM' Modal Popup Michael Washington's latest 'Simplified MVVM' post is published at The Code Project and is on Unit Testing with MVVM. Input Localization in Silverlight without IValueConverter Jason Young sent me some links to posts I've not seen... this first one is on localization by using the Language property of the Root Visual. MVVM – The Model - Part 1 – INotifyPropertyChanged Jason Young's next archive post is the first of a series on MVVM and Silverlight 4 ... implementing a simple ViewModel base class. Silverlight, WCF, and ASP.Net Configuration Gotchas Jason Young worked at tracking down the answers to some forum questions and in the process has produced a post of 'gotchas' with using WCF in Silverlight. A Chrome and Glass Theme - Part 5 Phil Middlemiss has part 5 of his Chrome and Glass Theme tutorial up ... in this one, he's looking at the Progress Bar and Slider. Download the files and play along. Silverlight Out of Browser (OOB) Versions, Images, and Isolated Storage Jeremy Likness has a post up responding to his 3 major questions about OOB apps, and he has to code up for the sample too. New Silverlight Video Tutorial: How to Make a Slide In/Out Navigation Bar – All in Blend Victor Gaudioso's latest video tutorial is on building a Behavior for a Slide in/out Navigation bar... kinda like the menu sliders on my GlyphMap Utility... only easier! Command Binding in Silverlight 4 (Step-by-Step) Kunal Chowdhury has another post up at DotNetFunda, and this time he's talking about Command Binding in Silverlight 4 with an eye toward MVVM usage. The Silverlight PageCurl implementation Antoni Dol has a post up about doing a Page Curl effect in Silverlight. He has a manual up on the effect and full application code. How to center and scale Silverlight applications using ViewBox control Jacek Ciereszko has a couple posts up about centering and scaling your app with the ViewBox control. This first one is a code solution. Source is available, as is a Polish version. Silverlight Center And Scale Behavior Jacek Ciereszko's 2nd post, he provides a Behavior that handles the scaling and centering of the previous post. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Silverlight Cream for December 29, 2010 -- #1018

    - by Dave Campbell
    In this Issue: Arik Poznanski, Derik Whittaker(-2-), Alex Knight, Maurice de Beijer, Jesse Liberty, Jason Ginchereau, Jeff Blankenburg, Mike Snow, and Peter Kuhn. Above the Fold: Silverlight: "Silverlight: Reading from a File Contained in your XAP" Mike Snow WP7: "A ReorderListBox for Windows Phone 7" Jason Ginchereau Expression Blend: "PathListBox: making rockin' animations" Alex Knight From SilverlightCream.com: Order in Chaos: Dependency Property Value Resolution Arik Poznanski sent me the link to his blog with this Dependency property value resolution post which demonstrates in successive detail xaml for each of the scenarios. Closing the Virtual Keyboard (SIP) and forcing binding in WP7 Derik Whittaker has a couple new posts up... this first is about how to close the SIP and forcing binding in a WP7 app... if you've run many WP7 apps I'm sure you understand the issue. Help my Slider control does not work inside a Grid in WP7 In Derik Whittaker's next post he details a problem he had with a Slider in a Grid that went AWOL... and how he resolved it.. also is asking why the solution works. PathListBox: making rockin' animations Holy Crap ... Alex Knight has his second PathListBox tutorial up and just stop reading and go check it out... dang! ... I'll still be here when you come back! Windows Phone 7, Animations and Data Binding Maurice de Beijer details an interesting problem he ran into where his databinding was hampering a page animation, what the root problem was and how he resolved it.. good information. Windows Phone From Scratch – Navigation Jesse Liberty has the next episode in the Windows Phone from Scratch series up and is talking about Navigation... he demos an ap with 3 pages and simple navigation this time. A ReorderListBox for Windows Phone 7 Found in Jeff Blankenburg's number 11, this post by Jason Ginchereau is a description of a Drag/Drop reodering ListBox drop-in for WP7 ... very cool, and source is on the post. What I Learned In WP7 – #Issue 11 Jeff Blankenburg's number 11 is a couple links itself... one to Jeff Wilcox for Silverlight UnitTest Framework, and one to Jason Ginchereau for Listbox Drag/Drop reordering... going to have to look that one up. Silverlight: Reading from a File Contained in your XAP Mike Snow's latest is on how to load up an extraneous file into your xap for loading at run-time and how to get that to actually work. XNA: Sophisticated primitives Peter Kuhn has a post up on using the XNA PrimitiveBatch class... he had trouble with it at first, and explains how to use it. XNA you say? ... think WP7. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • NYC Silverlight FireStarter - June 5th 2010 at the NYC Microsoft Office

    - by Sam Abraham
    On Saturday June 5th, 2010, I spent my Saturday morning at the NYC Silverlight FireStarter. Presenting was Peter Laudati from Microsoft and Jason Beres, Matt Van Horn and Todd Snyder from Infragistics. I watched the Simulcast for the morning sessions as I was tied up with some work, but ended up finally making it to the Microsoft Office and had the opportunity to attend the last hour of the event in person.   For me, the quality of the Simulcast was as good as in-person attendance so far as sound/video quality and the interaction with speakers. In the background was a screen with tweets from remote attendees asking questions or commenting on the presentations. Presenters did periodically stop to answer the tweeted questions as well as questions from attendees. Only thing I missed was getting my hands on some of that swag that was (literally) flying in the air at the event floor.   Upon my arrival at the Microsoft Office Location in NYC, I spoke with Rachel Appel and Peter Laudati asking for permission to take a few photos to record the outstanding effort that took place in putting this event together. Both agreed and I started with putting my photography skills to work.   You can always gauge the quality of an event with the number of its attendees who opt to stay till the last minute as well as the level of interaction of the audience with the speaker. With most of the FireStarter attendees remaining till the very end of the talk, and with the many questions that were asked, one can simply judge the event as a success as per my aforementioned criteria.   Evaluation forms were passed around and Peter strongly encouraged the audience to openly speak their mind as they record their comments. I didn't get to submit my evaluation as I was busy recording the event in photos, so here it goes: I believe that lots of hard work was put into making this event a reality. Quality of speakers, topics and level of Geekiness at the event was outstanding.  Overall, aside from a minor issue with Lunch delivery time, this event was of high quality and I am very sure everyone's evaluation will be in line with my analysis of it being a great success. Below are a few photos of the event.   --Sam Abraham Site Director - West Palm Beach .Net User Group www.Fladotnet.com     NYC Silverlight FireStarter Speakers - From Left to right: Peter Laudati, Todd Snyder, Matt Van Horn & Jason Beres   As jason wasn't quiet visible in the above photo, a closeup was taken (It was Jason's birthday and he had to leave a bit early, so the Infagisticts team thought outside the box...)     Full Room - That was at the last hour of the event   Another view of full room   Discussions during the break   End-of-event Raffle

    Read the article

  • Implementing a modern web application with Web API on top of old services

    - by Gaui
    My company has many WCF services which may or may not be replaced in the near future. The old web application is written in WebForms and communicates straight with these services via SOAP and returns DataTables. Now I am designing a new modern web application in a modern style, an AngularJS client which communicates with an ASP.NET Web API via JSON. The Web API then communicates with the WCF services via SOAP. In the future I want to let the Web API handle all requests and go straight to the database, but because the business logic implemented in the WCF services is complicated it's going to take some time to rewrite and replace it. Now to the problem: I'm trying to make it easy in the near future to replace the WCF services with some other data storage, e.g. another endpoint, database or whatever. I also want to make it easy to unit test the business logic. That's why I have structured the Web API with a repository layer and a service layer. The repository layer has a straight communication with the data storage (WCF service, database, or whatever) and the service layer then uses the repository (Dependency Injection) to get the data. It doesn't care where it gets the data from. Later on I can be in control and structure the data returned from the data storage (DataTable to POCO) and be able to test the logic in the service layer with some mock repository (using Dependency Injection). Below is some code to explain where I'm going with this. But my question is, does this all make sense? Am I making this overly complicated and could this be simplified in any way possible? Does this simplicity make this too complicated to maintain? My main goal is to make it as easy as possible to switch to another data storage later on, e.g. an ORM and be able to test the logic in the service layer. And because the majority of the business logic is implemented in these WCF services (and they return DataTables), I want to be in control of the data and the structure returned to the client. Any advice is greatly appreciated. Update 20/08/14 I created a repository factory, so services would all share repositories. Now it's easy to mock a repository, add it to the factory and create a provider using that factory. Any advice is much appreciated. I want to know if I'm making things more complicated than they should be. So it looks like this: 1. Repository Factory public class RepositoryFactory { private Dictionary<Type, IServiceRepository> repositories; public RepositoryFactory() { this.repositories = new Dictionary<Type, IServiceRepository>(); } public void AddRepository<T>(IServiceRepository repo) where T : class { if (this.repositories.ContainsKey(typeof(T))) { this.repositories.Remove(typeof(T)); } this.repositories.Add(typeof(T), repo); } public dynamic GetRepository<T>() { if (this.repositories.ContainsKey(typeof(T))) { return this.repositories[typeof(T)]; } throw new RepositoryNotFoundException("No repository found for " + typeof(T).Name); } } I'm not very fond of dynamic but I don't know how to retrieve that repository otherwise. 2. Repository and service // Service repository interface // All repository interfaces extend this public interface IServiceRepository { } // Invoice repository interface // Makes it easy to mock the repository later on public interface IInvoiceServiceRepository : IServiceRepository { List<Invoice> GetInvoices(); } // Invoice repository // Connects to some data storage to retrieve invoices public class InvoiceServiceRepository : IInvoiceServiceRepository { public List<Invoice> GetInvoices() { // Get the invoices from somewhere // This could be a WCF, a database, or whatever using(InvoiceServiceClient proxy = new InvoiceServiceClient()) { return proxy.GetInvoices(); } } } // Invoice service // Service that handles talking to a real or a mock repository public class InvoiceService { // Repository factory RepositoryFactory repoFactory; // Default constructor // Default connects to the real repository public InvoiceService(RepositoryFactory repo) { repoFactory = repo; } // Service function that gets all invoices from some repository (mock or real) public List<Invoice> GetInvoices() { // Query the repository return repoFactory.GetRepository<IInvoiceServiceRepository>().GetInvoices(); } }

    Read the article

  • How can I Setup overloaded method invocations in Moq?

    - by arootbeer
    I'm trying to mock a mapping interface IMapper: public interface IMapper<TFoo, TBar> { TBar Map(TFoo foo); TFoo Map(TBar bar); } In my test, I'm setting the mock mapper up to expect an invocation of each (around an NHibernate update operation): //... _mapperMock.Setup(m => m.Map(fooMock.Object)).Returns(barMock.Object); _mapperMock.Setup(m => m.Map(barMock.Object)).Returns(fooMock.Object); //... However, when the second Map invocation is made, the mapper mock throws because it is only expecting a single invocation. Watching the mapper mock during setup at runtime, I can look see the Map(TFoo foo) overload get registered, and then see it get replaced when the Map(TBar bar) overload is set up. Is this a problem with the way Moq handles setup, or is there a different syntax I need to use in this case?

    Read the article

  • Verifying method with array passed by reference using Moq

    - by kaa
    Given the following interface public interface ISomething { void DoMany(string[] strs); void DoManyRef(ref string[] strs); } I would like to verify that the DoManyRef method is called, and passed any string array as the strs parameter. The following test fails: public void CanVerifyMethodsWithArrayRefParameter() { var a = new Mock<ISomething>().Object; var strs = new string[0]; a.DoManyRef(ref strs); var other = It.IsAny<string[]>(); Mock.Get(a).Verify(t => t.DoManyRef(ref other)); } While the following not requiring the array passed by reference passes: public void CanVerifyMethodsWithArrayParameter() { var a = new Mock<ISomething>().Object; a.DoMany(new[] { "a", "b" }); Mock.Get(a).Verify(t => t.DoMany(It.IsAny<string[]>())); } I am not able to change the interface to eliminate the by reference requirement.

    Read the article

  • How can I use OCMock to verify that a method is never called?

    - by Justin Voss
    At my day job I've been spoiled with Mockito's never() verification, which can confirm that a mock method is never called. Is there some way to accomplish the same thing using Objective-C and OCMock? I've been using the code below, which works but it feels like a hack. I'm hoping there's a better way... - (void)testSomeMethodIsNeverCalled { id mock = [OCMockObject mockForClass:[MyObject class]]; [[[mock stub] andCall:@selector(fail) onObject:self] forbiddenMethod]; // more test things here, which hopefully // never call [mock forbiddenMethod]... } - (void)fail { STFail(@"This method is forbidden!"); }

    Read the article

  • Using Moq at Blend design time

    - by adrian hara
    This might be a bit out there, but suppose I want to use Moq in a ViewModel to create some design time data, like so: public class SomeViewModel { public SomeViewModel(ISomeDependency dependency) { if (IsInDesignMode) { var mock = new Mock<ISomeDependency>(); dependency = mock.Object; // this throws! } } } The mock could be set up to do some stuff, but you get the idea. My problem is that at design-time in Blend, this code throws an InvalidCastException, with the message along the lines of "Unable to cast object of type 'Castle.Proxies.ISomeDependencyProxy2b3a8f3188284ff0b1129bdf3d50d3fc' to type 'ISomeDependency'." While this doesn't necessarily look to be Moq related but Castle related, I hope the Moq example helps ;) Any idea why that is? Thanks!

    Read the article

  • PowerMock Mockito static methods

    - by anergy
    Do we need to mock all static methods of a class when using PowerMock (with Mockito)? I mean, suppose we have: class MockMe { public static MockMe getInstance(){ //return new Instance via complex process; } public static List<X> anotherStaticMethod(){ // does xyz } } My question, if I need to mock getInstance method, is it necessary to mock "anotherStaticMethod" as well? PowerMock version:1.3, Mockito version:1.8

    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

  • Missing libcurl.so.3 on updating tp PHP 5.2.13

    - by exentric
    Hi, I am trying to update my PHP to 5.2.13 however when I tried running yum update, it gives me this dependency error. php-5.2.13-jason.1.i386 from utterramblings has depsolving problems --> Missing Dependency: libcurl.so.3 is needed by package php-5.2.13-jason.1.i386 (utterramblings) Error: Missing Dependency: libcurl.so.3 is needed by package php-cli-5.2.13-jason.1.i386 (utterramblings) Error: Missing Dependency: libcurl.so.3 is needed by package php-5.2.13-jason.1.i386 (utterramblings) I believe this problem has been caused by my updating libcurl some time ago (to version 7.16.4-8.el5) but I have no idea how to solve this dependency issue. Some time ago my friend asked me regarding missing libcurl.so.3 as well on running some script. Can't say I remember what but he did say he managed to solved it (at least on his end) so I paid no attention to the libcurl.so.3 issue anymore. But now when I try to update my PHP, this problem arises again. This however does indeed exist (and presumably what solved my friend's issue): /usr/lib/libcurl.so.3 Any thoughts on this matter? I'm using centOS 5.3, PHP 5.2.11 and on LightTPD. -Regards

    Read the article

  • mocking superclass protected variable using jmockit

    - by shashi
    Hi, I couldnt able to mock the protected varibale defined in the superclass.i could able to mock the protected method in superclass but couldnt to mock the protected variable in to the subclass ,wherein am writing the testcase for subclass,Please if anybody out there has any soluton for it .please reply. Thanks Shashi

    Read the article

  • Unit Testing functions within repository interfaces - ASP.net MVC3 & Moq

    - by RawryLions
    I'm getting into writing unit testing and have implemented a nice repository pattern/moq to allow me to test my functions without using "real" data. So far so good.. However.. In my repository interface for "Posts" IPostRepository I have a function: Post getPostByID(int id); I want to be able to test this from my Test class but cannot work out how. So far I am using this pattern for my tests: [SetUp] public void Setup() { mock = new Mock<IPostRepository>(); } [Test] public void someTest() { populate(10); //This populates the mock with 10 fake entries //do test here } In my function "someTest" I want to be able to call/test the function GetPostById. I can find the function with mock.object.getpostbyid but the "object" is null. Any help would be appreciated :) iPostRepository: public interface IPostRepository { IQueryable<Post> Posts {get;} void SavePost(Post post); Post getPostByID(int id); }

    Read the article

  • Jmockit in JBoss

    - by Filip
    In a jboss service I need to mock some inner class (not EJB) with JMockit. Just for tests I've created inner class ToBeMocked and another one Mock. While deploying to jboss I get error NoClassDefFoundError in line: Mockit.setUpMock(ToBeMocked.class, new Mock()); with message: java.lang.NoClassDefFoundError: mockit/Mockit jmockit.jar is added to the classpath in jboss_service.xml. Any ideas?

    Read the article

  • Simple Moq ? - Problem with .Verify

    - by user127954
    Hi, just a simple question here. I've used Moq for awhile but, as of yet, have only used it for stubbing and not for mocking. I am trying to introduce our developers to unit testing. I set up a simple example to explain the concepts but i can't seem to get it working. Probably something simple so i thought i would just ask you all to see what i'm doing wrong: <Test()> _ Public Sub Divide_DivideByZero_LogsError() Dim mock = New Mock(Of ILogger) With mock Dim calc = New MyCalculator(New CalculatorData, .Object) calc.Divide(55, 0) mock.Object.WriteError("test", "Test") .Verify(Function(x) CType(x,ILogger).WriteError(it.IsAny(of String),It.IsAny(Of String)))) End With End Sub I'm using Moq version 3.2.416.3. I get an error on the .verify telling me that i'm calling it with incorrect arguments. I'm just trying to verify that .WriteError was called. any help would be appreciated.

    Read the article

  • Need help with writing test

    - by London
    I'm trying to write a test for this class its called Receiver : public void get(People person) { if(null != person) { LOG.info("Person with ID " + person.getId() + " received"); processor.process(person); }else{ LOG.info("Person not received abort!"); } } Here is the test : @Test public void testReceivePerson(){ context.checking(new Expectations() {{ receiver.get(person); atLeast(1).of(person).getId(); will(returnValue(String.class)); }}); } Note: receiver is the instance of Receiver class(real not mock), processor is the instance of Processor class(real not mock) which processes the person(mock object of People class). GetId is a String not int method that is not mistake. Test fails : unexpected invocation of person.getId() I'm using jMock any help would be appreciated. As I understood when I call this get method to execute it properly I need to mock person.getId() , and I've been sniping around in circles for a while now any help would be appreciated.

    Read the article

  • Test MVC using moq

    - by Raminder
    I am new to moq and I was trying to test a controller (MVC) behaviour that when the view raises a certain event, controller calls a certain function on model, here are the classes - public class Model { public void CalculateAverage() { ... } ... } public class View { public event EventHandler CalculateAverage; private void RaiseCalculateAverage() { if (CalculateAverage != null) { CalculateAverage(this, EventArgs.Empty); } } ... } public class Controller { private Model model; private View view; public Controller(Model model, View view) { this.model = model this.view = view; view.CalculaeAverage += view_CalculateAverage; } priavate void view_CalculateAverage(object sender, EventArgs args) { model.CalculateAverage(); } } and the test - [Test] public void ModelCalculateAverageCalled() { Mock<Model> modelMock = new Mock<Model>(); Mock<View> viewMock = new Mock<View>(); Controller controller = new Controller(modelMock.Object, viewMock.Object); viewMock.Raise(x => x.CalculateAverage += null, new EventArgs.Empty); modelMock.Verify(x => x.CalculateAverage()); //never comes here, test fails in above line and exits Assert.True(true); } The issue is that the test is failing in the second last line with "Invocation was not performed on the mock: x = x.CalculateAverage()". Another thing I noticed is that the test terminates on this second last line and the last line is never executed. Am I doing everything correct?

    Read the article

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