Search Results

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

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

  • Need help mocking a ASP.NET Controller in Rhino Mocks

    - 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 currently have: _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

  • Case insensitive expectations in Rhino Mocks

    - by user313886
    I'm using Rhino Mocks to expect a call. There is a single parameter which is a string. But I'm not bothered about the case of the string. I want the test to pass even if the case is wrong. So I'm doing the following: //expect log message to be called with a string parameter. //We want to ignore case when verifiyig so we use a constraint instead of a direct parameter Expect.Call(delegate { logger.LogMessage(null); }).Constraints(Is.Matching<string>(x => x.ToLower()=="f2")); It seems a bit log winded. Is there a more sensible way of doing this?

    Read the article

  • Unit Test For NpgsqlCommand With Rhino Mocks

    - by J Pollack
    My unit test keeps getting the following error: "System.InvalidOperationException: The Connection is not open." The Test [TestFixture] public class Test { [Test] public void Test1() { NpgsqlConnection connection = MockRepository.GenerateStub<NpgsqlConnection>(); // Tried to fake the open connection connection.Stub(x => x.State).Return(ConnectionState.Open); connection.Stub(x => x.FullState).Return(ConnectionState.Open); DbQueries queries = new DbQueries(connection); bool procedure = queries.ExecutePreProcedure("201003"); Assert.IsTrue(procedure); } } Code Under Test using System.Data; using Npgsql; public class DbQueries { private readonly NpgsqlConnection _connection; public DbQueries(NpgsqlConnection connection) { _connection = connection; } public bool ExecutePreProcedure(string date) { var command = new NpgsqlCommand("name_of_procedure", _connection); command.CommandType = CommandType.StoredProcedure; NpgsqlParameter parameter = new NpgsqlParameter {DbType = DbType.String, Value = date}; command.Parameters.Add(parameter); command.ExecuteScalar(); return true; } } How would you test the code using Rhino Mocks 3.6? PS. NpgsqlConnection is a connection to a PostgreSQL server.

    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

  • Seeding repository Rhino Mocks

    - by ahsteele
    I am embarking upon my first journey of test driven development in C#. To get started I'm using MSTest and Rhino.Mocks. I am attempting to write my first unit tests against my ICustomerRepository. It seems tedious to new up a Customer for each test method. In ruby-on-rails I'd create a seed file and load the customer for each test. It seems logical that I could put this boiler plate Customer into a property of the test class but then I would run the risk of it being modified. What are my options for simplifying this code? [TestMethod] public class CustomerTests : TestClassBase { [TestMethod] public void CanGetCustomerById() { // arrange var customer = new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" } } }; var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetById(5)).Return(customer); // assert Assert.AreEqual(customer, repository.GetById(5)); } [TestMethod] public void CanGetCustomerByDifId() { // arrange var customer = new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" } } }; var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetCustomerByDifID("55")).Return(customer); // assert Assert.AreEqual(customer, repository.GetCustomerByDifID("55")); } [TestMethod] public void CanGetCustomerByLogin() { // arrange var customer = new Customer() { CustId = 5, DifId = "55", CustLookupName = "The Dude", LoginList = new[] { new Login { LoginCustId = 5, LoginName = "tdude" } } }; var repository = Stub<ICustomerRepository>(); // act repository.Stub(rep => rep.GetCustomerByLogin("tdude")).Return(customer); // assert Assert.AreEqual(customer, repository.GetCustomerByLogin("tdude")); } } Test Base Class public class TestClassBase { protected T Stub<T>() where T : class { return MockRepository.GenerateStub<T>(); } } ICustomerRepository and IRepository public interface ICustomerRepository : IRepository<Customer> { IList<Customer> FindCustomers(string q); Customer GetCustomerByDifID(string difId); Customer GetCustomerByLogin(string loginName); } public interface IRepository<T> { void Save(T entity); void Save(List<T> entity); bool Save(T entity, out string message); void Delete(T entity); T GetById(int id); ICollection<T> FindAll(); }

    Read the article

  • Need help understanding Mocks and Stubs

    - by Theomax
    I'm new to use mocking frameworks and I have a few questions on the things that I am not clear on. I'm using Rhinomocks to generate mock objects in my unit tests. I understand that mocks can be created to verify interactions between methods and they record the interactions etc and stubs allow you to setup data and entities required by the test but you do not verify expectations on stubs. Looking at the recent unit tests I have created, I appear to be creating mocks literally for the purpose of stubbing and allowing for data to be setup. Is this a correct usage of mocks or is it incorrect if you're not actually calling verify on them? For example: user = MockRepository.GenerateMock<User>(); user.Stub(x => x.Id = Guid.NewGuid()); user.Stub(x => x.Name = "User1"); In the above code I generate a new user mock object, but I use a mock so I can stub the properties of the user because in some cases if the properties do not have a setter and I need to set them it seems the only way is to stub the property values. Is this a correct usage of stubbing and mocking? Also, I am not completely clear on what the difference between the following lines is: user.Stub(x => x.Id).Return(new Guid()); user.Stub(x => x.Id = Guid.NewGuid());

    Read the article

  • Moving from mock to real objects?

    - by jjchiw
    I'm like doing TDD so I started everything mocking objects, creating interface, stubbing, great. The design seems to work, now I'll implement the stuff, a lot of the code used in the stubs are going to be reused in my real implementation yay! Now should I duplicate the tests to use the real object implementation (but keeping the mocks object of the sensitive stuff like Database and "services" that are out of my context (http calls, etc...)) Or just change the mocks and stubs of the actual tests to use the real objects....... So the question is that, keep two tests or replace the stubs, mocks? And after that, I should keep designing with the mocks, stubs or just go with real objects? (Just making myself clear I'll keep the mock object of the sensitive stuff like database and services that are out of my context, in both situations.)

    Read the article

  • Rhino Mocks, Dependency Injection, and Separation of Concerns

    - by whatispunk
    I am new to mocking and dependency injection and need some guidance. My application is using a typical N-Tier architecture where the BLL references the DAL, and the UI references the BLL but not the DAL. Pretty straight forward. Lets say, for example, I have the following classes: class MyDataAccess : IMyDataAccess {} class MyBusinessLogic {} Each exists in a separate assembly. I want to mock MyDataAccess in the tests for MyBusinessLogic. So I added a constructor to the MyBusinessLogic class to take an IMyDataAccess parameter for the dependency injection. But now when I try to create an instance of MyBusinessLogic on the UI layer it requires a reference to the DAL. I thought I could define a default constructor on MyBusinessLogic to set a default IMyDataAccess implementation, but not only does this seem like a codesmell it didn't actually solve the problem. I'd still have a public constructor with IMyDataAccess in the signature. So the UI layer still requires a reference to the DAL in order to compile. One possible solution I am toying with is to create an internal constructor for MyBusinessLogic with the IMyDataAccess parameter. Then I can use an Accessor from the test project to call the constructor. But there's still that smell. What is the common solution here. I must just be doing something wrong. How could I improve the architecture?

    Read the article

  • Recursive mocking with Rhino-Mocks

    - by jaspernygaard
    Hi I'm trying to unittest several MVP implementations and can't quite figure out the best way to mock the view. I'll try to boil it down. The view IView consists e.g. of a property of type IControl. interface IView { IControl Control1 { get; } IControl Control2 { get; } } interface IControl { bool Enabled { get; set; } object Value { get; set; } } My question is whether there's a simple way to setup the property behavior for Enabled and Value on the IControl interface members on the IView interface - like recursive mocking a guess. I would rather not setup expectations for all my properties on the view (quite a few on each view). Thanks in advance

    Read the article

  • asp.net mvc rhino mocks mocking httprequest values

    - by Matthew
    Hi Is there a way to mock request params, what is the best approach when testing to create fake request values in order to run a test would some thing like this work? _context = MockRepository.GenerateStub<HttpContext>(); request = MockRepository.GenerateStub<HttpRequest>(); var collection = new NameValueCollection(); collection.Add("", ""); SetupResult.For(request.Params).Return(collection); SetupResult.For(_context.Request).Return(request);

    Read the article

  • Constructing mocks in unit tests

    - by Flynn1179
    Is there any way to have a mock constructed instead of a real instance when testing code that calls a constructor? For example: public class ClassToTest { public void MethodToTest() { MyObject foo = new MyObject(); Console.WriteLine(foo.ToString()); } } In this example, I need to create a unit test that confirms that calling MethodToTest on an instance of ClassToTest will indeed output whatever the result of the ToString() method of a newly created instance of MyObject. I can't see a way of realistically testing the 'ClassToTest' class in isolation; testing this method would actually test the 'myObject.ToString()' method as well as the MethodToTest method.

    Read the article

  • Difference in techniques for setting a stubbed method's return value with Rhino Mocks

    - by CRice
    What is the main difference between these following two ways to give a method some fake implementation? I was using the second way fine in one test but in another test the behaviour can not be achieved unless I go with the first way. These are set up via: IMembershipService service = test.Stub<IMembershipService>(); so (the first), using (test.Record()) //test is MockRepository instance { service.GetUser("dummyName"); LastCall.Return(new LoginUser()); } vs (the second). service.Stub(r => r.GetUser("dummyName")).Return(new LoginUser()); Edit The problem is that the second technique returns null in the test, when I expect it to return a new LoginUser. The first technique behaves as expected by returning a new LoginUser. All other test code used in both cases is identical.

    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

  • RhinoMocks Testing callback method

    - by joblot
    Hi All I have a service proxy class that makes asyn call to service operation. I use a callback method to pass results back to my view model. Doing functional testing of view model, I can mock service proxy to ensure methods are called on the proxy, but how can I ensure that callback method is called as well? With RhinoMocks I can test that events are handled and event raise events on the mocked object, but how can I test callbacks? ViewModel: public class MyViewModel { public void GetDataAsync() { // Use DI framework to get the object IMyServiceClient myServiceClient = IoC.Resolve<IMyServiceClient>(); myServiceClient.GetData(GetDataAsyncCallback); } private void GetDataAsyncCallback(Entity entity, ServiceError error) { // do something here... } } ServiceProxy: public class MyService : ClientBase, IMyServiceClient { // Constructor public NertiAdminServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } // IMyServiceClient member. public void GetData(Action<Entity, ServiceError> callback) { Channel.BeginGetData(EndGetData, callback); } private void EndGetData(IAsyncResult result) { Action<Entity, ServiceError> callback = result.AsyncState as Action<Entity, ServiceError>; ServiceError error; Entity results = Channel.EndGetData(out error, result); if (callback != null) callback(results, error); } } Thanks

    Read the article

  • Verify an event was raised by mocked object

    - by joblot
    In my unit test how can I verify that an event is raised by the mocked object. I have a View(UI) -- ViewModel -- DataProvider -- ServiceProxy. ServiceProxy makes async call to serivce operation. When async operation is complete a method on DataProvider is called (callback method is passed as a method parameter). The callback method then raise and event which ViewModel is listening to. For ViewModel test I mock DataProvider and verify that handler exists for event raised by DataProvider. When testing DataProvider I mock ServiceProxy, but how can I test that callback method is called and event is raised. I am using RhinoMock 3.5 and AAA syntax Thanks -- DataProvider -- public partial class DataProvider { public event EventHandler<EntityEventArgs<ProductDefinition>> GetProductDefinitionCompleted; public void GetProductDefinition() { var service = IoC.Resolve<IServiceProxy>(); service.GetProductDefinitionAsync(GetProductDefinitionAsyncCallback); } private void GetProductDefinitionAsyncCallback(ProductDefinition productDefinition, ServiceError error) { OnGetProductDefinitionCompleted(this, new EntityEventArgs<ProductDefinition>(productDefinition, error)); } protected void OnGetProductDefinitionCompleted(object sender, EntityEventArgs<ProductDefinition> e) { if (GetProductDefinitionCompleted != null) GetProductDefinitionCompleted(sender, e); } } -- ServiceProxy -- public class ServiceProxy : ClientBase<IService>, IServiceProxy { public void GetProductDefinitionAsync(Action<ProductDefinition, ServiceError> callback) { Channel.BeginGetProductDefinition(EndGetProductDefinition, callback); } private void EndGetProductDefinition(IAsyncResult result) { Action<ProductDefinition, ServiceError> callback = result.AsyncState as Action<ProductDefinition, ServiceError>; ServiceError error; ProductDefinition results = Channel.EndGetProductDefinition(out error, result); if (callback != null) callback(results, error); } }

    Read the article

  • How do I combine two interfaces when creating mocks?

    - by sduplooy
    We are using Rhino Mocks to perform some unit testing and need to mock two interfaces. Only one interface is implemented on the object and the other is implemented dynamically using an aspect-oriented approach. Is there an easy way to combine the two interfaces dynamically so that a mock can be created and the methods stubbed for both interfaces?

    Read the article

  • Rhino Mocks, AssertWasCalled with Arg Constraint on array parameter

    - by Etienne Giust
    Today, I had a hard time unit testing a function to make sure a Method with some array parameters was called. Method to be called : void AddUsersToRoles(string[] usernames, string[] roleNames);   I had previously used Arg<T>.Matches on complex types in other unit tests, but for some reason I was unable to find out how to apply the same logic with an array of strings.   It is actually quite simple to do, T really is a string[], so we use Arg<string[]>. As for the Matching part, a ToList() allows us to leverage the lambda expression.   sut.PermissionServices.AssertWasCalled(                 l => l.AddUsersToRoles(                     Arg<string[]>.Matches(a => a.ToList().First() == UserId.ToString())                     ,Arg<string[]>.Matches(a => a.ToList().First() == expectedRole1 && a.ToList()[1] == expectedRole2)                     )                     );   Of course, iw we expect an array with 2 or more values, the math would be something like : a => a.ToList()[0] == value1 && a.ToList()[1] == value2    … etc.

    Read the article

  • Agile Entity Framework 4 Repository: Part 6: Mocks & Unit Tests

    I did finish this series, honest I did. But not in the blog. Ive shown this in a number of conferences and even in my book, but I never came back and wrote it all down. In fact, I had the whole solutino written before I began the series, but it has gone through a lot of changes. Where did I leave off? Agile Entity Framework 4 Repository: Part 1- Model and POCO Classes Agile Entity Framework 4 Repository: Part 2- The Repository Agile EF4 Repository: Part 3 -Fine Tuning the Repository Agile...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

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

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

    Read the article

  • How to mock WCF Web Services with Rhino Mocks.

    - by Will
    How do I test a class that utilizes proxy clients generated by a Web Service Reference? I would like to mock the client, but the generated client interface doesn't contain the close method, which is required to properly terminate the proxy. If I don't use the interface, but instead a concrete reference, I get access to the close method but loose the ability to mock the proxy. I'm trying to test a class similar to this: public class ServiceAdapter : IServiceAdapter, IDisposable { // ILoggingServiceClient is generated via a Web Service reference private readonly ILoggingServiceClient _loggingServiceClient; public ServiceAdapter() : this(new LoggingServiceClient()) {} internal ServiceAdapter(ILoggingServiceClient loggingServiceClient) { _loggingServiceClient = loggingServiceClient; } public void LogSomething(string msg) { _loggingServiceClient.LogSomething(msg); } public void Dispose() { // this doesn't compile, because ILoggingServiceClient doesn't contain Close(), // yet Close is required to properly terminate the WCF client _loggingServiceClient.Close(); } }

    Read the article

  • Using RhinoMocks, how do you mock or stub a concrete class without an empty constructor?

    - by Mark Rogers
    Mocking a concrete class with Rhino Mocks seems to work pretty easy when you have an empty constructor on a class: public class MyClass{ public MyClass() {} } But if I add a constructor that takes parameters and remove the one that doesn't take parameters: public class MyClass{ public MyClass(MyOtherClass instance) {} } I tend to get an exception: System.MissingMethodException : Can't find a constructor with matching arguments I've tried putting in nulls in my call to Mock or Stub, but it doesn't work. Can I create mocks or stubs of concrete classes with Rhino Mocks, or must I always supply (implicitly or explicitly) a parameter-less constructor?

    Read the article

  • how to avoid returning mocks from a mocked object list

    - by koen
    I'm trying out mock/responsibility driven design. I seem to have problems to avoid returning mocks from mocks in the case of finder objects. An example could be an object that checks whether the bills from last month are paid. It needs a service that retrieves a list of bills for that. So I need to mock that service that retrieves the bills. At the same time I need that mock to return mocked Bills (since I don't want my test to rely on the correctness bill implementation). Is my design flawed? Is there a better way to test this? Or is this the way it will need to be when using finder objects (the finding of the bills in this case)?

    Read the article

  • Is static universally "evil" for unit testing and if so why does resharper recommend it?

    - by Vaccano
    I have found that there are only 3 ways to unit test (mock/stub) dependencies that are static in C#.NET: Moles TypeMock JustMock Given that two of these are not free and one has not hit release 1.0, mocking static stuff is not too easy. Does that make static methods and such "evil" (in the unit testing sense)? And if so, why does resharper want me to make anything that can be static, static? (Assuming resharper is not also "evil".) Clarification: I am talking about the scenario when you want to unit test a method and that method calls a static method in a different unit/class. By most definitions of unit testing, if you just let the method under test call the static method in the other unit/class then you are not unit testing, you are integration testing. (Useful, but not a unit test.)

    Read the article

  • Intelligent serial port mocks with Moq

    - by Padu Merloti
    I have to write a lot of code that deals with serial ports. Usually there will be a device connected at the other end of the wire and I usually create my own mocks to simulate their behavior. I'm starting to look at Moq to help with my unit tests. It's pretty simple to use it when you need just a stub, but I want to know if it is possible and if yes how do I create a mock for a hardware device that responds differently according to what I want to test. A simple example: One of the devices I interface with receives a command (move to position x), gives back an ACK message and goes to a "moving" state until it reaches the ordered position. I want to create a test where I send the move command and then keep querying state until it reaches the final position. I want to create two versions of the mock for two different tests, one where I expect the device to reach the final position successfully and the other where it will fail. Too much to ask?

    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

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