Search Results

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

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

  • Need an advice for unit testing using mock object

    - by Andree
    Hi there, I just recently read about "Mocking objects" for unit testing and currently I'm having a difficulties implementing this approach in my application. Please let me explain my problem. I have a User model class, which is dependent on 2 data sources (database and facebook web service). The controller class simply use this User model as an interface to access data and it doesn't care about where the data came from. Currently I never done any unit test to this User model because it is dependent on an external web service. But just a while ago, I read about object mocking and now I know that it is a common approach to unit test a class that depends on external resources (like in my case). Now I want to create a unit test for the User model, but then I encountered a design issue: In order for the User model to use a mocked Facebook SDK, I have to inject this mocked Facebook SDK to the User object (probably using a setter). Therefore I can't construct the Facebook SDK inside the User object. I have to construct it outside the User object, and inject the SDK into the User object. The real client of my User model is the application's controller. Therefore I have to construct the Facebook SDK inside the controller and inject it to the user object. Well, this is a problem because I want my controller to be as clean as possible. I want my controller to be ignorant about the application's data source. I'm not good at explaining something systematically, so you'll probably sleeping before reading this last paragraph. But anyway, I want to ask if anyone here ever encountered the same problem as mine? How do you solve this problem? Regards, Andree

    Read the article

  • Creating mock Objects in PHP unit

    - by Mike
    Hi, I've searched but can't quite find what I'm looking for and the manual isn't much help in this respect. I'm fairly new to unit testing, so not sure if I'm on the right track at all. Anyway, onto the question. I have a class: <?php class testClass { public function doSomething($array_of_stuff) { return AnotherClass::returnRandomElement($array_of_stuff); } } ?> Now, clearly I want the AnotherClass::returnRandomElement($array_of_stuff); to return the same thing every time. My question is, in my unit test, how do I mockup this object? I've tried adding the AnotherClass to the top of the test file, but when I want to test AnotherClass I get the "Cannot redeclare class" error. I think I understand factory classes, but I'm not sure how I would apply that in this instance. Would I need to write an entirely seperate AnotherClass class which contained test data and then use the Factory class to load that instead of the real AnotherClass? Or is using the Factory pattern just a red herring. I tried this: $RedirectUtils_stub = $this->getMockForAbstractClass('RedirectUtils'); $o1 = new stdClass(); $o1->id = 2; $o1->test_id = 2; $o1->weight = 60; $o1->data = "http://www.google.com/?ffdfd=fdfdfdfd?route=1"; $RedirectUtils_stub->expects($this->any()) ->method('chooseRandomRoot') ->will($this->returnValue($o1)); $RedirectUtils_stub->expects($this->any()) ->method('decodeQueryString') ->will($this->returnValue(array())); in the setUp() function, but these stubs are ignored and I can't work out whether it's something I'm doing wrong, or the way I'm accessing the AnotherClass methods. Help! This is driving me nuts.

    Read the article

  • How to use jquery .animate() to mock 'text-align:right'

    - by mrwienerdog
    I am building a very simple jquery menu. On hover, I have a menu on the right easing to the left margin of my menu container. This is easy, as the text is left aligned within said container. However, I also have a menu on the left, and because the links (left justified) are of differing length, the best I can do is adjust the padding to ease the text a uniform amount between links. Therefor, long link text goes to the right edge of the container, buy short text only makes it about half way. In reading about this, I have learned that you can not modify the text align property as it is non numeric. Is there any other way to do this? I of course tried to go with: $('#selector').css('text-align':'right') but that made the text jump to the right instead of ease. Is there any way to ensure all links ease to the rightmost margin of the container?

    Read the article

  • Mocking Sort With Mocha

    - by josephmate
    How can I mock an array's sort expect a lambda expression? This is a trivial example of my problem: # initializing the data l = lambda { |a,b| a <=> b } array = [ 1, 2, 3, 4, 5 ] sorted_array = [ 2, 3, 8, 9, 1] # I expect that sort will be called using the lambda as a parameter array.expects(:sort).with( l ).returns( sorted_array ) # perform the sort using the lambda expression temp = array.sort{|a,b| l.call(a,b) } Now, at first I expected that this would work; however, I got the following error: - expected exactly once, not yet invoked: [ 1, 2, 3, 4, 5 ].sort(#<Proc:0xb665eb48>) Is there a way to do what I am looking for? Cheers, Joseph

    Read the article

  • removing dependancy of a private function inside a public function using Rhino Mocks

    - by L G
    Hi All, I am new to mocking, and have started with Rhino Mocks. My scenario is like this..in my class library i have a public function and inside it i have a private function call, which gets output from a service.I want to remove the private function dependency. public class Employee { public virtual string GetFullName(string firstName, string lastName) { string middleName = GetMiddleName(); return string.Format("{0} {2} {1}", firstName, lastName,middleName ); } private virtual string GetMiddleName() { // Some call to Service return "George"; } } This is not my real scenario though, i just wanted to know how to remove dependency of GetMiddleName() function and i need to return some default value while unit testing. Note : I won't be able to change the private function here..or include Interface..Keeping the functions as such, is there any way to mock this.Thank

    Read the article

  • Mocking attributes - C#

    - by bob
    I use custom Attributes in a project and I would like to integrate them in my unit-tests. Now I use Rhino Mocks to create my mocks but I don't see a way to add my attributes (and there parameters) to them. Did I miss something, or is it not possible? Other mocking framework? Or do I have to create dummy implementations with my attributes? example: I have an interface in a plugin-architecture (IPlugin) and there is an attribute to add meta info to a property. Then I look for properties with this attribute in the plugin implementation for extra processing (storing its value, mark as gui read-only...) Now when I create a mock can I add easily an attribute to a property or the object instance itself? EDIT: I found a post with the same question - link. The answer there is not 100% and it is Java... EDIT 2: It can be done... searched some more (on SO) and found 2 related questions (+ answers) here and here Now, is this already implemented in one or another mocking framework?

    Read the article

  • Is there a tool I can use to generate interfaces and wrappers for object mocking in c#

    - by fostandy
    Given a class like System.Timers.Timer, or ANY managed class (whether user defined, from the .net framework, or some 3rd party library) is there some program I can use to (a) generate an interface based on this class and (b) generate a wrapper for the given class? for example if I have a public class Foo { public object MyProperty { get { ... } set { ... } } public int SomeMethod(object a) { ... } } it will create an interface interface IFoo { object MyProperty { get; set; } int SomeMethod(object a) { ... } } and maybe even a wrapper class FooWrap { // something for relay constructor here ... Foo _me; public object MyProperty { get { return _me.MyProperty; } set { _me.MyProperty = value; } } public int SomeMethod(object a) { return _me.SomeMethod(); } } Obviously there's stuff I haven't thought about like events, generics etc. I want a DWIMNWIS-PSICHTO(-Plus-Stuff-I-Clearly-Haven't-Thought-Of). I'm aware resharper can be used to extract an interface but I've only been able to use this on my own classes. Aside: Wow, it is amazing how simply becoming accustomed to a previously 'unacceptable' idea eventually gives it legitimacy. A year ago the idea of having to create interfaces for all objects I want to mock and adopting an injection framework would have seemed like the height of madness. It turns out that while it's not quite death and taxes, it is sparta. I am aware of and have used typemock. It certainly is the work of elvish wizards. One day when $800 does not seem like quite so much money I intend to buy it.

    Read the article

  • Writing Unit Tests for an ASP.NET MVC Action Method that handles Ajax Request and Normal Request

    - by shiju
    In this blog post, I will demonstrate how to write unit tests for an ASP.NET MVC action method, which handles both Ajax request and normal HTTP Request. I will write a unit test for specifying the behavior of an Ajax request and will write another unit test for specifying the behavior of a normal HTTP request. Both Ajax request and normal request will be handled by a single action method. So the ASP.NET MVC action method will be execute HTTP Request object’s IsAjaxRequest method for identifying whether it is an Ajax request or not. So we have to create mock object for Request object and also have to make as a Ajax request from the unit test for verifying the behavior of an Ajax request. I have used NUnit and Moq for writing unit tests. Let me write a unit test for a Ajax request Code Snippet [Test] public void Index_AjaxRequest_Returns_Partial_With_Expense_List() {     // Arrange       Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);     //Add XMLHttpRequest request header     request.Setup(req => req["X-Requested-With"]).         Returns("XMLHttpRequest");       IEnumerable<Expense> fakeExpenses = GetMockExpenses();     expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as PartialViewResult;     // Assert     Assert.AreEqual("_ExpenseList", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories");         }   In the above unit test, we are calling Index action method of a controller named ExpenseController, which will returns a PartialView named _ExpenseList, if it is an Ajax request. We have created mock object for HTTPContextBase and setup XMLHttpRequest request header for Request object’s X-Requested-With for making it as a Ajax request. We have specified the ControllerContext property of the controller with mocked object HTTPContextBase. Code Snippet controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller); Let me write a unit test for a normal HTTP method Code Snippet [Test] public void Index_NormalRequest_Returns_Index_With_Expense_List() {     // Arrange               Mock<HttpRequestBase> request = new Mock<HttpRequestBase>();     Mock<HttpResponseBase> response = new Mock<HttpResponseBase>();     Mock<HttpContextBase> context = new Mock<HttpContextBase>();       context.Setup(c => c.Request).Returns(request.Object);     context.Setup(c => c.Response).Returns(response.Object);       IEnumerable<Expense> fakeExpenses = GetMockExpenses();       expenseRepository.Setup(x => x.GetMany(It.         IsAny<Expression<Func<Expense, bool>>>())).         Returns(fakeExpenses);     ExpenseController controller = new ExpenseController(         commandBus.Object, categoryRepository.Object,         expenseRepository.Object);     controller.ControllerContext = new ControllerContext(         context.Object, new RouteData(), controller);     // Act     var result = controller.Index(null, null) as ViewResult;     // Assert     Assert.AreEqual("Index", result.ViewName);     Assert.IsNotNull(result, "View Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<Expense>),             result.ViewData.Model, "Wrong View Model");     var expenses = result.ViewData.Model         as IEnumerable<Expense>;     Assert.AreEqual(3, expenses.Count(),         "Got wrong number of Categories"); }   In the above unit test, we are not specifying the XMLHttpRequest request header for Request object’s X-Requested-With, so that it will be normal HTTP Request. If this is a normal request, the action method will return a ViewResult with a view template named Index. The below is the implementation of Index action method Code Snippet public ActionResult Index(DateTime? startDate, DateTime? endDate) {     //If date is not passed, take current month's first and last date     DateTime dtNow;     dtNow = DateTime.Today;     if (!startDate.HasValue)     {         startDate = new DateTime(dtNow.Year, dtNow.Month, 1);         endDate = startDate.Value.AddMonths(1).AddDays(-1);     }     //take last date of start date's month, if end date is not passed     if (startDate.HasValue && !endDate.HasValue)     {         endDate = (new DateTime(startDate.Value.Year,             startDate.Value.Month, 1)).AddMonths(1).AddDays(-1);     }     var expenses = expenseRepository.GetMany(         exp => exp.Date >= startDate && exp.Date <= endDate);     //if request is Ajax will return partial view     if (Request.IsAjaxRequest())     {         return PartialView("_ExpenseList", expenses);     }     //set start date and end date to ViewBag dictionary     ViewBag.StartDate = startDate.Value.ToShortDateString();     ViewBag.EndDate = endDate.Value.ToShortDateString();     //if request is not ajax     return View("Index",expenses); }   The index action method will returns a PartialView named _ExpenseList, if it is an Ajax request and will returns a View named Index if it is a normal request. Source Code The source code has been taken from my EFMVC app which can download from here

    Read the article

  • Why Moq is thorwing "expected Invocation on the mock at least once". Where as it is being set once,e

    - by Mohit
    Following is the code. create a class lib add the ref to NUnit framework 2.5.3.9345 and Moq.dll 4.0.0.0 and paste the following code. Try running it on my machine it throws TestCase 'MoqTest.TryClassTest.IsMessageNotNull' failed: Moq.MockException : Expected invocation on the mock at least once, but was never performed: v = v.Model = It.Is(value(Moq.It+<c__DisplayClass21[MoqTest.GenInfo]).match) at Moq.Mock.ThrowVerifyException(IProxyCall expected, Expression expression, Times times, Int32 callCount) at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times) at Moq.Mock.VerifySet[T](Mock1 mock, Action1 setterExpression, Times times, String failMessage) at Moq.Mock1.VerifySet(Action`1 setterExpression) Class1.cs(22,0): at MoqTest.TryClassTest.IsMessageNotNull() using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; using NUnit.Framework; namespace MoqTest { [TestFixture] public class TryClassTest { [Test] public void IsMessageNotNull() { var mockView = new Mock<IView<GenInfo>>(); mockView.Setup(v => v.ModuleId).Returns(""); TryPresenter tryPresenter = new TryPresenter(mockView.Object); tryPresenter.SetMessage(new object(), new EventArgs()); // mockView.VerifySet(v => v.Message, Times.AtLeastOnce()); mockView.VerifySet(v => v.Model = It.Is<GenInfo>(x => x != null)); } } public class TryPresenter { private IView<GenInfo> view; public TryPresenter(IView<GenInfo> view) { this.view = view; } public void SetMessage(object sender, EventArgs e) { this.view.Model = null; } } public class MyView : IView<GenInfo> { #region Implementation of IView<GenInfo> public string ModuleId { get; set; } public GenInfo Model { get; set; } #endregion } public interface IView<T> { string ModuleId { get; set; } T Model { get; set; } } public class GenInfo { public String Message { get; set; } } } And if you change one line mockView.VerifySet(v = v.Model = It.Is(x = x != null)); to mockView.VerifySet(v = v.Model, Times.AtLeastOnce()); it works fine. I think Exception is incorrect.

    Read the article

  • Why Moq is throwing "expected Invocation on the mock at least once". Where as it is being set once,e

    - by Mohit
    Following is the code. create a class lib add the ref to NUnit framework 2.5.3.9345 and Moq.dll 4.0.0.0 and paste the following code. Try running it on my machine it throws TestCase 'MoqTest.TryClassTest.IsMessageNotNull' failed: Moq.MockException : Expected invocation on the mock at least once, but was never performed: v = v.Model = It.Is(value(Moq.It+<c__DisplayClass21[MoqTest.GenInfo]).match) at Moq.Mock.ThrowVerifyException(IProxyCall expected, Expression expression, Times times, Int32 callCount) at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times) at Moq.Mock.VerifySet[T](Mock1 mock, Action1 setterExpression, Times times, String failMessage) at Moq.Mock1.VerifySet(Action`1 setterExpression) Class1.cs(22,0): at MoqTest.TryClassTest.IsMessageNotNull() using System; using System.Collections.Generic; using System.Linq; using System.Text; using Moq; using NUnit.Framework; namespace MoqTest { [TestFixture] public class TryClassTest { [Test] public void IsMessageNotNull() { var mockView = new Mock<IView<GenInfo>>(); mockView.Setup(v => v.ModuleId).Returns(""); TryPresenter tryPresenter = new TryPresenter(mockView.Object); tryPresenter.SetMessage(new object(), new EventArgs()); // mockView.VerifySet(v => v.Message, Times.AtLeastOnce()); mockView.VerifySet(v => v.Model = It.Is<GenInfo>(x => x != null)); } } public class TryPresenter { private IView<GenInfo> view; public TryPresenter(IView<GenInfo> view) { this.view = view; } public void SetMessage(object sender, EventArgs e) { this.view.Model = null; } } public class MyView : IView<GenInfo> { #region Implementation of IView<GenInfo> public string ModuleId { get; set; } public GenInfo Model { get; set; } #endregion } public interface IView<T> { string ModuleId { get; set; } T Model { get; set; } } public class GenInfo { public String Message { get; set; } } } And if you change one line mockView.VerifySet(v => v.Model = It.Is<GenInfo>(x => x != null)); to mockView.VerifySet(v => v.Model, Times.AtLeastOnce()); it works fine. I think Exception is incorrect.

    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

  • Using mocks to set up object even if you will not be mocking any behavior or verifying any interaction with it?

    - by smp7d
    When building a unit test, is it appropriate to use a mocking tool to assist you in setting up an object even if you will not be mocking any behavior or verifying any interaction with that object? Here is a simple example in pseudo-code: //an object we actually want to mock Object someMockedObject = Mock(Object.class); EqualityChecker checker = new EqualityChecker(someMockedObject); //an object we are mocking only to avoid figuring out how to instantiate or //tying ourselves to some constructor that may be removed in the future ComplicatedObject someObjectThatIsHardToInstantiate = Mock(ComplicatedObject.class); //set the expectation on the mock When(someMockedObject).equals(someObjectThatIsHardToInstantiate).return(false); Assert(equalityChecker.check(someObjectThatIsHardToInstantiate)).isFalse(); //verify that the mock was interacted with properly Verify(someMockedObject).equals(someObjectThatIsHardToInstantiate).oneTime(); Is it appropriate to mock ComplicatedObject in this scenario?

    Read the article

  • Trouble with RSpec's with method

    - by Thiago
    Hi there, I've coded the following spec: it "should call user.invite_friend" do user = mock_model(User, :id = 1) other_user = mock_model(User, :id = 2) User.stub!(:find).with(user.id).and_return(user) User.stub!(:find).with(other_user.id).and_return(other_user) user.should_receive(:invite_friend).with(other_user) post :invite, { :id = other_user.id }, {:user_id = user.id} end But I'm getting the following error when I run the specs NoMethodError in 'UsersController POST invite should call user.invite_friend' undefined method `find' for # Class:0x86d6918 app/controllers/users_controller.rb:144:in `invite' ./spec/controllers/users_controller_spec.rb:13: What's the mistake? Without .with it works just fine, but I want different return values for different arguments to the stub method. The following controller's actions might be relevant: def invite me.invite_friend(User.find params[:id]) respond_to do |format| format.html { redirect_to user_path(params[:id]) } end end def me User.find(session[:user_id]) end

    Read the article

  • How to create tests for poco objects

    - by Simon G
    Hi, I'm new to mocking/testing and wanting to know what level should you go to when testing. For example in my code I have the following object: public class RuleViolation { public string ErrorMessage { get; private set; } public string PropertyName { get; private set; } public RuleViolation( string errorMessage ) { ErrorMessage = errorMessage; } public RuleViolation( string errorMessage, string propertyName ) { ErrorMessage = errorMessage; PropertyName = propertyName; } } This is a relatively simple object. So my question is: Does it need a unit test? If it does what do I test and how? Thanks

    Read the article

  • Junit and EasyMock understanding clarifications

    - by harigm
    Still Now I am using JUnit, I came across EasyMock, I am understanding both are for the same purpose. Is my understanding correct? What are the advantages does EasyMock has over the Junit? Which one is easier to configure? Does EasyMock has any limitations? Please help me to learn

    Read the article

  • Using jmock how to reuse parameter

    - by BenZen
    I'm building a test, in wich i need to send question, and wait for the answer. Message passing is not the problem. In fact to figure out wich answer correspond to wich question, i use an id. My id is generated using an UUID. an i want to retrieve this id, wich is given as a parameter to a mocked object. It look like this: oneOf(message).setJMSCorrelationID(with(correlationId)); inSequence(sequence); Where correlationId is the string i'd like to keep for an other expecteation like this one: oneOf(session).createBrowser(with(inputChannel), with("JMSType ='pong' AND JMSCorrelationId = '"+correlationId+"'")); have you got an answer?

    Read the article

  • mocking command object in grails controller results in hasErrors() return false no matter what! Plea

    - by egervari
    I have a controller that uses a command object in a controller action. When mocking this command object in a grails' controller unit test, the hasErrors() method always returns false, even when I am purposefully violating its constraints. def save = { RegistrationForm form -> if(form.hasErrors()) { // code block never gets executed } else { // code block always gets executed } } In the test itself, I do this: mockCommandObject(RegistrationForm) def form = new RegistrationForm(emailAddress: "ken.bad@gmail", password: "secret", confirmPassword: "wrong") controller.save(form) I am purposefully giving it a bad email address, and I am making sure the password and the confirmPassword properties are different. In this case, hasErrors() should return true... but it doesn't. I don't know how my testing can be any where reliable if such a basic thing does not work :/ Here is the RegistrationForm class, so you can see the constraints I am using: class RegistrationForm { def springSecurityService String emailAddress String password String confirmPassword String getEncryptedPassword() { springSecurityService.encodePassword(password) } static constraints = { emailAddress(blank: false, email: true) password(blank: false, minSize:4, maxSize: 10) confirmPassword(blank: false, validator: { confirmPassword, form -> confirmPassword == form.password }) } }

    Read the article

  • Automatically creating DynaActionForms in Mockrunner via struts-config.xml

    - by T Reddy
    I'm switching from MockStrutsTestCase to Mockrunner and I'm finding that having to manually re-create all of my DynaActionForms in Mockrunner is a pain...there has to be an easier way?! Can somebody offer a tip to simplify this process? For instance, this form bean definition in struts-config.xml: <form-bean name="myForm" type="org.apache.struts.action.DynaActionForm"> <form-property name="property" type="java.lang.String"/> </form-bean> results in this code in Mockrunner: //define form config FormBeanConfig config = new FormBeanConfig(); config.setName("myForm"); config.setType(DynaActionForm.class.getName()); FormPropertyConfig property = new FormPropertyConfig(); property.setName("property"); property.setType("java.lang.String"); config.addFormPropertyConfig(property); //create mockrunner objects ActionMockObjectFactory factory = new ActionMockObjectFactory(); ActionTestModule module = new ActionTestModule(factory); DynaActionForm form = module.createDynaActionForm(config); Now imagine that I have dozens of DynaActionForms with dozens of attributes...that stinks!

    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

  • What is the best way to use Guice and JMock together?

    - by Yishai
    I have started using Guice to do some dependency injection on a project, primarily because I need to inject mocks (using JMock currently) a layer away from the unit test, which makes manual injection very awkward. My question is what is the best approach for introducing a mock? What I currently have is to make a new module in the unit test that satisfies the dependencies and bind them with a provider that looks like this: public class JMockProvider<T> implements Provider<T> { private T mock; public JMockProvider(T mock) { this.mock = mock; } public T get() { return mock; } } Passing the mock in the constructor, so a JMock setup might look like this: final CommunicationQueue queue = context.mock(CommunicationQueue.class); final TransactionRollBack trans = context.mock(TransactionRollBack.class); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(CommunicationQueue.class).toProvider(new JMockProvider<QuickBooksCommunicationQueue>(queue)); bind(TransactionRollBack.class).toProvider(new JMockProvider<TransactionRollBack>(trans)); } }); context.checking(new Expectations() {{ oneOf(queue).retrieve(with(any(int.class))); will(returnValue(null)); never(trans); }}); injector.getInstance(RunResponse.class).processResponseImpl(-1); Is there a better way? I know that AtUnit attempts to address this problem, although I'm missing how it auto-magically injects a mock that was created locally like the above, but I'm looking for either a compelling reason why AtUnit is the right answer here (other than its ability to change DI and mocking frameworks around without changing tests) or if there is a better solution to doing it by hand.

    Read the article

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