Search Results

Search found 694 results on 28 pages for 'mock'.

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

  • Mock RequireJS define dependencies with config.map

    - by Aligned
    Originally posted on: http://geekswithblogs.net/Aligned/archive/2014/08/18/mock-requirejs-define-dependencies-with-config.map.aspxI had a module dependency, that I’m pulling down with RequireJS that I needed to use and write tests against. In this case, I don’t care about the actual implementation of the module (it’s simple enough that I’m just avoiding some AJAX calls). EDIT: make sure you look at the bottom example after the edit before using the config.map approach. I found that there is an easier way. I did not want to change the constructor of the consumer as I had a chain of changes that would have to be made and that would have been to invasive for this task. I found a question on StackOverflow with a short, but helpful answer from “Artem Oboturov”. We can use the config.map from RequireJs to achieve this. Here is some code: A module example (“usefulModule” in Common/Modules/usefulModule.js): define([], function() { "use strict"; var testMethod = function() { ... }; // add more functionality of the module return { testMethod; } }); A consumer of usefulModule example: define([ "Commmon/Modules/usefulModule" ], function(usefulModule) { "use strict"; var consumerModule = function(){ var self = this; // add functionality of the module } }); Using config.map in the html of the test runner page (and in your Karma config –> I’m still trying to figure this out): map: {'*': { // replace usefulModule with a mock 'Common/Modules/usefulModule': '/Tests/Specs/Common/usefulModuleMock.js' } } With the new mapping, Require will load usefulModuleMock.js from Tests/Specs/Common instead of the real implementation. Some of the answers on StackOverflow mentioned Squire.js, which looked interesting, but I wasn’t ready to introduce a new library at this time. That’s all you need to be able to mock a depency in RequireJS. However, there are many good cases when you should pass it in through the constructor instead of this approach.   EDIT: After all that, here’s another, probably better way: The consumer class, updated: define([ "Commmon/Modules/usefulModule" ], function(UsefulModule) { "use strict"; var consumerModule = function(){ var self = this; self.usefulModule = new UsefulModule(); // add functionality of the module } }); Jasmine test: define([ "consumerModule", "/UnitTests/Specs/Common/Mocks/usefulModuleMock.js" ], function(consumerModule, UsefulModuleMock){ describe("when mocking out the module", function(){ it("should probably just override the property", function(){ var consumer = new consumerModule(); consumer.usefulModule = new UsefulModuleMock(); }); }); });   Thanks for letting me think out loud :-).

    Read the article

  • python mock patch : a method of instance is called?

    - by JuanPablo
    In python 2.7, I have this function from slacker import Slacker def post_message(token, channel, message): channel = '#{}'.format(channel) slack = Slacker(token) slack.chat.post_message(channel, message) with mock and patch, I can check that the token is used in Slacker class import unittest from mock import patch from slacker_cli import post_message class TestMessage(unittest.TestCase): @patch('slacker_cli.Slacker') def test_post_message_use_token(self, mock_slacker): token = 'aaa' channel = 'channel_name' message = 'message string' post_message(token, channel, message) mock_slacker.assert_called_with(token) how I can check the string use in post_message ? I try with mock_slacker.chat.post_message.assert_called_with('#channel') but I get AssertionError: Expected call: post_message('#channel') Not called

    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

  • Is it legal to stub the #class method of a Mock object when using RSpec in a Ruby on Rails applicati

    - by MiniQuark
    I would like to stub the #class method of a mock object: describe Letter do before(:each) do @john = mock("John") @john.stub!(:id).and_return(5) @john.stub!(:class).and_return(Person) # is this ok? @john.stub!(:name).and_return("John F.") Person.stub!(:find).and_return(@john) end it.should "have a valid #to field" do letter = Letter.create!(:to=>@john, :content => "Hello John") letter.to_type.should == @john.class.name letter.to_id.should == @john.id end [...] end On line 5 of this program, I stub the #class method, in order to allow things like @john.class.name. Is this the right way to go? Will there be any bad side effect? Edit: The Letter class looks like this: class Letter < ActiveRecord::Base belongs_to :to, :polymorphic => true [...] end I wonder whether ActiveRecord gets the :to field's class name with to.class.name or by some other means. Maybe this is what the class_name method is ActiveRecord::Base is for?

    Read the article

  • Howto install google-mock on Ubuntu 12.10

    - by user1459339
    I am having hard time trying to install Google C++ Mocking Framework. I have successfully run sudo apt-get install google-mock. Then I tried to compile this sample file #include "gmock/gmock.h" int main(int argc, char** argv) { ::testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } with g++ -lgmock main.cpp and these errors have shown main.cpp:(.text+0x1e): undefined reference to `testing::InitGoogleMock(int*, char**)' main.cpp:(.text+0x23): undefined reference to `testing::UnitTest::GetInstance()' main.cpp:(.text+0x2b): undefined reference to `testing::UnitTest::Run()' collect2: error: ld returned 1 exit status I guess the linker can not find the library files. Does anybody know how to fix this?

    Read the article

  • Using Mock for event listeners in unit-testing

    - by phtrivier
    I keep getting to test this kind of code (language irrelevant) : public class Foo() { public Foo(Dependency1 dep1) { this.dep1 = dep1; } public void setUpListeners() { this.dep1.addSomeEventListener(.... some listener code ...); } } Typically, you want to test what when the dependency fires the event, the class under tests reacts appropriately (in some situation, the only purpose of such classes is to wire lots of other components, that can be independently tested. So far, to test this, I always end up doing something like : creating a 'stub' that implements both a addXXXXListener, that simply stores the callback, and a fireXXXX, that simply calls any registered listener. This is a bit tedious since you have to create the mock with the right interface, but that can do use an introspective framework that can 'spy' on a method, and inject the real dependency in tests Is there a cleaner way to do this kind of things ?

    Read the article

  • How to install (or mock) Internet Explorer?

    - by Ivan
    I need to install a Windows application, which checks if there is Internet Explorer of at least 5th version installed and refuses to install (while I believe it does not really need it to work) if it is not. I've tried winetricks to install ie 8, 7, 6 full, 6 versions it offers - none worked - versions 7 and 8 installers report a function missing in msvcr (installing all msvcr versions didn't help), ie6 report some other error (I'll specify if it matters). I've also tried IEs4Linux - it also fails, complaining for a "BadIDChoice" X Window System error received by ies4linux-gtk.py. Is there a way to install any IE version in Ubuntu 10.10 with Wine or to mock its presence? I don't even need it to work, just to be installed in the Wine system so that other Windows programs could see it's there. I use Ubuntu 10.10 with Wine 1.3.8.

    Read the article

  • Moving from mock to real objects?

    - by jjchiw
    I'm like doing TDD so I started everything mocking objects, creating interface, stubbing, great. The design seems to work, now I'll implement the stuff, a lot of the code used in the stubs are going to be reused in my real implementation yay! Now should I duplicate the tests to use the real object implementation (but keeping the mocks object of the sensitive stuff like Database and "services" that are out of my context (http calls, etc...)) Or just change the mocks and stubs of the actual tests to use the real objects....... So the question is that, keep two tests or replace the stubs, mocks? And after that, I should keep designing with the mocks, stubs or just go with real objects? (Just making myself clear I'll keep the mock object of the sensitive stuff like database and services that are out of my context, in both situations.)

    Read the article

  • Mocking property sets

    - by mehfuzh
    In this post, i will be showing how you can mock property sets with your expected values or even action using JustMock. To begin, we have a sample interface: public interface IFoo {     int Value { get; set; } } Now,  we can create a mock that will throw on any call other than the one expected, generally its a strict mock and we can do it like: bool expected = false;  var foo = Mock.Create<IFoo>(BehaviorMode.Strict);  Mock.ArrangeSet(() => { foo.Value = 1; }).DoInstead(() => expected  = true);    foo.Value = 1;    Assert.True(expected); Here , the method for running though our expectation for set is Mock.ArrangeSet , where we can directly set our expectations or can even set matchers into it like: var foo = Mock.Create<IFoo>(BehaviorMode.Strict);   Mock.ArrangeSet(() => foo.Value = Arg.Matches<int>(x => x > 3));   foo.Value = 4; foo.Value = 5;   Assert.Throws<MockException>(() => foo.Value = 3);   In the example, any set for value not satisfying matcher expression will throw an MockException as this is a strict mock but what will be the case for loose mocks, where we also have to assert it. Here, let’s take an interface with an indexed property. Indexers are treated in the same way as properties, as with basic indexers let you access your class if it were an array. public interface IFooIndexed {     string this[int key] { get; set; } } We want to  setup a value for a particular index,  we then will pass that mock to some implementer where it will be actually called. Once done, we want to assert that if it has been invoked properly. var foo = Mock.Create<IFooIndexed>();   Mock.ArrangeSet(() => foo[0] = "ping");   foo[0] = "ping";   Mock.AssertSet(() => foo[0] = "ping"); In the above example, both the values are user defined, it might happen that we want to make it more dynamic, In this example, i set it up for set with any value and finally checked if it is set with the one i am looking for. var foo = Mock.Create<IFooIndexed>();   Mock.ArrangeSet(() => foo[0] = Arg.Any<string>());   foo[0] = "ping";   Mock.AssertSet(() => foo[0] = Arg.Matches<string>(x => string.Compare("ping", x) == 0)); This is more or less of mocking user sets , but we can further have it to throw exception or even do our own task for a particular set , like : Mock.ArrangeSet(() => foo.MyProperty = 10).Throws(new ArgumentException()); Or  bool expected = false;  var foo = Mock.Create<IFoo>(BehaviorMode.Strict);  Mock.ArrangeSet(() => { foo.Value = 1; }).DoInstead(() => expected  = true);    foo.Value = 1;    Assert.True(expected); Or call the original setter , in this example it will throw an NotImplementedExpectation var foo = Mock.Create<FooAbstract>(BehaviorMode.Strict); Mock.ArrangeSet(() => { foo.Value = 1; }).CallOriginal(); Assert.Throws<NotImplementedException>(() => { foo.Value = 1; });   Finally, try all these, find issues, post them to forum and make it work for you :-). Hope that helps,

    Read the article

  • Behind ASP.NET MVC Mock Objects

    - by imran_ku07
       Introduction:           I think this sentence now become very familiar to ASP.NET MVC developers that "ASP.NET MVC is designed with testability in mind". But what ASP.NET MVC team did for making applications build with ASP.NET MVC become easily testable? Understanding this is also very important because it gives you some help when designing custom classes. So in this article i will discuss some abstract classes provided by ASP.NET MVC team for the various ASP.NET intrinsic objects, including HttpContext, HttpRequest, and HttpResponse for making these objects as testable. I will also discuss that why it is hard and difficult to test ASP.NET Web Forms.      Description:           Starting from Classic ASP to ASP.NET MVC, ASP.NET Intrinsic objects is extensively used in all form of web application. They provide information about Request, Response, Server, Application and so on. But ASP.NET MVC uses these intrinsic objects in some abstract manner. The reason for this abstraction is to make your application testable. So let see the abstraction.           As we know that ASP.NET MVC uses the same runtime engine as ASP.NET Web Form uses, therefore the first receiver of the request after IIS and aspnet_filter.dll is aspnet_isapi.dll. This will start the application domain. With the application domain up and running, ASP.NET does some initialization and after some initialization it will call Application_Start if it is defined. Then the normal HTTP pipeline event handlers will be executed including both HTTP Modules and global.asax event handlers. One of the HTTP Module is registered by ASP.NET MVC is UrlRoutingModule. The purpose of this module is to match a route defined in global.asax. Every matched route must have IRouteHandler. In default case this is MvcRouteHandler which is responsible for determining the HTTP Handler which returns MvcHandler (which is derived from IHttpHandler). In simple words, Route has MvcRouteHandler which returns MvcHandler which is the IHttpHandler of current request. In between HTTP pipeline events the handler of ASP.NET MVC, MvcHandler.ProcessRequest will be executed and shown as given below,          void IHttpHandler.ProcessRequest(HttpContext context)          {                    this.ProcessRequest(context);          }          protected virtual void ProcessRequest(HttpContext context)          {                    // HttpContextWrapper inherits from HttpContextBase                    HttpContextBase ctxBase = new HttpContextWrapper(context);                    this.ProcessRequest(ctxBase);          }          protected internal virtual void ProcessRequest(HttpContextBase ctxBase)          {                    . . .          }             HttpContextBase is the base class. HttpContextWrapper inherits from HttpContextBase, which is the parent class that include information about a single HTTP request. This is what ASP.NET MVC team did, just wrap old instrinsic HttpContext into HttpContextWrapper object and provide opportunity for other framework to provide their own implementation of HttpContextBase. For example           public class MockHttpContext : HttpContextBase          {                    . . .          }                     As you can see, it is very easy to create your own HttpContext. That's what did the third party mock frameworks like TypeMock, Moq, RhinoMocks, or NMock2 to provide their own implementation of ASP.NET instrinsic objects classes.           The key point to note here is the types of ASP.NET instrinsic objects. In ASP.NET Web Form and ASP.NET MVC. For example in ASP.NET Web Form the type of Request object is HttpRequest (which is sealed) and in ASP.NET MVC the type of Request object is HttpRequestBase. This is one of the reason that makes test in ASP.NET WebForm is difficult. because their is no base class and the HttpRequest class is sealed, therefore it cannot act as a base class to others. On the other side ASP.NET MVC always uses a base class to give a chance to third parties and unit test frameworks to create thier own implementation ASP.NET instrinsic object.           Therefore we can say that in ASP.NET MVC, instrinsic objects are of type base classes (for example HttpContextBase) .Actually these base classes had it's own implementation of same interface as the intrinsic objects it abstracts. It includes only virtual members which simply throws an exception. ASP.NET MVC also provides the corresponding wrapper classes (for example, HttpRequestWrapper) which provides a concrete implementation of the base classes in the form of ASP.NET intrinsic object. Other wrapper classes may be defined by third parties in the form of a mock object for testing purpose.           So we can say that a Request object in ASP.NET MVC may be HttpRequestWrapper or may be MockRequestWrapper(assuming that MockRequestWrapper class is used for testing purpose). Here is list of ASP.NET instrinsic and their implementation in ASP.NET MVC in the form of base and wrapper classes. Base Class Wrapper Class ASP.NET Intrinsic Object Description HttpApplicationStateBase HttpApplicationStateWrapper Application HttpApplicationStateBase abstracts the intrinsic Application object HttpBrowserCapabilitiesBase HttpBrowserCapabilitiesWrapper HttpBrowserCapabilities HttpBrowserCapabilitiesBase abstracts the HttpBrowserCapabilities class HttpCachePolicyBase HttpCachePolicyWrapper HttpCachePolicy HttpCachePolicyBase abstracts the HttpCachePolicy class HttpContextBase HttpContextWrapper HttpContext HttpContextBase abstracts the intrinsic HttpContext object HttpFileCollectionBase HttpFileCollectionWrapper HttpFileCollection HttpFileCollectionBase abstracts the HttpFileCollection class HttpPostedFileBase HttpPostedFileWrapper HttpPostedFile HttpPostedFileBase abstracts the HttpPostedFile class HttpRequestBase HttpRequestWrapper Request HttpRequestBase abstracts the intrinsic Request object HttpResponseBase HttpResponseWrapper Response HttpResponseBase abstracts the intrinsic Response object HttpServerUtilityBase HttpServerUtilityWrapper Server HttpServerUtilityBase abstracts the intrinsic Server object HttpSessionStateBase HttpSessionStateWrapper Session HttpSessionStateBase abstracts the intrinsic Session object HttpStaticObjectsCollectionBase HttpStaticObjectsCollectionWrapper HttpStaticObjectsCollection HttpStaticObjectsCollectionBase abstracts the HttpStaticObjectsCollection class      Summary:           ASP.NET MVC provides a set of abstract classes for ASP.NET instrinsic objects in the form of base classes, allowing someone to create their own implementation. In addition, ASP.NET MVC also provide set of concrete classes in the form of wrapper classes. This design really makes application easier to test and even application may replace concrete implementation with thier own implementation, which makes ASP.NET MVC very flexable.

    Read the article

  • Write your Tests in RSpec with IronRuby

    - by kazimanzurrashid
    [Note: This is not a continuation of my previous post, treat it as an experiment out in the wild. ] Lets consider the following class, a fictitious Fund Transfer Service: public class FundTransferService : IFundTransferService { private readonly ICurrencyConvertionService currencyConvertionService; public FundTransferService(ICurrencyConvertionService currencyConvertionService) { this.currencyConvertionService = currencyConvertionService; } public void Transfer(Account fromAccount, Account toAccount, decimal amount) { decimal convertionRate = currencyConvertionService.GetConvertionRate(fromAccount.Currency, toAccount.Currency); decimal convertedAmount = convertionRate * amount; fromAccount.Withdraw(amount); toAccount.Deposit(convertedAmount); } } public class Account { public Account(string currency, decimal balance) { Currency = currency; Balance = balance; } public string Currency { get; private set; } public decimal Balance { get; private set; } public void Deposit(decimal amount) { Balance += amount; } public void Withdraw(decimal amount) { Balance -= amount; } } We can write the spec with MSpec + Moq like the following: public class When_fund_is_transferred { const decimal ConvertionRate = 1.029m; const decimal TransferAmount = 10.0m; const decimal InitialBalance = 100.0m; static Account fromAccount; static Account toAccount; static FundTransferService fundTransferService; Establish context = () => { fromAccount = new Account("USD", InitialBalance); toAccount = new Account("CAD", InitialBalance); var currencyConvertionService = new Moq.Mock<ICurrencyConvertionService>(); currencyConvertionService.Setup(ccv => ccv.GetConvertionRate(Moq.It.IsAny<string>(), Moq.It.IsAny<string>())).Returns(ConvertionRate); fundTransferService = new FundTransferService(currencyConvertionService.Object); }; Because of = () => { fundTransferService.Transfer(fromAccount, toAccount, TransferAmount); }; It should_decrease_from_account_balance = () => { fromAccount.Balance.ShouldBeLessThan(InitialBalance); }; It should_increase_to_account_balance = () => { toAccount.Balance.ShouldBeGreaterThan(InitialBalance); }; } and if you run the spec it will give you a nice little output like the following: When fund is transferred » should decrease from account balance » should increase to account balance 2 passed, 0 failed, 0 skipped, took 1.14 seconds (MSpec). Now, lets see how we can write exact spec in RSpec. require File.dirname(__FILE__) + "/../FundTransfer/bin/Debug/FundTransfer" require "spec" require "caricature" describe "When fund is transferred" do Convertion_Rate = 1.029 Transfer_Amount = 10.0 Initial_Balance = 100.0 before(:all) do @from_account = FundTransfer::Account.new("USD", Initial_Balance) @to_account = FundTransfer::Account.new("CAD", Initial_Balance) currency_convertion_service = Caricature::Isolation.for(FundTransfer::ICurrencyConvertionService) currency_convertion_service.when_receiving(:get_convertion_rate).with(:any, :any).return(Convertion_Rate) fund_transfer_service = FundTransfer::FundTransferService.new(currency_convertion_service) fund_transfer_service.transfer(@from_account, @to_account, Transfer_Amount) end it "should decrease from account balance" do @from_account.balance.should be < Initial_Balance end it "should increase to account balance" do @to_account.balance.should be > Initial_Balance end end I think the above code is self explanatory, treat the require(line 1- 4) statements as the add reference of our visual studio projects, we are adding all the required libraries with this statement. Next, the describe which is a RSpec keyword. The before does exactly the same as NUnit's Setup or MsTest’s TestInitialize attribute, but in the above we are using before(:all) which acts as ClassInitialize of MsTest, that means it will be executed only once before all the test methods. In the before(:all) we are first instantiating the from and to accounts, it is same as creating with the full name (including namespace)  like fromAccount = new FundTransfer.Account(.., ..), next, we are creating a mock object of ICurrencyConvertionService, check that for creating the mock we are not using the Moq like the MSpec version. This is somewhat an interesting issue of IronRuby or maybe the DLR, it seems that it is not possible to use the lambda expression that most of the mocking tools uses in arrange phase in Iron Ruby, like: currencyConvertionService.Setup(ccv => ccv.GetConvertionRate(Moq.It.IsAny<string>(), Moq.It.IsAny<string>())).Returns(ConvertionRate); But the good news is, there is already an excellent mocking tool called Caricature written completely in IronRuby which we can use to mock the .NET classes. May be all the mocking tool providers should give some thought to add the support for the DLR, so that we can use the tool that we are already familiar with. I think the rest of the code is too simple, so I am skipping the explanation. Now, the last thing, how we are going to run it with RSpec, lets first install the required gems. Open you command prompt and type the following: igem sources -a http://gems.github.com This will add the GitHub as gem source. Next type: igem install uuidtools caricature rspec and at last we have to create a batch file so that we can execute it in the Notepad++, create a batch like in the IronRuby bin directory like my previous post and put the following in that batch file: @echo off cls call spec %1 --format specdoc pause Next, add a run menu and shortcut in the Notepad++ like my previous post. Now when we run it it will show the following output: When fund is transferred - should decrease from account balance - should increase to account balance Finished in 0.332042 seconds 2 examples, 0 failures Press any key to continue . . . You will complete code of this post in the bottom. That's it for today. Download: RSpecIntegration.zip

    Read the article

  • Mock the window.setTimeout in a Jasmine test to avoid waiting

    - by Aligned
    Originally posted on: http://geekswithblogs.net/Aligned/archive/2014/08/21/mock-the-window.settimeout-in-a-jasmine-test-to-avoid-waiting.aspxJasmine has a clock mocking feature, but I was unable to make it work in a function that I’m calling and want to test. The example only shows using clock for a setTimeout in the spec tests and I couldn’t find a good example. Here is my current and slightly limited approach.   If we have a method we want to test: var test = function(){ var self = this; self.timeoutWasCalled = false; self.testWithTimeout = function(){ window.setTimeout(function(){ self.timeoutWasCalled = true; }, 6000); }; }; Here’s my testing code: var realWindowSetTimeout = window.setTimeout; describe('test a method that uses setTimeout', function(){ var testObject; beforeEach(function () { // force setTimeout to be called right away, no matter what time they specify jasmine.getGlobal().setTimeout = function (funcToCall, millis) { funcToCall(); }; testObject = new test(); }); afterEach(function() { jasmine.getGlobal().setTimeout = realWindowSetTimeout; }); it('should call the method right away', function(){ testObject.testWithTimeout(); expect(testObject.timeoutWasCalled).toBeTruthy(); }); }); I got a good pointer from Andreas in this StackOverflow question. This would also work for window.setInterval. Other possible approaches: create a wrapper module of setTimeout and setInterval methods that can be mocked. This can be mocked with RequireJS or passed into the constructor. pass the window.setTimeout function into the method (this could get messy)

    Read the article

  • C++ Mock/Test boost::asio::io_stream - based Asynch Handler

    - by rbellamy
    I've recently returned to C/C++ after years of C#. During those years I've found the value of Mocking and Unit testing. Finding resources for Mocks and Units tests in C# is trivial. WRT Mocking, not so much with C++. I would like some guidance on what others do to mock and test Asynch io_service handlers with boost. For instance, in C# I would use a MemoryStream to mock an IO.Stream, and am assuming this is the path I should take here. C++ Mock/Test best practices boost::asio::io_service Mock/Test best practices C++ Async Handler Mock/Test best practices I've started the process with googlemock and googletest.

    Read the article

  • python mock side_effect or return_value dependent on call_count

    - by user18380
    To test a polling function I want to mock the calling of a sub function so that the first time it is called it will fail, and the second time it is called it will succeed. Here's a very simplified version of it: poll_function(var1): value = sub_function(var1) # First call will return None while not value: time.sleep(POLLING_INTERVAL) value = sub_function(var1) # A subsequent call will return a string, e.g "data" return value Is this possible to do with a Mock object from the mock framework? I know Mock objects have a call_count attribute I should be able to use somehow. Right now I've solved it by creating a custom mock object that I use to monkey patch sub_function(), but I feel there should be a better less verbose way of doing it: def test_poll(): class MyMock(object): def __init__(self, *args): self.call_count = 0 def sub_function(self, *args, **kwargs): if self.call_count > 1: return "data" else: self.call_count += 1 return None my_mock = MyMock() with patch('sub_function', my_mock.sub_function): ok_(poll_function())

    Read the article

  • Playing with aspx page cycle using JustMock

    - by mehfuzh
    In this post , I will cover a test code that will mock the various elements needed to complete a HTTP page request and  assert the expected page cycle steps. To begin, i have a simple enumeration that has my predefined page steps: public enum PageStep {     PreInit,     Load,     PreRender,     UnLoad } Once doing so, i  first created the page object [not mocking]. Page page = new Page(); Here, our target is to fire up the page process through ProcessRequest call, now if we take a look inside the method with reflector.net,  the call trace will go like : ProcessRequest –> ProcessRequestWithNoAssert –> SetInstrinsics –> Finallly ProcessRequest. Inside SetInstrinsics ,  it requires calls from HttpRequest, HttpResponse and HttpBrowserCababilities. Using this clue at hand, we can easily know the classes / calls  we need to mock in order to get through the expected call. Accordingly, for  HttpBrowserCapabilities our required mock code will look like: var browser = Mock.Create<HttpBrowserCapabilities>(); // Arrange Mock.Arrange(() => browser.PreferredRenderingMime).Returns("text/html"); Mock.Arrange(() => browser.PreferredResponseEncoding).Returns("UTF-8"); Mock.Arrange(() => browser.PreferredRequestEncoding).Returns("UTF-8"); Now, HttpBrowserCapabilities is get though [Instance]HttpRequest.Browser. Therefore, we create the HttpRequest mock: var request = Mock.Create<HttpRequest>(); Then , add the required get call : Mock.Arrange(() => request.Browser).Returns(browser); As, [instance]Browser.PerferrredResponseEncoding and [instance]Browser.PreferredResponseEncoding  are also set to the request object and to make that they are set properly, we can add the following lines as well [not required though]. bool requestContentEncodingSet = false; Mock.ArrangeSet(() => request.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() =>  requestContentEncodingSet = true); Similarly, for response we can write:  var response = Mock.Create<HttpResponse>();    bool responseContentEncodingSet = false;  Mock.ArrangeSet(() => response.ContentEncoding = Encoding.GetEncoding("UTF-8")).DoInstead(() => responseContentEncodingSet = true); Finally , I created a mock of HttpContext and set the Request and Response properties that will returns the mocked version. var context = Mock.Create<HttpContext>();   Mock.Arrange(() => context.Request).Returns(request); Mock.Arrange(() => context.Response).Returns(response); As, Page internally calls RenderControl method , we just need to replace that with our one and optionally we can check if  invoked properly: bool rendered = false; Mock.Arrange(() => page.RenderControl(Arg.Any<HtmlTextWriter>())).DoInstead(() => rendered = true); That’s  it, the rest of the code is simple,  where  i asserted the page cycle with the PageSteps that i defined earlier: var pageSteps = new Queue<PageStep>();   page.PreInit +=delegate { pageSteps.Enqueue(PageStep.PreInit); }; page.Load += delegate { pageSteps.Enqueue(PageStep.Load); }; page.PreRender += delegate { pageSteps.Enqueue(PageStep.PreRender);}; page.Unload +=delegate { pageSteps.Enqueue(PageStep.UnLoad);};   page.ProcessRequest(context);   Assert.True(requestContentEncodingSet); Assert.True(responseContentEncodingSet); Assert.True(rendered);   Assert.Equal(pageSteps.Dequeue(), PageStep.PreInit); Assert.Equal(pageSteps.Dequeue(), PageStep.Load); Assert.Equal(pageSteps.Dequeue(), PageStep.PreRender); Assert.Equal(pageSteps.Dequeue(), PageStep.UnLoad);   Mock.Assert(request); Mock.Assert(response); You can get the test class shown in this post here to give a try by yourself with of course JustMock :-). Enjoy!!

    Read the article

  • How do you mock ViewModel Commands using moq?

    - by devnet247
    Hi I might be approaching this all wrong.But please help me to understand. I really want to TDD building wpf application using Moq. I would like to mock the viewmodel. Application Show a list of contacts and when you double click on a contact it shows the contact. Test Moq GetContactsCommand.Test it has been called. Test that you get a list of contacts. Not sure how to mock the viewModel and it's commands can you correct me? So I have started to do the following [Test] public void Should_be_able_to_mock_getContactsCommand_and_get_a_list_of_contacts() { //Arrange var expectedContacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; var mock = new Mock<IContactListViewModel>(); mock.SetupGet(x => x.GetContactsCommand).Verifiable(); mock.SetupGet(x => x.Contacts).Returns(expectedContacts); //Act //? //assert mock.VerifySet(x => x.Contacts, Times.AtLeastOnce()); mock.Object.Contacts.Count.ShouldEqual(expectedContacts.Count); } public interface IContactListViewModel { ObservableCollection<ContactViewModel> Contacts { get; set; } ICommand GetContactsCommand{ get; } } public interface IContactModel { string FirstName { get; set; } string LastName { get; set; } string Email { get; set; } } public class ContactModel : IContactModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } public class ContactViewModel : ViewModelBase { private readonly ContactModel _contactModel; public ContactViewModel(ContactModel contactModel) { _contactModel = contactModel; } public string FirstName { get { return _contactModel.FirstName; } set { _contactModel.FirstName = value; OnPropertyChanged("FirstName"); } } public string LastName { get { return _contactModel.LastName; } set { _contactModel.LastName = value; OnPropertyChanged("LastName"); } } public string Email { get { return _contactModel.Emai; } set { _contactModel.Email = value; OnPropertyChanged("Email"); } } } public class ContactListViewModel : ViewModelBase, IContactListViewModel { private ObservableCollection<ContactViewModel> _contacts; public ObservableCollection<ContactViewModel> Contacts { get { return _contacts; } set { _contacts = value; OnPropertyChanged("Contacts"); } } private RelayCommand _getContactsCommand; public ICommand GetContactsCommand { get { return _getContactsCommand ?? (_getContactsCommand = new RelayCommand(x => GetContacts(), x => CanGetContacts)); } } private static bool CanGetContacts { get { return true; } } private void GetContacts() { //pretend we are going to the service or db whatever Contacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; } }

    Read the article

  • Zend Framework/PHPUnit: How to Stub/Mock an object method that connects to a database?

    - by Andrew
    In my Zend Framework project, I have a form that I am testing. In my form, a multi-select element gets its options from a model, which gets the data from the database. public function init() { $this->addElement('select', 'Region_ID', array('multiOptions' => $this->getRegions())); } protected function getRegions() { $mapper = new Model_RegionMapper(); return $mapper->getFormSelectData(); //this method will try to connect to a database (or get another object that will connect to the database) } I tried copying the example in the PHPUnit documentation, but it doesn't seem to be working. public function setUp() { $stub = $this->getMock('Model_RegionMapper'); $stub->expects($this->any()) ->method('getFormSelectData') ->will($this->returnValue(array('testdata'))); } public function testFoo() { //this will fail $form = new My_Form(); } The test fails because it is trying to find a table in the database that doesn't exist. But I don't want it to connect to the database at all. How do I correctly stub/mock this method so that it doesn't call the database?

    Read the article

  • Moq basic questions

    - by devoured elysium
    I made the following test for my class: var mock = new Mock<IRandomNumberGenerator>(); mock.Setup(framework => framework.Generate(0, 50)) .Returns(7.0); var rnac = new RandomNumberAverageCounter(mock.Object, 1, 100); rnac.Run(); double result = rnac.GetAverage(); Assert.AreEqual(result, 7.0, 0.1); The problem here was that I changed my mind about what range of values Generate(int min, int max) would use. So in Mock.Setup() I defined the range as from 0 to 50 while later I actually called the Generate() method with a range from 1 to 100. I ran the test and it failed. I know that that is what it's supposed to happen but I was left wondering if isn't there a way to launch an exception or throw in a message when trying to run the method with wrong params. Also, if I want to run this Generate() method 10 times with different values (let's say, from 1 to 10), will I have to make 10 mock setups or something, or is there a special method for it? The best I could think of is this (which isn't bad, I'm just asking if there is other better way): for (int i = 1; i < 10; ++i) { mock.Setup(framework => framework.Generate(1, 100)) .Returns((double)i); }

    Read the article

  • Doing your first mock with JustMock

    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...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Using NBuilder to mock up a data driven UI - Part 1

    In this article we will take a look at a fairly new open source project called NBuilder (http://www.nbuilder.org and http://code.google.com/p/nbuilder/) and how it can be used to provide us with fake data out of the gate. NBuilder allows you to quickly stand up generated objects based on standard .net types in an easy fluent manner. And that is just the start!

    Read the article

  • Using NBuilder to mock up a data driven UI - Part 2

    In this article we will continue our discussion by filling out the implementation in our service class with some NBuilder code. Once we have the working service class in place we can then create a working UI (in the ASP.NET MVC project we created in the last article).

    Read the article

  • Mock Repository vs. Real Repository w/Mocked Data

    - by n8wrl
    I must be doing something fundamentally wrong. I am implmenting my repositories and then testing them with mocked data. All is well. Now I want to test my domain objects so I point them at mock repositories. But I'm finding that I have to re-implement logic from the 'real' repositories into the mocks, or, create 'helper classes' that encapsulate the logic and interact with the repositories (real or mock), and then I have to test those too. So what am I missing - why implement and test mock repositories when I could use the real ones with mocked data? EDIT: To clarify, by 'mocked data' I do not hit the actual database. I have a 'DB mock layer' I can insert under the real repositories that returns known-data.

    Read the article

  • Cannot mock class with constructor having array parameter using Rhino Mocks

    - by SharePoint Newbie
    Hi, We cannot mock his class in RhinoMocks. public class Service { public Service(Command[] commands){} } public abstract class Command {} // Code var mock = MockRepository.GenerateMock<Service>(new Command[]{}); // or mock = MockRepository.GenerateMock<Service>(null) Rhino mocks fails complaining that it cannot find a constructor with matching arguments. What am I doing wrong? Thanks,

    Read the article

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