Search Results

Search found 209 results on 9 pages for 'mocks'.

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

  • 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

  • Version control - stubs and mocks

    - by Tesserex
    For the sake of this question, I don't care about the difference between stubs, mocks, dummies, fakes, etc. Let's say I'm working on a project with one other person. I'm working on component A and he is working on component B. They work together, so I stub out B for testing, and he stubs out A. We're working in a DVCS, let's say Git, because that's actually the case here. When it comes time to merge our components together, we need to get the "real" files from my A and his B, but throw away all the fake stuff. During development, it's likely (unless I need to learn how to properly stub things) that the fakes have the same file names and class names as the real thing. So my question is: what is the proper procedure for doing version control on the fakes, and how are the components correctly merged, making sure to grab the real thing and not the fake? I would guess that one way is just do the merge, expect it to say CONFLICT, and then manually delete all the fake code out of the half-merged files. But this sounds tedious and inefficient. Should the fake things not go under VC at all? Should they be ripped out just before merging? Sorry if the answer to this should be obvious or trivial, I'm just looking for a "suggested practice" here.

    Read the article

  • Unit testing with Mocks. Test behaviour not implementation

    - by Kenny Eliasson
    Hi.. I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided. Like the code provided below. public class UserRegistrationProcess : IUserRegistration { private readonly IRepository _repository; private readonly ISmsService _smsService; public UserRegistrationProcess(IRepository repository, ISmsService smsService) { _repository = repository; _smsService = smsService; } public void Register(string phone) { var user = new User(phone); _repository.Save(user); _smsService.Send(phone, "Welcome", "Message!"); } } It is a really simple class but how would you go about and test it? At the moment im using Mocks but I dont really like it [Test] public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase() { var repository = new Mock<IRepository>(); var smsService = new Mock<ISmsService>(); var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object); var phone = "0768524440"; userRegistration.Register(phone); repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once()); } [Test] public void WhenRegistreringANewUser_ItWillSendANewSms() { var repository = new Mock<IRepository>(); var smsService = new Mock<ISmsService>(); var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object); var phone = "0768524440"; userRegistration.Register(phone); smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once()); } It feels like I am testing the wrong thing here? Any thoughts on how to make this better?

    Read the article

  • RhinoMocks: how to test if method was called when using PartialMock

    - by epitka
    I have a clas that is something like this public class MyClass { public virtual string MethodA(Command cmd) { //some code here} public void MethodB(SomeType obj) { // do some work MethodA(command); } } I mocked MyClass as PartialMock (mocks.PartialMock<MyClass>) and I setup expectation for MethodA var cmd = new Command(); //set the cmd to expected state Expect.Call(MyClass.MethodA(cmd)).Repeat.Once(); Problem is that MethodB calls actual implementation of MethodA instead of mocking it up. I must be doing something wrong (not very experienced with RhinoMocks). How do I force it to mock MetdhodA? Here is the actual code: var cmd = new SetBaseProductCoInsuranceCommand(); cmd.BaseProduct = planBaseProduct; var insuredType = mocks.DynamicMock<InsuredType>(); Expect.Call(insuredType.Code).Return(InsuredTypeCode.AllInsureds); cmd.Values.Add(new SetBaseProductCoInsuranceCommand.CoInsuranceValues() { CoInsurancePercent = 0, InsuredType = insuredType, PolicySupplierType = ppProvider }); Expect.Call(() => service.SetCoInsurancePercentages(cmd)).Repeat.Once(); mocks.ReplayAll(); //act service.DefaultCoInsurancesFor(planBaseProduct); //assert service.AssertWasCalled(x => x.SetCoInsurancePercentages(cmd),x=>x.Repeat.Once());

    Read the article

  • Injecting Mockito mocks into a Spring bean

    - by teabot
    I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired annotation on private member fields. I have considered using ReflectionTestUtils.setField but the bean instance that I wish to inject is actually a proxy and hence does not declare the private member fields of the target class. I do not wish to create a public setter to the dependency as I will then be modifying my interface purely for the purposes of testing. I have followed some advice given by the Spring community but the mock does not get created and the auto-wiring fails: <bean id="dao" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="com.package.Dao" /> </bean> The error I currently encounter is as follows: ... Caused by: org...NoSuchBeanDefinitionException: No matching bean of type [com.package.Dao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: { @org...Autowired(required=true), @org...Qualifier(value=dao) } at org...DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(D...y.java:901) at org...DefaultListableBeanFactory.doResolveDependency(D...y.java:770) If I set the constructor-arg value to something invalid no error occurs when starting the application context.

    Read the article

  • Unit testing with Mocks when SUT is leveraging Task Parallel Libaray

    - by StevenH
    I am trying to unit test / verify that a method is being called on a dependency, by the system under test. The depenedency is IFoo. The dependent class is IBar. IBar is implemented as Bar. Bar will call Start() on IFoo in a new (System.Threading.Tasks.)Task, when Start() is called on Bar instance. Unit Test (Moq): [Test] public void StartBar_ShouldCallStartOnAllFoo_WhenFoosExist() { //ARRANGE //Create a foo, and setup expectation var mockFoo0 = new Mock<IFoo>(); mockFoo0.Setup(foo => foo.Start()); var mockFoo1 = new Mock<IFoo>(); mockFoo1.Setup(foo => foo.Start()); //Add mockobjects to a collection var foos = new List<IFoo> { mockFoo0.Object, mockFoo1.Object }; IBar sutBar = new Bar(foos); //ACT sutBar.Start(); //Should call mockFoo.Start() //ASSERT mockFoo0.VerifyAll(); mockFoo1.VerifyAll(); } Implementation of IBar as Bar: class Bar : IBar { private IEnumerable<IFoo> Foos { get; set; } public Bar(IEnumerable<IFoo> foos) { Foos = foos; } public void Start() { foreach(var foo in Foos) { Task.Factory.StartNew( () => { foo.Start(); }); } } } I appears that the issue is obviously due to the fact that the call to "foo.Start()" is taking place on another thread (/task), and the mock (Moq framework) can't detect it. But I could be wrong. Thanks

    Read the article

  • rspec mocks: verify expectations in it "should" methods?

    - by Derick Bailey
    I'm trying to use rspec's mocking to setup expectations that I can verify in the it "should" methods... but I don't know how to do this... when i call the .should_receive methods on the mock, it verifies the expected call as soon as the before :all method exits. here's a small example: describe Foo, "when doing something" do before :all do Bar.should_recieve(:baz) foo = Foo.new foo.create_a_Bar_and_call_baz end it "should call the bar method" do # ??? what do i do here? end end How can i verify the expected call in the 'it "should"' method? do i need to use mocha or another mocking framework instead of rspec's? or ???

    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

  • IgnoreArguments including an Action<T>

    - by James L
    I'm probably missing something obvious here, so apologies in advance! Using Rhino Mocks, how do I set an expectation that a method taking an Action will be called, but I want to use IgnoreArguments. Obviously I can't specify null as that isn't an Action, and I dont want any meaningless code in the test. As I said, it's probably obvious by the syntax is eluding me at the moment!

    Read the article

  • Disable selected automated tests at runtime

    - by squig
    Is is posable to disable selected automated tests at runtime? I'm using VSTS and rhino mocks and have some intergation tests that require an external dependancy to be installed (MQ). Not all the developers on my team have this installed. Currently all the tests that require MQ inherit from a base class that checks if MQ is installed and if is not sets the test result to inconclusive. This works as it stops the tests from running, but marks the test run as unsuccseessful and can hide other failures. Any ideas?

    Read the article

  • Mock Assertions on objects inside Parallel ForEach's???

    - by jacko
    Any idea how we can assert a mock object was called when it is being accessed inside Parallel.ForEach via a closure? I assume that because each invocation is on a different thread that Rhino Mocks loses track of the object? Pseudocode: var someStub = MockRepository.GenerateStub() Parallel.Foreach(collectionOfInts, anInt => someStub.DoSomething(anInt)) someStub.AssertWasCalled(s => s.DoSomething, Repeat.Five.Times) This test will return an expectation violation, expecting the stub to be called 5 times but being actually called 0 times. Any ideas how we can tell the lambdas to keep track of the thread-local stub object?

    Read the article

  • What is wrong with Stubs for unit testing?

    - by MatthewMartin
    I just watched this funny YouTube Video about unit testing (it's Hitler with fake subtitles chewing out his team for not doing good unit tests--skip it if you're humor impaired) where stubs get roundly criticized. But I don't understand what wrong with stubs. I haven't started using a mocking framework and I haven't started feeling the pain from not using one. Am I in for a world a hurt sometime down the line, having chosen handwritten stubs and fakes instead of mocks (like Rhinomock etc)? (using Fowler's taxonomy) What are the considerations for picking between a mock and handwritten stub?

    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

  • What is the best testing pattern for checking that parameters are being used properly?

    - by Joseph
    I'm using Rhino Mocks to try to verify that when I call a certain method, that the method in turn will properly group items and then call another method. Something like this: //Arrange var bucketsOfFun = new BucketGame(); var balls = new List<IBall> { new Ball { Color = Color.Red }, new Ball { Color = Color.Blue }, new Ball { Color = Color.Yellow }, new Ball { Color = Color.Orange }, new Ball { Color = Color.Orange } }; //Act bucketsOfFun.HaveFunWithBucketsAndBalls(balls); //Assert ??? Here is where the trouble begins for me. My method is doing something like this: public void HaveFunWithBucketsAndBalls(IList<IBall> balls) { //group all the balls together according to color var blueBalls = GetBlueBalls(balls); var redBalls = GetRedBalls(balls); // you get the idea HaveFunWithABucketOfBalls(blueBalls); HaveFunWithABucketOfBalls(redBalls); // etc etc with all the different colors } public void HaveFunWithABucketOfBalls(IList<IBall> colorSpecificBalls) { //doing some stuff here that i don't care about //for the test i'm writing right now } What I want to assert is that each time I call HaveFunWithABucketOfBalls that I'm calling it with a group of 1 red ball, then 1 blue ball, then 1 yellow ball, then 2 orange balls. If I can assert that behavior then I can verify that the method is doing what I want it to do, which is grouping the balls properly. Any ideas of what the best testing pattern for this would be?

    Read the article

  • Need help mocking a ASP.NET Controller in RhinoMocks

    - by Pure.Krome
    Hi folks, I'm trying to mock up a fake ASP.NET Controller. I don't have any concrete controllers, so I was hoping to just mock a Controller and it will work. This is what I have, currently. _fakeRequestBase = MockRepository.GenerateMock<HttpRequestBase>(); _fakeRequestBase.Stub(x => x.HttpMethod).Return("GET"); _fakeContextBase = MockRepository.GenerateMock<HttpContextBase>(); _fakeContextBase.Stub(x => x.Request).Return(_fakeRequestBase); var controllerContext = new ControllerContext(_fakeContextBase, new RouteData(), MockRepository.GenerateMock<ControllerBase>()); _fakeController = MockRepository.GenerateMock<Controller>(); _fakeController.Stub(x => x.ControllerContext).Return(controllerContext); Everything works except the last line, which throws a runtime error and is asking me for some Rhino.Mocks source code or something (which I don't have). See how I'm trying to mock up an abstract Controller - is that allowed? Can someone help me?

    Read the article

  • Mocking objects with complex Lambda Expressions as parameters

    - by iCe
    Hi there, I´m encountering this problem trying to mock some objects that receive complex lambda expressions in my projects. Mostly with with proxy objects that receive this type of delegate: Func<Tobj, Fun<TParam1, TParam2, TResult>> I have tried to use Moq as well as RhinoMocks to acomplish mocking those types of objects, however both fail. (Moq fails with NotSupportedException, and in RhinoMocks simpy does not satisgy expectation). This is simplified example of what I´m trying to do: I have a Calculator object that does calculations: public class Calculator { public Calculator() { } public int Add(int x, int y) { var result = x + y; return result; } public int Substract(int x, int y) { var result = x - y; return result; } } I need to validate parameters on every method in the Calculator class, so to keep with the Single Responsability principle, I create a validator class. I wire everything up using a Proxy class, that prevents having duplicate code: public class CalculatorProxy : CalculatorExample.ICalculatorProxy { private ILimitsValidator _validator; public CalculatorProxy(Calculator _calc, ILimitsValidator _validator) { this.Calculator = _calc; this._validator = _validator; } public int Operation(Func&lt;Calculator, Func&lt;int, int, int&gt;&gt; operation, int x, int y) { _validator.ValidateArgs(x, y); var calcMethod = operation(this.Calculator); var result = calcMethod(x, y); _validator.ValidateResult(result); return result; } public Calculator Calculator { get; private set; } } Now, I´m testing a component that does use the CalculatorProxy, so I want to mock it, for example using Rhino Mocks: [TestMethod] public void ParserWorksWithCalcultaroProxy() { var calculatorProxyMock = MockRepository.GenerateMock&lt;ICalculatorProxy&gt;(); calculatorProxyMock.Expect(x =&gt; x.Calculator).Return(_calculator); calculatorProxyMock.Expect(x =&gt; x.Operation(c =&gt; c.Add, 2, 2)).Return(4); var mathParser = new MathParser(calculatorProxyMock); mathParser.ProcessExpression("2 + 2"); calculatorProxyMock.VerifyAllExpectations(); } However I cannot get it to work! Any ideas about how this can be done? Thanks a lot!

    Read the article

  • How to invoke WPF Dispatcher in Nunit?

    - by Reporting Avatar
    I want to test an application which renders a text block with a data field value. I would like to get the actual width and actual height, once the rendering completes. Everything works fine. The problem came first, when I tried to test the application. I'm unable to invoke the dispatcher from the test project. Following is the code. this.Loaded += (s, e) => { TextBlock textBlock1 = new TextBlock(); //// Text block value is assigned from data base field. textBlock1.Text = strValueFromDataBaseField; //// Setting the wrap behavior. textBlock1.TextWrapping = TextWrapping.WrapWithOverflow; //// Adding the text block to the layout canvas. this.layoutCanvas.Children.Add(textBlock1); this.Dispatcher.BeginInvoke(DispatcherPriority.Background, (Action)(() => { //// After rendering the text block with the data base field value. Measuring the actual width and height. this.TextBlockActualWidth = textBlock1.ActualWidth; this.TextBlockActualHeight = textBlock1.ActualHeight; //// Other calculations based on the actual widht and actual height. } )); }; I've just started using the NUnit. So, please help me. Thanks

    Read the article

  • RhinoMocks AAA Syntax

    - by Bill Campbell
    Hi, I've spent a good part of the day trying to figure out why a simple RhinoMocks test doesn't return the value I'm setting in the return. I'm sure that I'm just missing something really simple but I can't figure it out. Here's my test: [TestMethod] public void CopyvRAFiles_ShouldCallCopyvRAFiles_ShouldReturnTrue2() { FileInfo fi = new FileInfo(@"c:\Myprogram.txt"); FileInfo[] myFileInfo = new FileInfo[2]; myFileInfo[0] = fi; myFileInfo[1] = fi; var mockSystemIO = MockRepository.GenerateMock<ISystemIO>(); mockSystemIO.Stub(x => x.GetFilesForCopy("c:")).Return(myFileInfo); mockSystemIO.Expect(y => y.FileCopyDateCheck(@"c:\Myprogram.txt", @"c:\Myprogram.txt")).Return("Test"); CopyFiles copy = new CopyFiles(mockSystemIO); List<string> retValue = copy.CopyvRAFiles("c:", "c:", new AdminWindowViewModel(vRASharedData)); mockSystemIO.VerifyAllExpectations(); } I have an interface for my SystemIO class I'm passing in a mock for that to my CopyFiles class. I'm setting an expectation on my FileCopyDatCheck method and saying that it should Return("Test"). When I step through the code, it returns a null insteaed. Any ideas what I'm missing here? Here's my CopyFiles class Method: public List<string> CopyvRAFiles(string currentDirectoryPath, string destPath, AdminWindowViewModel adminWindowViewModel) { string fileCopied; List<string> filesCopied = new List<string>(); try { sysIO.CreateDirectoryIfNotExist(destPath); FileInfo[] files = sysIO.GetFilesForCopy(currentDirectoryPath); if (files != null) { foreach (FileInfo file in files) { fileCopied = sysIO.FileCopyDateCheck(file.FullName, destPath + file.Name); filesCopied.Add(fileCopied); } } //adminWindowViewModel.CheckFilesThatRequireSystemUpdate(filesCopied); return filesCopied; } catch (Exception ex) { ExceptionPolicy.HandleException(ex, "vRAClientPolicy"); Console.WriteLine("{0} Exception caught.", ex); ShowErrorMessageDialog(ex); return null; } } I would think that "fileCopied" would have the Return value set by the Expect. The GetFilesForCopy returns the two files in myFileInfo. Please Help. :) thanks in advance!

    Read the article

  • How to write a test for accounts controller for forms authenticate

    - by Anil Ali
    Trying to figure out how to adequately test my accounts controller. I am having problem testing the successful logon scenario. Issue 1) Am I missing any other tests.(I am testing the model validation attributes separately) Issue 2) Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() and Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() test are not passing. I have narrowed it down to the line where i am calling _membership.validateuser(). Even though during my mock setup of the service i am stating that i want to return true whenever validateuser is called, the method call returns false. Here is what I have gotten so far AccountController.cs [HandleError] public class AccountController : Controller { private IMembershipService _membershipService; public AccountController() : this(null) { } public AccountController(IMembershipService membershipService) { _membershipService = membershipService ?? new AccountMembershipService(); } [HttpGet] public ActionResult LogOn() { return View(); } [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (_membershipService.ValidateUser(model.UserName,model.Password)) { if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Overview"); } ModelState.AddModelError("*", "The user name or password provided is incorrect."); } return View(model); } } AccountServices.cs public interface IMembershipService { bool ValidateUser(string userName, string password); } public class AccountMembershipService : IMembershipService { public bool ValidateUser(string userName, string password) { throw new System.NotImplementedException(); } } AccountControllerFacts.cs public class AccountControllerFacts { public static AccountController GetAccountControllerForLogonSuccess() { var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>(); var controller = new AccountController(membershipServiceStub); membershipServiceStub .Stub(x => x.ValidateUser("someuser", "somepass")) .Return(true); return controller; } public static AccountController GetAccountControllerForLogonFailure() { var membershipServiceStub = MockRepository.GenerateStub<IMembershipService>(); var controller = new AccountController(membershipServiceStub); membershipServiceStub .Stub(x => x.ValidateUser("someuser", "somepass")) .Return(false); return controller; } public class LogOn { [Fact] public void Get_ReturnsViewResultWithDefaultViewName() { // Arrange var controller = GetAccountControllerForLogonSuccess(); // Act var result = controller.LogOn(); // Assert Assert.IsType<ViewResult>(result); Assert.Empty(((ViewResult)result).ViewName); } [Fact] public void Put_ReturnsOverviewRedirectToRouteResultIfLogonSuccessAndNoReturnUrlGiven() { // Arrange var controller = GetAccountControllerForLogonSuccess(); var user = new LogOnModel(); // Act var result = controller.LogOn(user, null); var redirectresult = (RedirectToRouteResult) result; // Assert Assert.IsType<RedirectToRouteResult>(result); Assert.Equal("Overview", redirectresult.RouteValues["controller"]); Assert.Equal("Index", redirectresult.RouteValues["action"]); } [Fact] public void Put_ReturnsRedirectResultIfLogonSuccessAndReturnUrlGiven() { // Arrange var controller = GetAccountControllerForLogonSuccess(); var user = new LogOnModel(); // Act var result = controller.LogOn(user, "someurl"); var redirectResult = (RedirectResult) result; // Assert Assert.IsType<RedirectResult>(result); Assert.Equal("someurl", redirectResult.Url); } [Fact] public void Put_ReturnsViewIfInvalidModelState() { // Arrange var controller = GetAccountControllerForLogonFailure(); var user = new LogOnModel(); controller.ModelState.AddModelError("*","Invalid model state."); // Act var result = controller.LogOn(user, "someurl"); var viewResult = (ViewResult) result; // Assert Assert.IsType<ViewResult>(result); Assert.Empty(viewResult.ViewName); Assert.Same(user,viewResult.ViewData.Model); } [Fact] public void Put_ReturnsViewIfLogonFailed() { // Arrange var controller = GetAccountControllerForLogonFailure(); var user = new LogOnModel(); // Act var result = controller.LogOn(user, "someurl"); var viewResult = (ViewResult) result; // Assert Assert.IsType<ViewResult>(result); Assert.Empty(viewResult.ViewName); Assert.Same(user,viewResult.ViewData.Model); Assert.Equal(false,viewResult.ViewData.ModelState.IsValid); } } }

    Read the article

  • When using a mocking framework and MSPEC where do you set your stubs

    - by Kev Hunter
    I am relatively new to using MSpec and as I write more and more tests it becomes obvious to reduce duplication you often have to use a base class for your setup as per Rob Conery's article I am happy with using the AssertWasCalled method to verify my expectations, but where do you set up a stub's return value, I find it useful to set the context in the base class injecting my dependencies but that (I think) means that I need to set my stubs up in the Because delegate which just feels wrong. Is there a better approach I am missing?

    Read the article

  • How to use the AAA syntax to do an AssertWasCalled but ignore arguments

    - by Toran Billups
    I'm using the new AAA syntax and wanted to know the syntax to do the below and have the mock ignore the agruments. mockAccount.AssertWasCalled(account = account.SetPassword("dsfdslkj")); I think the below is how I would do this with the record/ replay model but I wanted to see if this could be done with AAA using 3.6 mockAccount.Expect(account = account.SetPassword("sdfdsf")).IgnoreArguments(); mockAccount.VerifyAllExpectations(); Thank you in advance

    Read the article

  • Mocking View with RhinoMocks

    - by blu
    We are using MVP (Supervising Controller) for ASP.NET WebForms with 3.5 SP1. What is the preferred way to check the value of a view property that only has the a set operation with RhinoMocks? Here is what we have so far: var service = MockRepository.GenerateStub<IFooService>(); // stub some data for the method used in OnLoad in the presenter var view = MockRepository.GenerateMock<IFooView>(); var presenter = new FooPresenter(view, service); view.Raise(v => v.Load += null, this, EventArgs.Empty); Assert.IsTrue(view.Bars.Count == 10); // there is no get on Bars Should we use Expects or another way, any input would be great. Thanks Update based on Darin Dimitrov's reply. var bars = new List<Bar>() { new Bar() { BarId = 1 } }; var fooService = MockRepository.GenerateStub<IFooService>(); // this is called in OnLoad in the Presenter fooService.Stub(x => x.GetBars()).Return(bars); var view = MockRepository.GenerateMock<IFooView>(); var presenter = new FooPresenter(view, fooService); view.Raise(v => v.Load += null, this, EventArgs.Empty); view.AssertWasCalled(x => x.Bars = bars); // this does not pass This doesn't work. Should I be testing it this way or is there a better way?

    Read the article

  • How to test if raising an event results in a method being called conditional on value of parameters

    - by MattC
    I'm trying to write a unit test that will raise an event on a mock object which my test class is bound to. What I'm keen to test though is that when my test class gets it's eventhandler called it should only call a method on certain values of the eventhandlers parameters. My test seems to pass even if I comment the code that calls ProcessPriceUpdate(price); I'm in VS2005 so no lambdas please :( So... public delegate void PriceUpdateEventHandler(decimal price); public interface IPriceInterface{ event PriceUpdateEventHandler PriceUpdate; } public class TestClass { IPriceInterface priceInterface = null; TestClass(IPriceInterface priceInterface) { this.priceInterface = priceInterface; } public void Init() { priceInterface.PriceUpdate += OnPriceUpdate; } public void OnPriceUpdate(decimal price) { if(price > 0) ProcessPriceUpdate(price); } public void ProcessPriceUpdate(decimal price) { //do something with price } } And my test so far :s public void PriceUpdateEvent() { MockRepository mock = new MockRepository(); IPriceInterface pi = mock.DynamicMock<IPriceInterface>(); TestClass test = new TestClass(pi); decimal prc = 1M; IEventRaiser raiser; using (mock.Record()) { pi.PriceUpdate += null; raiser = LastCall.IgnoreArguments().GetEventRaiser(); Expect.Call(delegate { test.ProcessPriceUpdate(prc); }).Repeat.Once(); } using (mock.Playback()) { test.Init(); raiser.Raise(prc); } }

    Read the article

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