Search Results

Search found 381 results on 16 pages for 'mocking'.

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

  • Mocking ISession.Query<T>() for testing consumer

    - by TheCloudlessSky
    I'm trying to avoid using an in memory database for testing (though I might have to do this if the following is impossible). I'm using NHibernate 3.0 with LINQ. I'd like to be able to mock session.Query<T>() to return some dummy values but I can't since it's an extension method and these are pretty much impossible to test. Does anyone have any suggestions (other than using an in memory database) for testing session queries with LINQ?

    Read the article

  • asp.net mvc How to test controllers correctly

    - by Simon G
    Hi, I'm having difficulty testing controllers. Original my controller for testing looked something like this: SomethingController CreateSomethingController() { var somethingData = FakeSomethingData.CreateFakeData(); var fakeRepository = FakeRepository.Create(); var controller = new SomethingController(fakeRepository); return controller; } This works fine for the majority of testing until I got the Request.IsAjaxRequest() part of code. So then I had to mock up the HttpContext and HttpRequestBase. So my code then changed to look like: public class FakeHttpContext : HttpContextBase { bool _isAjaxRequest; public FakeHttpContext( bool isAjaxRequest = false ) { _isAjaxRequest = isAjaxRequest; } public override HttpRequestBase Request { get { string ajaxRequestHeader = ""; if ( _isAjaxRequest ) ajaxRequestHeader = "XMLHttpRequest"; var request = new Mock<HttpRequestBase>(); request.SetupGet( x => x.Headers ).Returns( new WebHeaderCollection { {"X-Requested-With", ajaxRequestHeader} } ); request.SetupGet( x => x["X-Requested-With"] ).Returns( ajaxRequestHeader ); return request.Object; } } private IPrincipal _user; public override IPrincipal User { get { if ( _user == null ) { _user = new FakePrincipal(); } return _user; } set { _user = value; } } } SomethingController CreateSomethingController() { var somethingData = FakeSomethingData.CreateFakeData(); var fakeRepository = FakeRepository.Create(); var controller = new SomethingController(fakeRepository); ControllerContext controllerContext = new ControllerContext( new FakeHttpContext( isAjaxRequest ), new RouteData(), controller ); controller.ControllerContext = controllerContext; return controller; } Now its got to that stage in my controller where I call Url.Route and Url is null. So it looks like I need to start mocking up routes for my controller. I seem to be spending more time googling on how to fake/mock objects and then debugging to make sure my fakes are correct than actual writing the test code. Is there an easier way in to test a controller? I've looked at the TestControllerBuilder from MvcContrib which helps with some of the issues but doesn't seem to do everything. Is there anything else available that will do the job and will let me concentrate on writing the tests rather than writing mocks? Thanks

    Read the article

  • Best way to mock WCF Client proxy

    - by chugh97
    Are there any ways to mock a WCF client proxy using Rhino mocks framework so I have access to the Channel property? I am trying to unit test Proxy.Close() method but as the proxy is constructed using the abstract base class ClientBast which has the ICommunication interface, my unit test is failing as the internal infrastructure of the class is absent in the mock object. Any good ways with code samples would be greatly appreciated.

    Read the article

  • Error while using PowerMockito.whenNew()

    - by Ankush
    I am using PowerMockito(1.3.6) with Mockito(1.8.3) and Junit(4.7) for testing. I am quite stuck on an error: [junit] Testcase: testNextPNRFromQueueHappyPath(com.orbitz.galileo.host.robot.GalpoQueueConnectionTest): Caused an ERROR [junit] org/mockito/internal/IMockHandler [junit] java.lang.NoClassDefFoundError: org/mockito/internal/IMockHandler [junit] at org.powermock.api.mockito.internal.expectation.DefaultConstructorExpectationSetup.createNewSubsituteMock(DefaultConstructorExpectationSetup.java:80) [junit] at org.powermock.api.mockito.internal.expectation.DefaultConstructorExpectationSetup.withArguments(DefaultConstructorExpectationSetup.java:48) [junit] at com.orbitz.galileo.host.robot.GalpoQueueConnectionTest.testNextPNRFromQueueHappyPath(GalpoQueueConnectionTest.java:62) [junit] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [junit] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [junit] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) My class under test : GalpoQueueConnection is basically creating a new object of another class : QueueReadBuilder. I am trying to do something like: @RunWith(PowerMockRunner.class) @PrepareForTest({GalpoQueueConnection.class, ApolloProcUtils.class}) public class GalpoQueueConnectionTest extends TestCase{ @Test public void testNextPNRFromQueueHappyPath() throws Exception { QueueReadBuilder mockBuilder = mock(QueueReadBuilder.class); PowerMockito.whenNew(QueueReadBuilder.class).withArguments(anyString(), anyString(), anyString()).thenReturn(mockBuilder); } } It seems like somehow powermockito is trying to call IMockHandler, and I looked at Mockito 1.8.3 api, and there isn't any. Any suggestions/ clues would be welcome.

    Read the article

  • Is TDD broken in Python?

    - by Konstantin
    Hi! Assume we have a class UserService with attribute current_user. Suppose it is used in AppService class. We have AppService covered with tests. In test setup we stub out current_user with some mock value: UserService.current_user = 'TestUser' Assume we decide to rename current_user to active_user. We rename it in UserService but forget to make change to its usage in AppService. We run tests and they pass! Test setup adds attribute current_user which is still (wrongly but successfully) used in AppService. Now our tests are useless. They pass but application will fail in production. We can't rely on our test suite == TDD is not possible. Is TDD broken in Python?

    Read the article

  • Chaining IQueryables together

    - by Matt Greer
    I have a RIA Services based app that is using Entity Framework on the server side (possibly not relevant). In my real app, I can do something like this. EntityQuery<Status> query = statusContext.GetStatusesQuery().Where(s => s.Description.Contains("Foo")); Where statusContext is the client side subclass of DomainContext that RIA Services was kind enough to generate for me. The end result is an EntityQuery<Status> object who's Query property is an object that implements IQueryable and represents my where clause. The WebDomainClient is able to take this EntityQuery and not just give me back all of my Statuses but also filtered with my where clause. I am trying to implement this in a mock DomainClient. This MockDomainClient accepts an IQueryably<Entity> which it returns when asked for. But what if the user makes the query and includes the ad hoc additional query? How can I merge the two together? My MockDomainClient is (this is modeled after this blog post) ... public class MockDomainClient : LocalDomainClient { private IQueryable<Entity> _entities; public MockDomainClient(IQueryable<Entity> entities) { _entities = entities; } public override IQueryable<Entity> DoQuery(EntityQuery query) { if (query.Query == null) { return _entities; } // otherwise want the union of _entities and query.Query, query.Query is IQueryable // the below does not work and was a total shot in the dark: //return _entities.Union(query.Query.Cast<Entity>()); } } public abstract class LocalDomainClient : System.ServiceModel.DomainServices.Client.DomainClient { private SynchronizationContext _syncContext; protected LocalDomainClient() { _syncContext = SynchronizationContext.Current; } ... public abstract IQueryable<Entity> DoQuery(EntityQuery query); protected override IAsyncResult BeginQueryCore(EntityQuery query, AsyncCallback callback, object userState) { IQueryable<Entity> localQuery = DoQuery(query); LocalAsyncResult asyncResult = new LocalAsyncResult(callback, userState, localQuery); _syncContext.Post(o => (o as LocalAsyncResult).Complete(), asyncResult); return asyncResult; } ... }

    Read the article

  • nMoq 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. 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 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); } Thanks

    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

  • How to properly match varargs in Mockito

    - by qualidafial
    I've been trying to get to mock a method with vararg parameters using Mockito: interface A { B b(int x, int y, C... c); } A a = mock(A.class); B b = mock(B.class); when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b); assertEquals(b, a.b(1, 2)); This doesn't work, however if I do this instead: when(a.b(anyInt(), anyInt())).thenReturn(b); assertEquals(b, a.b(1, 2)); This works, despite that I have completely omitted the varargs argument when stubbing the method. Any clues?

    Read the article

  • Qt, unit testing and mock objects.

    - by Eye of Hell
    Hello. Qt framework has internal support for testing via QtTest package. Unfortunately, i didn't find any facilities in it that can assist in creating mock objects. Qt signals and slots offers a natural way to create a unit-testing friendly units with input (slots) and output (signals). But is it any easy way to test that calling specified slot in object will result in emitting correct signals with correct arguments? Of course i can manually create a mock objects and connect them to objects being tested, but it's a lot of code. Maybe it's some techniques exists that allows to somehow automate mock objects creation while unit-testing Qt-based applications?

    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 mock Request.Files[] in MVC unit test class?

    - by kapil
    I want to test a controller method in MVC unit test. For my controller method to test, I require a Request.Files[] collection with length one. I want to mock Request.Files[] as I have used a file upload control on my view rendered by controller method. Can anyone please suggest how can I mock request.file collection in my unit test. thanks, kapil

    Read the article

  • How to mock protected virtual members with Rhino.Mocks?

    - by Vadim
    Moq allows developers to mock protected members. I was looking for the same functionality in Rhino.Mocks but fail to find it. Here's an example from Moq Quick Start page how to mock protected method. // at the top of the test fixture using Moq.Protected() // in the test var mock = new Mock<CommandBase>(); mock.Protected() .Setup<int>("Execute") .Returns(5); // if you need argument matching, you MUST use ItExpr rather than It // planning on improving this for vNext mock.Protected() .Setup<string>("Execute", ItExpr.IsAny<string>()) .Returns(true); Let me know if I'm chasing something that doesn't exit.

    Read the article

  • How do I mock an object in this case? no obvious way to replace object with mock

    - by Tristan
    Hi there, Suppose I have this very simple method in Store's model: def geocode_address loc = Store.geocode(address) self.lat = loc.lat self.lng = loc.lng end If I want to write some test scripts that aren't affected by the geocoding service, which may be down, have limitations or depend on my internet connection, how do I mock out the geocoding service? If I could pass a geocoding object into the method, it would be easy, but I don't see how I could do it in this case. Thanks! Tristan

    Read the article

  • How can I mock this asynchronous method?

    - by Charlie
    I have a class that roughly looks like this: public class ViewModel { public ViewModel(IWebService service) { this.WebService = service; } private IWebService WebService{get;set;} private IEnumerable<SomeData> MyData{get;set;} private void GetReferenceData() { this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete, null); } private void GetReferenceDataOnComplete(IAsyncResult result) { this.MyData = this.WebService.EndGetStaticReferenceData(result); } . . . } I want to mock my IWebService interface so that when BeginGetStaticReferenceData is called it is able to call the callback method. I'm using Moq and I can't work out how to do this. My unit test set up code looks something like: //Arrange var service = new Mock<IWebService>(); service.Setup(x => x.BeginGetStaticReferenceData(/*.......don't know.....*/)); service.Setup(x => x.EndGetStaticReferenceData(It.IsAny<IAsyncResult>())).Returns(new List<SomeData>{new SomeData{Name="blah"}}); var viewModel = new ViewModel(service.Object); . .

    Read the article

  • Mock versus Implementation. How to share both approaches in a single Test class ?

    - by Arthur Ronald F D Garcia
    Hi, See the following Mock Test by using Spring/Spring-MVC public class OrderTest { // SimpleFormController private OrderController controller; private OrderService service; private MockHttpServletRequest request; @BeforeMethod public void setUp() { request = new MockHttpServletRequest(); request.setMethod("POST"); Integer orderNumber = 421; Order order = new Order(orderNumber); // Set up a Mock service service = createMock(OrderService.class); service.save(order); replay(service); controller = new OrderController(); controller.setService(service); controller.setValidator(new OrderValidator()); request.addParameter("orderNumber", String.valueOf(orderNumber)); } @Test public void successSave() { controller.handleRequest(request, new MockHttpServletResponse()); // Our OrderService has been called by our controller verify(service); } @Test public void failureSave() { // Ops... our orderNumber is required request.removeAllParameters(); ModelAndView mav = controller.handleRequest(request, new MockHttpServletResponse()); BindingResult bindException = (BindingResult) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + "command"); assertEquals("Our Validator has thrown one FieldError", bindException.getAllErrors(), 1); } } As you can see, i do as proposed by Triple A pattern Arrange (setUp method) Act (controller.handleRequest) Assert (verify and assertEquals) But i would like to test both Mock and Implementation class (OrderService) by using this single Test class. So in order to retrieve my Implementation, i re-write my class as follows @ContextConfiguration(locations="/app.xml") public class OrderTest extends AbstractTestNGSpringContextTests { } So how should i write my single test to Arrange both Mock and Implementation OrderService without change my Test method (sucessSave and failureSave) I am using TestNG, but you can show in JUnit if you want regards,

    Read the article

  • How to test IO code in JUnit?

    - by add
    I'm want to test two services: service which builds file name service which writes some data into file provided by 1st service In first i'm building some complex file structure (just for example {user}/{date}/{time}/{generatedId}.bin) In second i'm writing data to the file passed by first service (1st service calls 2nd service) How can I test both services using mocks without making any real IO interractions? Just for example: 1st service: public class DefaultLogService implements LogService { public void log(SomeComplexData data) { serializer.write(new FileOutputStream(buildComplexFileStructure()), data); or serializer.write(buildComplexFileStructure(), data); or serializer.write(new GenericInputEntity(buildComplexFileStructure()), data); } private ComplextDataSerializer serializer; // mocked in tests } 2nd service: public class DefaultComplexDataSerializer implements ComplexDataSerializer { void write(InputStream stream, SomeComplexData data) {...} or void write(File file, SomeCompexData data) {...} or void write(GenericInputEntity entity, SomeComplexData data) {...} } In first case i need to pass FileOutputStream which will create a file (i.e. i can't test 1st service) In second case i need to pass File. What can i do in 2nd service test if I need to test data which will be written to specified file? (i can't test 2nd service) In third case i think i need some generic IO object which will wrap File. Maybe there is some ready-to-use solution for this purpose?

    Read the article

  • How do I mock a class property with mox?

    - by Harley
    I have a class: class myclass(object): @property def myproperty(self): return 'hello' Using mox and py.test, how do I mock out myproperty? I've tried: mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty = 'goodbye' and mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty.AndReturns('goodbye') but both fail with AttributeError: can't set attribute.

    Read the article

  • How to test a class that makes HTTP request and parse the response data in Obj-C?

    - by GuidoMB
    I Have a Class that needs to make an HTTP request to a server in order to get some information. For example: - (NSUInteger)newsCount { NSHTTPURLResponse *response; NSError *error; NSURLRequest *request = ISKBuildRequestWithURL(ISKDesktopURL, ISKGet, cookie, nil, nil); NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (!data) { NSLog(@"The user's(%@) news count could not be obtained:%@", username, [error description]); return 0; } NSString *regExp = @"Usted tiene ([0-9]*) noticias? no leídas?"; NSString *stringData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; NSArray *match = [stringData captureComponentsMatchedByRegex:regExp]; [stringData release]; if ([match count] < 2) return 0; return [[match objectAtIndex:1] intValue]; } The things is that I'm unit testing (using OCUnit) the hole framework but the problem is that I need to simulate/fake what the NSURLConnection is responding in order to test different scenarios and because I can't relay on the server to test my framework. So the question is Which is the best ways to do this?

    Read the article

  • How to mock a file with EasyMock?

    - by Todd
    Hello, I have recently been introduced to EasyMock and have been asked to develop some unit tests for a FileMonitor class using it. The FileMonitor class is based on a timed event that wakes up and checks for file modification(s) in a defined list of files and directories. I get how to do this using the actual file system, write a test that writes to a file and let the FileMonitor do its thing. So, how do I do this using EasyMock? I just don't get how to have EasyMock mock the file system. Thanks, Todd

    Read the article

  • How Moles Isolation framework is implemented?

    - by Buu Nguyen
    Moles is an isolation framework created by Microsoft. A cool feature of Moles is that it can "mock" static/non-virtual methods and sealed classes (which is not possible with frameworks like Moq). Below is the quick demonstration of what Moles can do: Assert.AreNotEqual(new DateTime(2012, 1, 1), DateTime.Now); // MDateTime is part of Moles; the below will "override" DateTime.Now's behavior MDateTime.NowGet = () => new DateTime(2012, 1, 1); Assert.AreEqual(new DateTime(2012, 1, 1), DateTime.Now); Seems like Moles is able to modify the CIL body of things like DateTime.Now at runtime. Since Moles isn't open-source, I'm curious to know which mechanism Moles uses in order to modify methods' CIL at runtime. Can anyone shed any light?

    Read the article

  • Mock static method Activator.CreateInstance to return a mock of another class

    - by Jeep87c
    I have this factory class and I want to test it correctly. Let's say I have an abstract class which have many child (inheritance). As you can see in my Factory class the method BuildChild, I want to be able to create an instance of a child class at Runtime. I must be able to create this instance during Runtime because the type won't be know before runtime. And, I can NOT use Unity for this project (if so, I would not ask how to achieve this). Here's my Factory class that I want to test: public class Factory { public AnAbstractClass BuildChild(Type childType, object parameter) { AnAbstractClass child = (AnAbstractClass) Activator.CreateInstance(childType); child.Initialize(parameter); return child; } } To test this, I want to find a way to Mock Activator.CreateInstance to return my own mocked object of a child class. How can I achieve this? Or maybe if you have a better way to do this without using Activator.CreateInstance (and Unity), I'm opened to it if it's easier to test and mock! I'm currently using Moq to create my mocks but since Activator.CreateInstance is a static method from a static class, I can't figure out how to do this (I already know that Moq can only create mock instances of objects). I took a look at Fakes from Microsoft but without success (I had some difficulties to understand how it works and to find some well explained examples). Please help me! EDIT: I need to mock Activator.CreateInstance because I want to force this method to return another mocked object. The correct thing I want is only to stub this method (not to mock it). So when I test BuildChild like this: [TestMethod] public void TestBuildChild() { var mockChildClass = new Mock(AChildClass); // TODO: Stub/Mock Activator.CreateInstance to return mockChildClass when called with "type" and "parameter" as follow. var type = typeof(AChildClass); var parameter = "A parameter"; var child = this._factory.BuildChild(type, parameters); } Activator.CreateInstance called with type and parameter will return my mocked object instead of creating a new instance of the real child class (not yet implemented).

    Read the article

  • Unit testing with JMS (ActiveMQ)

    - by larry cai
    How to do unit testing with JMS ? Is it some de-facto for this ? I googled something - Unit testing for JMS: http://activemq.apache.org/how-to-unit-test-jms-code.html - jmsTemplate: activemq.apache.org/jmstemplate-gotchas.html - mockRunner : mockrunner.sourceforge.net/ Do you have any good experience on those and suggestion for me ?

    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

  • Moq - How to mock a function call on a concrete object?

    - by dferraro
    Hello, How can I do this in Moq? Foo bar = new Foo(); Fake(bar.PrivateGetter).Return('whatever value') It seems I can only find how to mock an object that was created via the framework. I want to mock just a single method/property on a concrete object I've created... In TypeMock, I would just do Isolate.WhenCalled(bar.PrivateGetter).Returns('whatever value').. Any ideas?

    Read the article

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