Search Results

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

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

  • Mock a void method which change the input value

    - by Kar
    Hi, How could I mock a void method with parameters and change the value parameters? My void method looks like this: public interface IFoo { void GetValue(int x, object y) // takes x and do something then access another class to get the value of y } I prepared a delegate class: private delegate void GetValueDelegate(int x, object y); private void GetValue(int x, object y) { // process x // prepare a new object obj if (y == null) y = new Object(); if (//some checks) y = obj; } I wrote something like this: Expect.Call(delegate {x.GetValue(5, null);}).Do (new GetValueDelegate(GetValue)).IgnoreArguments().Repeat.Any(); But seems like it's not working. Any clue on what could be wrong?

    Read the article

  • C# Unit Testing - Generating Mock DataContexts / LINQ -> SQL classes

    - by gav
    Hi All, I am loving the new world that is C#, I've come to a point with my toy programs where I want to start writing some unit tests. My code currently uses a database via a DatabaseDataContext object (*.dbml file), what's the best way to create a mock for this object? Given how easy it is to generate the database LINQ - SQL code and how common a request this must be I'm hoping that VS2010 has built in functionality to help with testing. If I'm way off and this must be done manually could you please enlighten me as to your preferred approach? Many Thanks, Gavin

    Read the article

  • Mock Objects properties not changing

    - by frictionlesspulley
    I am new to using Mock test in .Net. I am testing out a financial transaction which is of the following nature: int amt =20; //sets all the props and func and returns a FinaceAccount. //Note I did not SetUp the amt of the account. var account =GetFinanceAccount() //service layer to be tested _financeService.tranx(account,amt); //checks if the amt was added to the account.amt //here the amt comes out same as that set in GetFinanceAccount. Assert.AreEqual(account.amt ,amt) I know that the function tranx works correctly but there is an issue with the test. Are there any GOOD reference material on Mocking in .Net

    Read the article

  • Framework for creating mock objects in Java

    - by Amir Rachum
    This is NOT a question about which is the best framework, etc. I have never used a mocking framework and I'm a bit puzzled by the idea. How does it know how to create the mock object? Is it done in runtime or generates a file? How do you know its behavior? And most importantly - what is the work flow of using such a framework (what is the step-by-step for creating a test). Can anyone explain? You can choose whichever framework you like for example, just say what it is.

    Read the article

  • Running a loop (such as one for a mock webserver) within a thread

    - by bob c
    I'm trying to run a mock webserver within a thread within a class. I've tried passing the class' @server property to the thread block but as soon as I try to do server.accept the thread stops. Is there some way to make this work? I want to basically be able to run a webserver off of this script while still taking user input via stdin.gets. Is this possible? class Server def initialize() @server = TCPServer.new(8080) end def run() @thread = Thread.new(@server) { |server| while true newsock = server.accept puts "some stuff after accept!" next if !newsock # some other stuff end } end end def processCommand() # some user commands here end test = Server.new while true do processCommand(STDIN.gets) end In the above sample, the thread dies on server.accept

    Read the article

  • not using partial mocking? do they also mean in web-app?

    - by 01
    Im learning Mockito and in chapter 16 they say you should not use partial mocking in new system. I disagree, for example in one of my actions i use partial mocking for static framework methods, sql calls, etc. I extracted the stuff into methods and then mock it in tests. Most of those methods are specific to this action and wont be call from other actions, so it not worth to extract special components. I agree that you shouldn't using partial mocking in frameworks, but not in hard to mock actions. What are minuses of using partial mocking in web-app?

    Read the article

  • How to mock HTTPSession/FlexSession with TestNG and some Mocking Framework

    - by ifischer
    I'm developing a web application running on Tomcat 6, with Flex as Frontend. I'm testing my backend with TestNG. Currently, I'm trying to test the following method in my Java-Backend: public UserPE login(String mail, String password) { UserPE dbuser = findUserByMail(mail); if (dbuser == null || !dbuser.getPassword().equals(password)) throw new RuntimeException("Invalid username and/or password"); // Save logged in user FlexSession session = FlexContext.getFlexSession(); session.setAttribute("user", dbuser); return dbuser; } The method needs access to the FlexContext which only exists when i run it on the Servlet container (don't bother if you don't know Flex, it's more a Java-Mocking question in general). Otherwise i get a Nullpointer exception when calling session.setAttribute(). Unfortunately, I cannot set the FlexContext from outside, which would make me able to set it from my tests. It's just obtained inside the method. What would be the best way to test this method with a Mocking framework, without changing the method or the class which includes the method? And which framework would be the easiest for this use case (there are hardly other things i have to mock in my app, it's pretty simple)? Sorry I could try out all of them for myself and see how i could get this to work, but i hope that i'll get a quickstart with some good advices!

    Read the article

  • Avoiding dispose of underlying stream

    - by danbystrom
    I'm attempting to mock some file operations. In the "real" object I have: StreamWriter createFile( string name ) { return new StreamWriter( Path.Combine( _outFolder, name ), false, Encoding.UTF8 ) ); } In the mock object I'd like to have: StreamWriter createFile( string name ) { var ms = new MemoryStream(); _files.Add( Path.Combine( _outFolder, name ), ms ); return new StreamWriter( ms, Encoding.UTF8 ) ); } where _files is a dictionary to store created files for later inspection. However, when the consumer closes the StreamWriter, it also disposes the MeamoryStream... :-( Any thoughts on how to pursue this?

    Read the article

  • Mockito verify no more interactions but omit getters

    - by michael lucas
    Mockito api provides method: Mockito.verifyNoMoreInteractions(someMock); but is it possible in Mockito to declare that I don't want more interactions with a given mock with the exceptions of interactions with its getter methods? The simple scenario is the one in which I test that sut changes only certain properties of a given mock and lefts other properties untapped. In example I want to test that UserActivationService changes property Active on an instance of class User but does't do anything to properties like Role, Password, AccountBalance, etc. I'm open to criticism regarding my approach to the problem.

    Read the article

  • Visual C++ overrides/mock objects for unit testing?

    - by Mark
    When I'm running unit tests, I want to be able to "stub out" or create a mock object, but I'm running into DLL Hell. For example: There are two DLL libraries built: A.dll and B.dll -- Classes in A.dll have calls to classes in B.dll so when A.dll was built, the link line was using B.lib for the defintions. My test driver (Foo.exe) is testing classes in A.dll, so it links against A.lib. However, I want to "stub out" some of the calls A.dll makes to B.dll with simple versions (return basic value, no DB look up, etc). I can't build an Override.dll that just overrides the needed methods (not entire classes) and replace B.dll because Foo.exe will A) complain that B.dll is missing if I just remove it and put Override.dll in it's place or B) if I rename Override.dll to B.dll, Foo.exe complains that there are unresolved symbols because Override.dll is not a complete implementation of B.dll. Is there a way to do this? Is there a way to statically link Foo.exe with A.lib, B.lib and Override.lib such that it will work without having to completely rebuild A.lib and B.lib to remove the __delcspec(dllexport)? Is there another option?

    Read the article

  • C# testing framework that works like JUnit in Eclipse?

    - by bluebomber357
    Hello all, I come from a Java/Eclipse background and I fear that I am spoiled by how easy it is to get JUnit and JMock running in Eclipse, and have that GUI with the bar and pass/fail information pop up. It just works with no hassle. I see a lot of great options for testing in C# with Visual Studio. NUnit looks really nice because it contains unit and mock testing all in one. The trouble is, I can't figure out how to get the IDE display my results. The NUnit documentation seems to show that it doesn't automatically show results through the VS IDE. I found http://testdriven.net/, which seems to trumpet that is makes VS display these stats and work with multiple frameworks, but it isn't open source. Is there anyway to get unit and mock testing working with the VS IDE like it does in Java with Eclipse?

    Read the article

  • How best to construct our test subjects in unit tests?

    - by Liath
    Some of our business logic classes require quite a few dependencies (in our case 7-10). As such when we come to unit test these the creation become quite complex. In most tests these dependencies are often not required (only some dependencies are required for particular methods). As a result unit tests often require a significant number of lines of code to mock up these useless dependencies (which can't be null because of null checks). For example: [Test] public void TestMethodA() { var dependency5 = new Mock<IDependency1>(); dependency5.Setup(x => x. // some setup var sut = new Sut(new Mock<IDependency1>().Object, new Mock<IDependency2>().Object, new Mock<IDependency3>().Object, new Mock<IDependency4>().Object, dependency5); Assert.SomeAssert(sut.MethodA()); } In this example almost half the test is taken up creating dependencies which aren't used. I've investigated an approach where I have a helper method. [Test] public void TestMethodA() { var dependency5 = new Mock<IDependency1>(); dependency5.Setup(x => x. // some setup var sut = CreateSut(null, null, null, null, dependency5); Assert.SomeAssert(sut.MethodA()); } private Sut CreateSut(IDependency1 d1, IDependency2 d2...) { return new Sut(d1 ?? new Mock<IDependency1>().Object, d2 ?? new Mock<IDependency2>().Object, } But these often grow very complicated very quickly. What is the best way to create these BLL classes in test classes to reduce complexity and simplify tests?

    Read the article

  • Mocking using boost::shared_ptr and AMOP

    - by Edison Gustavo Muenz
    Hi, I'm trying to write mocks using amop. I'm using Visual Studio 2008. I have this interface class: struct Interface { virtual void Activate() = 0; }; and this other class which receives pointers to this Interface, like this: struct UserOfInterface { void execute(Interface* iface) { iface->Activate(); } }; So I try to write some testing code like this: amop::TMockObject<Interface> mock; mock.Method(&Interface::Activate).Count(1); UserOfInterface user; user.execute((Interface*)mock); mock.Verifiy(); It works! So far so good, but what I really want is a boost::shared_ptr in the execute() method, so I write this: struct UserOfInterface { void execute(boost::shared_ptr<Interface> iface) { iface->Activate(); } }; How should the test code be now? I tried some things, like: amop::TMockObject<Interface> mock; mock.Method(&Interface::Activate).Count(1); UserOfInterface user; boost::shared_ptr<Interface> mockAsPtr((Interface*)mock); user.execute(mockAsPtr); mock.Verifiy(); It compiles, but obviously crashes, since at the end of the scope the variable 'mock' gets double destroyed (because of the stack variable 'mock' and the shared_ptr). I also tried to create the 'mock' variable on the heap: amop::TMockObject<Interface>* mock(new amop::TMockObject<Interface>); mock->Method(&Interface::Activate).Count(1); UserOfInterface user; boost::shared_ptr<Interface> mockAsPtr((Interface*)*mock); user.execute(mockAsPtr); mock->Verifiy(); But it doesn't work, somehow it enters an infinite loop, before I had a problem with boost not finding the destructor for the mocked object when the shared_ptr tried to delete the object. Has anyone used amop with boost::shared_ptr successfully?

    Read the article

  • How can i inject servletcontext in spring

    - by M.R.
    I need to write a junit test for a rather complex application which runs in a tomcat. I wrote a class which builds up my spring context. private static ApplicationContext springContext = null; springContext = new ClassPathXmlApplicationContext( new String[] {"beans"....}); In the application there is a call: public class myClass implements ServletContextAware { .... final String folder = servletContext.getRealPath("/example"); ... } which breaks everything, because the ServletContext is null. I have started to build a mock object: static ServletConfig servletConfigMock = createMock(ServletConfig.class); static ServletContext servletContextMock = createMock(ServletContext.class); @BeforeClass public static void setUpBeforeClass() throws Exception { expect(servletConfigMock.getServletContext()).andReturn(servletContextMock).anyTimes(); expect(servletContextMock.getRealPath("/example")).andReturn("...fulllpath").anyTimes(); replay(servletConfigMock); replay(servletContextMock); } Is there a simple methode to inject the ServletContext or to start the tomcat with a deployment descriptor at the runtime of the junit test? I am using: spring, maven, tomcat 6 and easymock for the mock objects.

    Read the article

  • Please help! Delegate returns null via Dipendency Injection.

    - by Raj Aththanayake
    Can someone please help? I use Google code’s Moq framework for mocking within my Unit Tests and Unity for Dependency Injection. In my Test class private Mock<ICustomerSearchService> CustomerSearchServiceMock = null; private CustomerService customerService = null; private void SetupMainData() { CustomerSearchServiceMock = new Mock<ICustomerSearchService>(); customerService = new CustomerService (); // CustomerSearchService is a property in CustomerService and dependency is configuered via Unity customerService.CustomerSearchService = CustomerSearchServiceMock.Object; Customer c = new Customer () { ID = "AT" }; CustomerSearchServiceMock.Setup(s => s.GetCustomer(EqualsCondition)).Returns(c); } [TestMethod] public void GetCustomerData_Test_Method() { SetupMainData() var customer = customerService.GetCustomerData("AT"); } public static bool EqualsCondition(Customer customer) { return customer.ID.Equals("AT"); } In my Test class CustomerService class public class CustomerService : ICustomerService { [Dependency] public ICustomerSearchService CustomerSearchService { get; set; } public IEnumerable<SomeObject> GetCustomerData(string custID) { I GET Null for customer ?????} var customer = CustomerSearchService.GetCustomer (c => c.ID.Equals(custID)); //Do more things } } When I debug the code I can see CustomerSearchService has a proxy object, but the customer returns as null. Any ideas? Or is there something missing here? Note: ICustomerSearchService I have implemented below method. Customer GetCustomer(Func<Customer, bool> predicate);

    Read the article

  • What C# mocking framework to use?

    - by Corin
    I want to start using mock objects on my next C# project. After a quick google I've found there are many: NMock EasyMock.NET TypeMock Isolator Commercial / Paid Rhino Mocks Moq So my question is: what one is your favourite .NET mocking framework and why?

    Read the article

  • How to Fake a AsyncToken return in ActionScript 3

    - by Brett
    Using Parsley, I have a service that I access through a [Command(selector='list')] public function getRssFeed( msg:RssEvent ):AsyncToken { return service.list() as AsyncToken; } when I point to the "Real" RssService, everything works as expected. My problem is when I point to the "Mock" RssService. I can't figure out how to fake a AsyncToken with some dummy data return... does anyone knows how to do this ?

    Read the article

  • Mocking using 'traditional' Record/Replay vs Moq model

    - by fung
    I'm new to mocks and am deciding on a mock framework. The Moq home quotes Currently, it's the only mocking library that goes against the generalized and somewhat unintuitive (especially for novices) Record/Reply approach from all other frameworks. Can anyone explain simply what the Record/Replay approach is and how Moq differs? What are the pros and cons of each especially from the point of deciding a framework? Thanks.

    Read the article

  • RSpec - mocking a class method

    - by Chris Kilmer
    I'm trying to mock a class method with rspec: lib/db.rb class Db def self.list(options) Db::Payload.list(options) end end lib/db/payload.rb class Db::Payload def self.list(options={}) end end In my spec, I'm trying to setup the expectation Db::Payload.list will be called when I call Db.list: describe Db do before(:each) do @options = {} Db::Payload.should_receive(:list).with(@options) end it 'should build the LIST payload' do Db.list(@options) end end The problem is that I am always receiving the following error: undefined method `should_receive' for Db::Payload:Class Any help understanding this error would be most appreciated :-)

    Read the article

  • Mocking with java 1.4

    - by Filip
    Is there any framework, whick allows to mock concrete classes, not only interfaces in java 1.4? I have third party code with a singleton class, where I wanna change one function, without touching orignal code. Is it possible?

    Read the article

  • How to mock/stub calls to message taglib in Grails controller

    - by Dave
    I've got a Grails controller which relies on the message taglib to resolve an i18n message: class TokenController { def passwordReset = { def token = DatedToken.findById(params.id); if (!isValidToken(token, params)) { flash.message = message(code: "forgotPassword.reset.invalidToken") redirect controller: 'forgotPassword', action: 'index' return } render view:'/forgotPassword/reset', model: [token: token.token] } } I've written a unit test for the controller: class TokenControllerTests extends ControllerUnitTestCase { void testPasswordResetInvalidTokenRedirect() { controller.passwordReset() assert... } } Since the message taglib is called in the controller I get a MissingMethodException: groovy.lang.MissingMethodException: No signature of method: TokenController.message() is applicable for argument types: (java.util.LinkedHashMap) values: [[code:forgotPassword.reset.invalidToken]] Does anyone know the best way to get around this issue in a unit test? Ideally I would like to perform assertions on the message but right now I'd be happy if the test just ran! Thanks

    Read the article

  • MVC UI with Mock Controllers?

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

    Read the article

  • Google Mock for iPhone development?

    - by Cliff
    I have an interesting situation where I am refactoring a bunch of ObjC iPhone code to create a C++ API. I'm a novice to C++ and looking into C++ mocking frameworks to augment the work I'd done using OCUnit and poor man's mocks. I ran across googlemock and wanted to know if anyone has ever used it for iPhone development? Also, how can I share this (or mockpp) with other devs as it is an installable package and doesn't seem to lend itself to checking into a repository?

    Read the article

  • Rhino Mocks Sample How to Mock Property

    - by guazz
    How can I test that "TestProperty" was set a value when ForgotMyPassword(...) was called? > public interface IUserRepository { User GetUserById(int n); } public interface INotificationSender { void Send(string name); int TestProperty { get; set; } } public class User { public int Id { get; set; } public string Name { get; set; } } public class LoginController { private readonly IUserRepository repository; private readonly INotificationSender sender; public LoginController(IUserRepository repository, INotificationSender sender) { this.repository = repository; this.sender = sender; } public void ForgotMyPassword(int userId) { User user = repository.GetUserById(userId); sender.Send("Changed password for " + user.Name); sender.TestProperty = 1; } } // Sample test to verify that send was called [Test] public void WhenUserForgetPasswordWillSendNotification_WithConstraints() { var userRepository = MockRepository.GenerateStub<IUserRepository>(); var notificationSender = MockRepository.GenerateStub<INotificationSender>(); userRepository.Stub(x => x.GetUserById(5)).Return(new User { Id = 5, Name = "ayende" }); new LoginController(userRepository, notificationSender).ForgotMyPassword(5); notificationSender.AssertWasCalled(x => x.Send(null), options => options.Constraints(Rhino.Mocks.Constraints.Text.StartsWith("Changed"))); }

    Read the article

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