Search Results

Search found 155 results on 7 pages for 'moq'.

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

  • moq SetupSet is obsolete. In place of what?

    - by jkohlhepp
    Let's say I want to use moq to create a callback on a setter to store the set property in my own field for later use. (Contrived example - but it gets to the point of the question.) I could do something like this: myMock.SetupSet(x => x.MyProperty).Callback(value => myLocalVariable = value); And that works just fine. However, SetupSet is obsolete according to Intellisense. But it doesn't say what should be used as an alternative. I know that moq provides SetupProperty which will autowire the property with a backing field. But that is not what I'm looking for. I want to capture the set value into my own variable. How should I do this using non-obsolete methods?

    Read the article

  • [News] Utiliser le framework de bouchon Moq

    Moq est un framework permettant de mettre en oeuvre les mock-objets destin?es aux phases de tests. Cet excellent article illustre le principe : " (...) it is intended to be straightforward and easy to use mocking framework that doesn?t require any prior knowledge of the mocking concepts. So, it doesn't requires deep learning curve from the developers. It takes full advantage of the .NET 3.5 expression trees and the lambda expressions. Any of the methods and properties of the mock object can be easily represented in the lambda expressions."

    Read the article

  • How to Mock HttpWebRequest and HttpWebResponse using the Moq Framework?

    - by Nicholas
    How do you use the Moq Framework to Mock HttpWebRequest and HttpWebResponse in the following Unit Test? [Test] public void Verify_That_SiteMap_Urls_Are_Reachable() { // Arrange - simplified Uri uri = new Uri("http://www.google.com"); // Act HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Asset Assert.AreEqual("OK", response.StatusCode.ToString()); }

    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

  • When mocking a class with Moq, how can I CallBase for just specific methods?

    - by Daryn
    I really appreciate Moq's Loose mocking behaviour that returns default values when no expectations are set. It's convenient and saves me code, and it also acts as a safety measure: dependencies won't get unintentionally called during the unit test (as long as they are virtual). However, I'm confused about how to keep these benefits when the method under test happens to be virtual. In this case I do want to call the real code for that one method, while still having the rest of the class loosely mocked. All I have found in my searching is that I could set mock.CallBase = true to ensure that the method gets called. However, that affects the whole class. I don't want to do that because it puts me in a dilemma about all the other properties and methods in the class that hide call dependencies: if CallBase is true then I have to either Setup stubs for all of the properties and methods that hide dependencies -- Even though my test doesn't think it needs to care about those dependencies, or Hope that I don't forget to Setup any stubs (and that no new dependencies get added to the code in the future) -- Risk unit tests hitting a real dependency. Q: With Moq, is there any way to test a virtual method, when I mocked the class to stub just a few dependencies? I.e. Without resorting to CallBase=true and having to stub all of the dependencies? Example code to illustrate (uses MSTest, InternalsVisibleTo DynamicProxyGenAssembly2) In the following example, TestNonVirtualMethod passes, but TestVirtualMethod fails - returns null. public class Foo { public string NonVirtualMethod() { return GetDependencyA(); } public virtual string VirtualMethod() { return GetDependencyA();} internal virtual string GetDependencyA() { return "! Hit REAL Dependency A !"; } // [... Possibly many other dependencies ...] internal virtual string GetDependencyN() { return "! Hit REAL Dependency N !"; } } [TestClass] public class UnitTest1 { [TestMethod] public void TestNonVirtualMethod() { var mockFoo = new Mock<Foo>(); mockFoo.Setup(m => m.GetDependencyA()).Returns(expectedResultString); string result = mockFoo.Object.NonVirtualMethod(); Assert.AreEqual(expectedResultString, result); } [TestMethod] public void TestVirtualMethod() // Fails { var mockFoo = new Mock<Foo>(); mockFoo.Setup(m => m.GetDependencyA()).Returns(expectedResultString); // (I don't want to setup GetDependencyB ... GetDependencyN here) string result = mockFoo.Object.VirtualMethod(); Assert.AreEqual(expectedResultString, result); } string expectedResultString = "Hit mock dependency A - OK"; }

    Read the article

  • How can I Setup overloaded method invocations in Moq?

    - by arootbeer
    I'm trying to mock a mapping interface IMapper: public interface IMapper<TFoo, TBar> { TBar Map(TFoo foo); TFoo Map(TBar bar); } In my test, I'm setting the mock mapper up to expect an invocation of each (around an NHibernate update operation): //... _mapperMock.Setup(m => m.Map(fooMock.Object)).Returns(barMock.Object); _mapperMock.Setup(m => m.Map(barMock.Object)).Returns(fooMock.Object); //... However, when the second Map invocation is made, the mapper mock throws because it is only expecting a single invocation. Watching the mapper mock during setup at runtime, I can look see the Map(TFoo foo) overload get registered, and then see it get replaced when the Map(TBar bar) overload is set up. Is this a problem with the way Moq handles setup, or is there a different syntax I need to use in this case?

    Read the article

  • How to mock the Request.ServerVariables using MOQ for ASP.NET MVC?

    - by melaos
    hi guys, i'm just learning to put in unit testing for my asp.net mvc when i came to learn about the mock and the different frameworks there is out there now. after checking SO, i found that MOQ seems to be the easiest to pick up. as of now i'm stuck trying to mock the Request.ServerVariables, as after reading this post, i've learned that it's better to abstract them into property. as such: /// <summary> /// Return the server port /// </summary> protected string ServerPort { get { return Request.ServerVariables.Get("SERVER_PORT"); } } But i'm having a hard time learning how to properly mock this. I have a home controller ActionResult function which grabs the user server information and proceed to create a form to grab the user's information. i tried to use hanselman's mvcmockhelpers class but i'm not sure how to use it. this is what i have so far... [Test] public void Create_Redirects_To_ProductAdded_On_Success() { FakeViewEngine engine = new FakeViewEngine(); HomeController controller = new HomeController(); controller.ViewEngine = engine; MvcMockHelpers.SetFakeControllerContext(controller); controller.Create(); var results = controller.Create(); var typedResults = results as RedirectToRouteResult; Assert.AreEqual("", typedResults.RouteValues["action"], "Wrong action"); Assert.AreEqual("", typedResults.RouteValues["controller"], "Wrong controller"); } Questions: As of now i'm still getting null exception error when i'm running the test. So what am i missing here? And if i use the mvcmockhelpers class, how can i still call the request.verifyall function to ensure all the mocking are properly setup?

    Read the article

  • How to throw a SqlException(need for mocking)

    - by chobo2
    Hi I am trying to test some exceptions in my project and one of the Exceptions I catch is SQlException. Now It seems that you can't go new SqlException() so I am not sure how I can throw a exception especially without somehow calling the database(and since it is unit tests it is usually advised not to call the database since it is slow). So I am using nunit and moq so I am not sure how to fake this. Edit Based on the answers they seem to all be based on ado.net I am using linq to sql. So that stuff is like behind the scenes. Edit @ Matt Hamilton System.ArgumentException : Type to mock must be an interface or an abstract or non-sealed class. at Moq.Mock`1.CheckParameters() at Moq.Mock`1..ctor(MockBehavior behavior, Object[] args) at Moq.Mock`1..ctor(MockBehavior behavior) at Moq.Mock`1..ctor() Posts to the first line when it tries to mockup var ex = new Mock<System.Data.SqlClient.SqlException>(); ex.SetupGet(e => e.Message).Returns("Exception message");

    Read the article

  • How do you unit test a LINQ query using Moq and Machine.Specifications?

    - by Phil.Wheeler
    I'm struggling to get my head around how to accommodate a mocked repository's method that only accepts a Linq expression as its argument. Specifically, the repository has a First() method that looks like this: public T First(Expression<Func<T, bool>> expression) { return All().Where(expression).FirstOrDefault(); } The difficulty I'm encountering is with my MSpec tests, where I'm (probably incorrectly) trying to mock that call: public abstract class with_userprofile_repository { protected static Mock<IRepository<UserProfile>> repository; Establish context = () => { repository = new Mock<IRepository<UserProfile>>(); repository.Setup<UserProfile>(x => x.First(up => up.OpenID == @"http://testuser.myopenid.com")).Returns(GetDummyUser()); }; protected static UserProfile GetDummyUser() { UserProfile p = new UserProfile(); p.OpenID = @"http://testuser.myopenid.com"; p.FirstName = "Joe"; p.LastLogin = DateTime.Now.Date.AddDays(-7); p.LastName = "Bloggs"; p.Email = "[email protected]"; return p; } } I run into trouble because it's not enjoying the Linq expression: System.NotSupportedException: Expression up = (up.OpenID = "http://testuser.myopenid.com") is not supported. So how does one test these sorts of scenarios?

    Read the article

  • How do you unit test a LINQ expression using Moq and Machine.Specifications?

    - by Phil.Wheeler
    I'm struggling to get my head around how to accommodate a mocked repository's method that only accepts a Linq expression as its argument. Specifically, the repository has a First() method that looks like this: public T First(Expression<Func<T, bool>> expression) { return All().Where(expression).FirstOrDefault(); } The difficulty I'm encountering is with my MSpec tests, where I'm (probably incorrectly) trying to mock that call: public abstract class with_userprofile_repository { protected static Mock<IRepository<UserProfile>> repository; Establish context = () => { repository = new Mock<IRepository<UserProfile>>(); repository.Setup<UserProfile>(x => x.First(up => up.OpenID == @"http://testuser.myopenid.com")).Returns(GetDummyUser()); }; protected static UserProfile GetDummyUser() { UserProfile p = new UserProfile(); p.OpenID = @"http://testuser.myopenid.com"; p.FirstName = "Joe"; p.LastLogin = DateTime.Now.Date.AddDays(-7); p.LastName = "Bloggs"; p.Email = "[email protected]"; return p; } } I run into trouble because it's not enjoying the Linq expression: System.NotSupportedException: Expression up = (up.OpenID = "http://testuser.myopenid.com") is not supported. So how does one test these sorts of scenarios?

    Read the article

  • Why in the world is this Moq + NUnit test failing?

    - by Dave Falkner
    I have this dataAccess mock object and I'm trying to verify that one of its methods is being invoked, and that the argument passed into this method fulfills certain constraints. As best I can tell, this method is indeed being invoked, and with the constraints fulfilled. This line of the test throws a MockException: data.Verify(d => d.InsertInvoice(It.Is<Invoice>(i => i.TermPaymentAmount == 0m)), Times.Once()); However, removing the constraint and accepting any invoice passes the test: data.Verify(d => d.InsertInvoice(It.IsAny<Invoice>()), Times.Once()); I've created a test windows form that instantiates this test class, runs its .Setup() method, and then calls the method which I am wishing to test. I insert a breakpoint on the line of code where the mock object is failing the test data.InsertInvoice(invoice); to actually hover over the invoice, and I can confirm that its .TermPaymentAmount decimal property is indeed zero at the time the method is invoked. Out of desperation, I even added a call back to my dataAccess mock: data.Setup(d => d.InsertInvoice(It.IsAny<Invoice>())).Callback((Invoice inv) => System.Windows.Forms.MessageBox.Show(inv.TermPaymentAmount.ToString("G17"))); And this gives me a message box showing "0". This is really baffling me, and no one else in my shop has been able to figure this out. Any help would be appreciated. A barely related question, which I should probably ask independently, is whether it is preferable to use Mock.Verify(...) as I have here, or to use Mock.Expect(...).Verifiable followed by Mock.VerifyAll() as I have seen other people doing? If the answer is situational, which situations would warrent the use of one over the other?

    Read the article

  • Using Moq at Blend design time

    - by adrian hara
    This might be a bit out there, but suppose I want to use Moq in a ViewModel to create some design time data, like so: public class SomeViewModel { public SomeViewModel(ISomeDependency dependency) { if (IsInDesignMode) { var mock = new Mock<ISomeDependency>(); dependency = mock.Object; // this throws! } } } The mock could be set up to do some stuff, but you get the idea. My problem is that at design-time in Blend, this code throws an InvalidCastException, with the message along the lines of "Unable to cast object of type 'Castle.Proxies.ISomeDependencyProxy2b3a8f3188284ff0b1129bdf3d50d3fc' to type 'ISomeDependency'." While this doesn't necessarily look to be Moq related but Castle related, I hope the Moq example helps ;) Any idea why that is? Thanks!

    Read the article

  • The art of Unit Testing with Examples in .NET

    - by outcoldman
    First time when I familiarized with unit testing was 5 or 6 years ago. It was start of my developing career. I remember that somebody told me about code coverage. At that time I didn’t write any Unit tests. Guy, who was my team lead, told me “Do you see operator if with three conditions? You should check all of these conditions”. So, after that I had written some code, I should go to interface and try to invoke all code which I wrote from user interface. Nice? At current time I know little more about tests and unit testing. I have not participated in projects, designed by Test Driven Development (TDD). Basics of my knowledge are a spying code of my colleagues, some articles and screencasts. I had decide that I should know much more, and became a real professional of unit testing, this is why I had start to read book The art of Unit Testing with Examples in .NET. More than, in my current job place looks like I’m just one who writing unit tests for my code. I should show good examples of my tests. ,a href="http://outcoldman.ru/en/blog/show/267"Read more...

    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

  • generated service mock: everything but RhinoMocks fails?

    - by hko
    I have the "quest" to search for the next Mocking Framework for my company, and basically it's down to NSubstitute (simplest syntax, but no strict mocks), FakeItEasy(best reviews, Roy Osherove bonus, and slightly better lib support than NSubstitute), Moq (best "other libs support", biggest featureset, downside: mock.Object). We definitely want to move on from RhinoMocks, e.g. because of the unusefull interactiontest error messages (it should tell me what the parameter was instead, when a verification fails). So I was pretty surprised the other day (that was yesterday) when I found out RhinoMocks could do a thing where every other mock framework fails at: Mocking an autogenerated SomethingService (a typical VS autogenerated service with a default construtor in a partial class). Please don't argue about the design.. I intend to write lightweight integration tests (and some unit tests), and I can't mess around with the service, the product is installed on too many customers system. See this code: // here the NSubstitute and FakeItEasy equivalents throw an exception.. see below TicketStoreService fakeTicketStoreService = MockRepository.GenerateMock<TicketStoreService>(); fakeTicketStoreService.Expect(service => service.DoSomething(Arg.Is(new Guid())).Return(new Guid()); fakeTicketStoreService.DoSomething(Arg.Is(new Guid())); fakeTicketStoreService.VerifyAllExpectations(); Note that DoSomething is a non-virtual methodcall in an autogenerated class. So it shouldn't work, according to common knowledge. But it does. Problem is that it's the only (non commercial) framework that can do this: Rhino.Mocks works, and verification works too FakeItEasy says it doesn't find a default constructor (probably just wrong exception message): No default constructor was found on the type SomeNamespace.TicketStoreService Moq gives something sane and understandable: Invalid setup on a non-virtual (overridable in VB) member: service=> service.DoSomething Nsubstitute gives a message System.NotSupportedException: Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface. I'm really wondering what's going on here with the frameworks, except Moq. The "fancy new" frameworks seem to have an initial perf hit too, probably preparing some Type cache and serializing stuff, whilst RhinoMocks somehow manages to create a very "slim" mock without recursion. I have to admit I didn't like RhinoMocks very well, but here it shines.. unfortunately. So, is there a way to get that to work with newer (non-commercial!) mocking frameworks, or somehow get a sane error message out of Rhino.Mocks? And why can Rhino.Mocks achieve this, when clearly every Mocking framework states it can only work with virtual methods when given a concrete class? Let's not derail the discussion by talking about alternative approaches like Extract&Override or runtime-proxy Mocking frameworks like JustMock/TypeMock/Moles or the new Fakes framework, I know these, but that would be less ideal solutions, for reasons beyond this topic. Any help appreciated..

    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

  • Weird .net 4.0 exception when running unit tests

    - by vdh_ant
    Hi guys I am receiving the following exception when trying to run my unit tests using .net 4.0 under VS2010 with moq 3.1. Attempt by security transparent method 'SPPD.Backend.DataAccess.Test.Specs_for_Core.When_using_base.Can_create_mapper()' to access security critical method 'Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(System.Object)' failed. Assembly 'SPPD.Backend.DataAccess.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception. The test I am running is really straight forward and looks something like the following: [TestMethod] public void Can_create_mapper() { this.SetupTest(); var mockMapper = new Moq.Mock<IMapper>().Object; this._Resolver.Setup(x => x.Resolve<IMapper>()).Returns(mockMapper).Verifiable(); var testBaseDa = new TestBaseDa(); var result = testBaseDa.TestCreateMapper<IMapper>(); Assert.IsNotNull(result); //<<< THROWS EXCEPTION HERE Assert.AreSame(mockMapper, result); this._Resolver.Verify(); } I have no idea what this means and I have been looking around and have found very little on the topic. The closest reference I have found is this http://dotnetzip.codeplex.com/Thread/View.aspx?ThreadId=80274 but its not very clear on what they did to fix it... Anyone got any ideas?

    Read the article

  • Any teams out there using TypeMock? Is it worth the hefty price tag?

    - by dferraro
    Hi, I hope this question is not 'controversial' - I'm just basically asking - has anyone here purchased TypeMock and been happy (or unhappy) with the results? We are a small dev shop of only 12 developers including the 2 dev managers. We've been using NMock so far but there are limitations. I have done research and started playing with TypeMock and I love it. It's super clean syntax and lets you basically mock everything, which is great for legacy code. The problem is - how do I justify to my boss spending 800-1200$ per license for an API which has 4-5 competitors that are completly free? 800-1200$ is how much Infragistrics or Telerik cost per license - and there sure as hell isn't 4-5 open source comparable UI frameworks... Which is why I find it a bit overpriced, albeit an awesome library... Any opinions / experiences are greatly appreciated. EDIT: after finding MOQ I thought I fell in love - until I found out that it's not fully supported in VB.NET because VB lacks lambda sub routines =(. Is anyone using MOQ for VB.NET? The problem is we are a mixed shop - we use C# for our CRM development and VB for everything else. Any guidence is greatly appreciated again

    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

  • Do we really need isolation frameworks to create stubs?

    - by Sandbox
    I have read this: http://martinfowler.com/articles/mocksArentStubs.html My concepts about a stub and a mock are clear. I understand the need of isolation frameworks like moq, rhinomocks and like to create a mock object. As mocks, participate in actual verfication of expectations. But why do we need these frameworks to create stubs. I would rather prefer rolling out a hand created stub and use it in various fixtures.

    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

  • Mocking a Wcf ServiceContract

    - by Michael
    I want to mock a ServiceContract. The problem is that Moq (and Castle Dynamic-Proxy) copies the attributes from the interface to the dynamic proxy which Wcf don't like. Wcf sais: The ServiceContractAttribute should only be define on either the interface or the implementation, not both.

    Read the article

  • When can we mock an object and its methods?

    - by Shailendra
    I am novice to the Moq and unit testing. I have to write unit tests to a lot of classes which has the objects of other classes. can i mock the methods of the class objects. Here is the exact scenerio- I have a class two classes A and B and A has a private object of B and in a method of A i am internally calling the method of B and then doing some calculation and returning the result. Can i mock the method of B in this scenerio? Please try to give me full detail about the conditions where i can mock the methods and functions of the class. Thanx

    Read the article

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