Search Results

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

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

  • How to mock ISerializable classes with Moq?

    - by asmois
    Hi there, I'm completly new to Moq and now trying to create a mock for System.Assembly class. I'm using this code: var mockAssembly = new Mock<Assembly>(); mockAssembly.Setup( x => x.GetTypes() ).Returns( new Type[] { typeof( Type1 ), typeof( Type2 ) } ); But when I run tests I get next exception: System.ArgumentException : The type System.Reflection.Assembly implements ISerializable, but failed to provide a deserialization constructor Stack Trace: at Castle.DynamicProxy.Generators.BaseProxyGenerator.VerifyIfBaseImplementsGet­ObjectData(Type baseType) at Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options) at Castle.DynamicProxy.DefaultProxyBuilder.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options) at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors) at Moq.Proxy.CastleProxyFactory.CreateProxy[T](ICallInterceptor interceptor, Type[] interfaces, Object[] arguments) at Moq.Mock`1.<InitializeInstance>b__0() at Moq.PexProtector.Invoke(Action action) at Moq.Mock`1.InitializeInstance() at Moq.Mock`1.OnGetObject() at Moq.Mock`1.get_Object() Could you reccomend me the right way to mock ISerializable classes (like System.Assembly) with Moq. Thanks in advance!

    Read the article

  • How to mock an SqlDataReader using Moq - Update

    - by Simon G
    Hi, I'm new to moq and setting up mocks so i could do with a little help. Title says it all really - how do I mock up an SqlDataReader using Moq? Thanks Update After further testing this is what I have so far: private IDataReader MockIDataReader() { var moq = new Mock<IDataReader>(); moq.Setup( x => x.Read() ).Returns( true ); moq.Setup( x => x.Read() ).Returns( false ); moq.SetupGet<object>( x => x["Char"] ).Returns( 'C' ); return moq.Object; } private class TestData { public char ValidChar { get; set; } } private TestData GetTestData() { var testData = new TestData(); using ( var reader = MockIDataReader() ) { while ( reader.Read() ) { testData = new TestData { ValidChar = reader.GetChar( "Char" ).Value }; } } return testData; } The issue you is when I do reader.Read in my GetTestData() method its always empty. I need to know how to do something like reader.Stub( x => x.Read() ).Repeat.Once().Return( true ) as per the rhino mock example: http://stackoverflow.com/questions/1792984/mocking-a-datareader-and-getting-a-rhino-mocks-exceptions-expectationviolationexc

    Read the article

  • How should moq's VerifySet be called in VB.net

    - by Bender
    I am trying to test that a property has been set but when I write this as a unit test: moqFeed.VerifySet(Function(m) m.RowAdded = "Row Added") moq complains that "Expression is not a property setter invocation" My complete code is Imports Gallio.Framework Imports MbUnit.Framework Imports Moq <TestFixture()> Public Class GUI_FeedPresenter_Test Private moqFeed As Moq.Mock(Of IFeedView) <SetUp()> Sub Setup() moqFeed = New Mock(Of IFeedView) End Sub <Test()> Public Sub New_Presenter() Dim pres = New FeedPresenter(moqFeed.Object) moqFeed.VerifySet(Function(m) m.RowAdded = "Row Added") End Sub End Class Public Interface IFeedView Property RowAdded() As String End Interface Public Class FeedPresenter Private _FeedView As IFeedView Public Sub New(ByVal feedView As IFeedView) _FeedView = feedView _FeedView.RowAdded = "Row Added" End Sub End Class I can't find any examples of moq in VB, I would be grateful for any examples.

    Read the article

  • Using Moq to set indexers in C#

    - by emddudley
    I'm having trouble figuring out how to set indexers in C# with Moq. The Moq documentation is weak, and I've done a lot of searching... what I'd like to do is similar in the solution to How to Moq Setting an Indexed property: var someClass = new Mock<ISomeClass>(); someClass.SetupSet(o => o.SomeIndexedProperty[3] = 25); I want to modify the above to work for any index and any value so I can just do something like this: someClass.Object.SomeIndexedProperty[1] = 5; Currently I have the following, which works great for the indexed property getter, but if I ever set the value Moq ignores it: var someValues = new int[] { 10, 20, 30, 40 }; var someClass = new Mock<ISomeClass>(); someClass.Setup(o => o.SomeIndexedProperty[It.IsAny<int>()]) .Returns<int>(index => someValues[index]); // Moq doesn't set the value below, so the Assert fails! someClass.Object.SomeIndexedProperty[3] = 25; Assert.AreEqual(25, someClass.Object.SomeIndexedProperty[3]);

    Read the article

  • Moq how do you test internal methods?

    - by jo
    Hi, Told by my boss to use Moq and that is it. I like it but it seems that unlike MSTest or mbunit etc... you cannot test internal methods So I am forced to make public some internal implementation in my interface so that i can test it. Am I missing something? Can you test internal methods using Moq? Thanks a lot

    Read the article

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

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

    Read the article

  • [NUnit+Moq] Guidelines for using Assert versus Verify

    - by emddudley
    I'm new to unit testing, and I'm learning how to use NUnit and Moq. NUnit provides Assert syntax for testing conditions in my unit tests, while Moq provides some Verify functions. To some extent these seem to provide the same functionality. How do I know when it's more appropriate to use Assert or Verify? Maybe Assert is better for confirming state, and Verify is better for confirming behavior (Classical versus Mockist)?

    Read the article

  • Moq: Unable to cast to interface

    - by Pickels
    Hello, earlier today I asked this question. So since moq creates it's own class from an interface I wasn't able to cast it to a different class. So it got me wondering what if I created a ICustomPrincipal and tried to cast to that. This is how my mocks look: var MockHttpContext = new Mock<HttpContextBase>(); var MockPrincipal = new Mock<ICustomPrincipal>(); MockHttpContext.SetupGet(h => h.User).Returns(MockPrincipal.Object); In the method I am trying to test the follow code gives the error(again): var user = (ICustomPrincipal)httpContext.User; The error is the following: Unable to cast object of type 'IPrincipalProxy4081807111564298854aabfc890edcc8' to type 'MyProject.Web.ICustomPrincipal'. I guess I still need some practice with interfaces and moq but shouldn't I be able to cast the class that moq created back to ICustomPrincipal? I know httpContext.User returns an IPrincipal so maybe something gets lost there? Well if anybody can help me I would appreciate that. Pickels Edit: As requested the full code of the method I am testing. It's still not finished but this is what I have so far: public bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } var user = (ICustomPrincipal)httpContext.User; if (!user.Identity.IsAuthenticated) { return false; } return true; }

    Read the article

  • Moq.Mock<T> - how to setup a method that takes an expression

    - by Paul
    I am Mocking my repository interface and am not sure how to setup a method that takes an expression and returns an object? I am using Moq and NUnit Interface: public interface IReadOnlyRepository : IDisposable { IQueryable<T> All<T>() where T : class; T Single<T>(Expression<Func<T, bool>> expression) where T : class; } Test with IQueryable already setup, but don't know how to setup the T Single: private Moq.Mock<IReadOnlyRepository> _mockRepos; private AdminController _controller; [SetUp] public void SetUp() { var allPages = new List<Page>(); for (var i = 0; i < 10; i++) { allPages.Add(new Page { Id = i, Title = "Page Title " + i, Slug = "Page-Title-" + i, Content = "Page " + i + " on page content." }); } _mockRepos = new Moq.Mock<IReadOnlyRepository>(); _mockRepos.Setup(x => x.All<Page>()).Returns(allPages.AsQueryable()); //Not sure what to do here??? _mockRepos.Setup(x => x.Single<Page>() //---- _controller = new AdminController(_mockRepos.Object); }

    Read the article

  • Simple Moq ? - Problem with .Verify

    - by user127954
    Hi, just a simple question here. I've used Moq for awhile but, as of yet, have only used it for stubbing and not for mocking. I am trying to introduce our developers to unit testing. I set up a simple example to explain the concepts but i can't seem to get it working. Probably something simple so i thought i would just ask you all to see what i'm doing wrong: <Test()> _ Public Sub Divide_DivideByZero_LogsError() Dim mock = New Mock(Of ILogger) With mock Dim calc = New MyCalculator(New CalculatorData, .Object) calc.Divide(55, 0) mock.Object.WriteError("test", "Test") .Verify(Function(x) CType(x,ILogger).WriteError(it.IsAny(of String),It.IsAny(Of String)))) End With End Sub I'm using Moq version 3.2.416.3. I get an error on the .verify telling me that i'm calling it with incorrect arguments. I'm just trying to verify that .WriteError was called. any help would be appreciated.

    Read the article

  • AllowPartiallyTrustedCallersAttribute exception - unit testing with moq

    - 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

  • Moq broken? Not working with .net 4.0

    - 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

  • Moq and accessing called parameters

    - by lozzar
    I've just started to implement unit tests (using xUnit and Moq) on an already established project of mine. The project extensively uses dependency injection via the unity container. I have two services A and B. Service A is the one being tested in this case. Service A calls B and gives it a delegate to an internal function. This 'callback' is used to notify A when a message has been received that it must handle. Hence A calls (where b is an instance of service B): b.RegisterHandler(Guid id, Action<byte[]> messageHandler); In order to test service A, I need to be able to call messageHandler, as this is the only way it currently accepts messages. Can this be done using Moq? ie. Can I mock service B, such that when RegisterHandler is called, the value of messageHandler is passed out to my test? Or do I need to redesign this? Are there any design patterns I should be using in this case? Does anyone know of any good resources on this kind of design?

    Read the article

  • Moq how to correctly mock read-only properties or set only properies

    - by Chris Marisic
    What is the correct way for dealing with interfaces the expose only read-only or set-only properties with Moq? Previously I've added the other accessor but this has bleed into my domain too far with random throw new NotImplementedException() statements throughout. I just want to do something simple like mock.VerifySet(view => view.SetOnlyValue, Times.Never()); But this is a compile error of The property 'SetOnlyValue' has no getter

    Read the article

  • How to Unit Test HtmlHelper with Moq?

    - by DaveDev
    Could somebody show me how you would go about creating a mock HTML Helper with Moq? This article has a link to an article claiming to describe this, but following the link only returns an ASP.NET Runtime Error [edit] I asked a more specific question related to the same subject here, but it hasn't gotten any responses. I figured it was too specific, so I thought I could get a more general answer to a more general question and modify it to meet my requirements. Thanks

    Read the article

  • How do you mock the session object collection using Moq

    - by rayray2030
    I am using shanselmann's MvcMockHelper class to mock up some HttpContext stuff using Moq but the issue I am having is being able to assign something to my mocked session object in my MVC controller and then being able to read that same value in my unit test for verification purposes. My question is how do you assign a storage collection to the mocked session object to allow code such as session["UserName"] = "foo" to retain the "foo" value and have it be available in the unit test.

    Read the article

  • ASP.Net MVC Moq SetupGet

    - by Nicholas Murray
    Hi, I am starting out with TDD using Moq to Mock an interface that I have: public interface IDataService { void Commit(); TopListService TopLists { get; } } From the samples I have seen I would expect SetupGet (or Setup) to appear in the intellisense when I type var mockDataService = new Mock<IDataService>(); mockDataService. But it is missing. Could someone suggest why?

    Read the article

  • How do you mock ViewModel Commands using moq?

    - by devnet247
    Hi I might be approaching this all wrong.But please help me to understand. I really want to TDD building wpf application using Moq. I would like to mock the viewmodel. Application Show a list of contacts and when you double click on a contact it shows the contact. Test Moq GetContactsCommand.Test it has been called. Test that you get a list of contacts. Not sure how to mock the viewModel and it's commands can you correct me? So I have started to do the following [Test] public void Should_be_able_to_mock_getContactsCommand_and_get_a_list_of_contacts() { //Arrange var expectedContacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; var mock = new Mock<IContactListViewModel>(); mock.SetupGet(x => x.GetContactsCommand).Verifiable(); mock.SetupGet(x => x.Contacts).Returns(expectedContacts); //Act //? //assert mock.VerifySet(x => x.Contacts, Times.AtLeastOnce()); mock.Object.Contacts.Count.ShouldEqual(expectedContacts.Count); } public interface IContactListViewModel { ObservableCollection<ContactViewModel> Contacts { get; set; } ICommand GetContactsCommand{ get; } } public interface IContactModel { string FirstName { get; set; } string LastName { get; set; } string Email { get; set; } } public class ContactModel : IContactModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } public class ContactViewModel : ViewModelBase { private readonly ContactModel _contactModel; public ContactViewModel(ContactModel contactModel) { _contactModel = contactModel; } public string FirstName { get { return _contactModel.FirstName; } set { _contactModel.FirstName = value; OnPropertyChanged("FirstName"); } } public string LastName { get { return _contactModel.LastName; } set { _contactModel.LastName = value; OnPropertyChanged("LastName"); } } public string Email { get { return _contactModel.Emai; } set { _contactModel.Email = value; OnPropertyChanged("Email"); } } } public class ContactListViewModel : ViewModelBase, IContactListViewModel { private ObservableCollection<ContactViewModel> _contacts; public ObservableCollection<ContactViewModel> Contacts { get { return _contacts; } set { _contacts = value; OnPropertyChanged("Contacts"); } } private RelayCommand _getContactsCommand; public ICommand GetContactsCommand { get { return _getContactsCommand ?? (_getContactsCommand = new RelayCommand(x => GetContacts(), x => CanGetContacts)); } } private static bool CanGetContacts { get { return true; } } private void GetContacts() { //pretend we are going to the service or db whatever Contacts = new ObservableCollection<ContactViewModel> { new ContactViewModel(new ContactModel { FirstName = "Jo", LastName = "Bloggs", Email = "[email protected]" }), new ContactViewModel(new ContactModel { FirstName = "Mary", LastName = "Bloggs", Email = "[email protected]" }) }; } }

    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

  • Mock a Linq to Sql EntityRef using Moq?

    - by Jeremy Holt
    My datacontext contains a table named Userlog with a one to many relationship with table UserProfile. In class UserLog public UserProfile UserProfile { get {return this._UserProfile.Entity;} } In class UserProfile public EntitySet<UserLog> UserLogs { get{return this._UserLogs;} } { set {this._UserLogs.Assign(value); } How would I go about mocking (using Moq) UserLog.UserProfile without changing the autogenerated code? What I would like to do is something like: var mockUserLog = new Mock<UserLog>(); mockUserLog.Setup(c=>c.UserProfile.FirstName).Returns("Fred"); etc I can do this if I go into the designer.cs and make FirstName and UserProfile virtual, however I would like to do this in the partial class. Any ideas? Thanks Jeremy

    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

  • 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

1 2 3 4 5 6 7  | Next Page >