FAQ Database Discussion Community


How do I setup MOQ to accept Any instances of a given Expression?

c#,.net,unit-testing,moq
I have the following interface that I want to mock: public interface ISomeInterface { string GiveMe(Expression<Func<Person, bool>> predicate); } With the following Poco: public class Person { public string Name { get; set; } } Then I am setting up my mock as: [Test] public void Run() { var expectedPredicate...

Setup Mock to redirect to overloaded method

c#,unit-testing,moq
I have a method called: SendMail(string from, string to, string subject, string smtpServer) and an overloaded Method SendMail(string from, string to, string subject, SmtpClient smtpClient) In my unit test I want to setup my MailService mock so that when the method SendMail(string, string, string, string) is called I want to...

Moq + Unit Testing + System.Reflection.TargetParameterCountException: Parameter Count mismatch

unit-testing,moq
I am getting a "System.Reflection.TargetParameterCountException: Parameter Count mismatch" exception when attempting to mock our ApiClient. I am using the following code to Setup the Moq response private void SetupApiClientForGetZones(IEnumerable<Zone> zone) { this.MockHubApiClient.Setup(x => x.GetAsync<IEnumerable<Zone>>(It.IsAny<string>(), It.IsAny<IDictionary<string, string>>())) .Returns( (string name) => { return zone == null ? Task.FromResult<IEnumerable<Zone>>(null) : Task.Run(()...

Unit Test WebApi to upload image using Mock

c#,asp.net,unit-testing,asp.net-web-api,moq
I am starting to write unit tests for all our controllers and seem to be getting the hang of it, but now i am a bit stuck. I have the following controller method that i would like to write a unit test for but a am a bit lost. Can...

Can I access the full power of Autofac in UnitTests, using the Moq integration

c#,unit-testing,mocking,moq,autofac
My project (which happens built on top of Orchard, though I don't think that's relevant) uses Autofac. I am writing unit tests in which I want to stub out any dependencies using Moq, and I'm using the Autofac/Moq integration to achieve this. This is fine for any simple dependencies that...

Test my json data parser should return a logger

c#,unit-testing,moq,xunit
Let's look at my json string structure. So there are 7 loggers, let's expand the nodes for the details. { "root_logger" : "MyFailoverLogger", "loggers": [ { "logger_name": "MyFileLogger", "logger_type": "MyCompany.Loggers.FileSystemLogger", "layout": "${message}|${exception}", "stack_trace": { "error": true, "fatal": false }, "file_path_pattern" : "\\\\corporate.MyCompany.com\\data\\recordings\\logs\\YYYY\\MM\\DD", "file_name_pattern" : "app.{MMDDhhmm}.log", "rollover_after_n_hours" : 5, "rollover_after_n_megabytes": 5,...

RestSharp Moq Object Null Exception C# REST Unit Test

c#,rest,nunit,moq,restsharp
I'm having difficulties trying to figure this out. Any help is greatly appreciated. My restClient.Object gets a null exception. When I inspect the .Object of the restClient I get Message: Exception has been thrown by the target of an invocation. Inner Exception: Value cannot be null.Parameter name: source Stack Trace:...

Unit test MVC action calling Web API using httpclient

model-view-controller,asp.net-web-api,moq
Please see the code below. Using in-memory hosting of httpclient, and Passing httpclient object to controller in order to unit test action method. But I am getting "Internal Server Error" ReasonPhrase upon HttpResponseMessage response =_httpClient.GetAsync. Please help me, is it correct approach? private readonly HttpClient _httpClient; public SecurityMfMvcController(HttpClient httpClient) {...

Can I reuse It.Any argument descriptors in Moq

c#,.net,unit-testing,moq
I have some code similar to FooMock.Setup( m => m.Bar( It.Is<BarArg>( x => long_test_x_is_ok(x) ) ); naively, I thought I could rewrite this as: var barArg = It.Is<BarArg>( x => long_test_x_is_ok(x) ); FooMock.Setup( m => m.Bar( barArg ) ); but Moq doesn't love me. Is there a may to do...

Mocking GetEnumerator using Moq

c#,moq
I'm trying to mock the Variables interface in Microsoft.Office.Interop.Word assembly var variables = new Mock<Variables>(); variables.Setup(x => x.Count).Returns(2); variables.Setup(x => x.GetEnumerator()).Returns(TagCollection); private IEnumerator TagCollection() { var tag1 = new Mock<Variable>(); tag1.Setup(x => x.Name).Returns("Foo"); tag1.Setup(x => x.Value).Returns("Bar"); var tag2 = new Mock<Variable>(); tag2.Setup(x => x.Name).Returns("Baz"); tag2.Setup(x => x.Value).Returns("Qux"); yield return...

moq and fetching an exception

unit-testing,tdd,moq
I'm trying to learn moq test with some simple examples I have public class CustomerService { private readonly ICustomerRepository _repository; public CustomerService(ICustomerRepository repository) { _repository = repository; } public void CreateWithMoney(CustomerDTO dto) { var cust = new Customer { FirstName = dto.FirstName, LastName = dto.LastName, FinacialStatus = dto.FinacialStatus }; if...

Return values set on for-loop/foreach loop

c#,moq
I'm new to Moq and I was able to mock some scenarios like returning list or an object. I'm having this problem where I need to get different values return from GetNoteBookTypeAndProcess in loop. In my below example I mock the GetNoteBooks method and return a list of NoteBook object...

Unit Tests Fail when “Run All” in Visual Studio but passes individually

c#,unit-testing,visual-studio-2012,moq
I am having this wierd problem with MOQ Unit tests. I have around 636 unit tests written using MOQ Framework in VS 2012. When I run them project-wise and/or individually, they pass successfully. but whenever I select Run-All they fail randomly showing different errors. Most of the methods show IO.FileNotFoundException....

Unit test a void method with Mock?

c#,unit-testing,moq,xunit
I want to test a void method with Mock. public class ConsoleTargetBuilder : ITargetBuilder { private const string CONSOLE_WITH_STACK_TRACE = "consoleWithStackTrace"; private const string CONSOLE_WITHOUT_STACK_TRACE = "consoleWithoutStackTrace"; private LoggerModel _loggerModel; private LoggingConfiguration _nLogLoggingConfiguration; public ConsoleTargetBuilder(LoggerModel loggerModel, LoggingConfiguration nLogLoggingConfiguration) { _loggerModel = loggerModel; _nLogLoggingConfiguration = nLogLoggingConfiguration; } public void...

How to mock Asp.net identity UserManager's CreateAsync method

c#,asp.net,moq
I am trying to mock the UserStore's CreateAsync method to have an in-memory user store. public void Can_Create_User() { //Arrange var dummyUser = new ApplicationUser() { UserName = "PinkWarrior", Email = "[email protected]" }; var mockStore = new Mock<IUserStore<ApplicationUser>>(); var userManager = new UserManager<ApplicationUser>(mockStore.Object); mockStore.Setup(x => x.CreateAsync(dummyUser)) .Returns(Task.FromResult(IdentityResult.Success)); //Act Task<IdentityResult> tt...

Mocking Method Execution Times and Sequence

c#,.net,moq
I am using Moq paired with an Interface of methods. I need to test that the methods in this interface are executed in a certain sequence as well as a certain number of times for each one. Interface public interface IInterface { void MethodOne(string foo); void MethodTwo(string foo); } Method...

Mocking repository and callback issue

c#,unit-testing,mocking,moq
I have a Repository which I have mocked using Moq. I have a Service which I have mocked. The service expects a repository in its constructor and I have successfully been able to do this. The problem I am now facing is that, I want the Repository to not connect...

Using mock to test a void method

.net,unit-testing,moq,xunit
I have a class public class NLogRuleComposer : INLogComponentComposer { private LoggingConfiguration _nLogLoggingConfiguration; //TODO: think we need to constructor-inject the logging config public void ComposeComponent(LoggerModel loggerModel , LoggingConfiguration nLogLoggingConfiguration , string loggerFullName) { _nLogLoggingConfiguration = nLogLoggingConfiguration; var ruleName = loggerFullName; var minimumLevel = LogLevel.FromString(loggerModel.level.min_level); var maximumLevel = LogLevel.FromString(loggerModel.level.max_level); var...

Mocking a tree data structure

c#,data-structures,nunit,moq
I'm writing a program that takes a given binary tree and attempts to determine if the tree is balanced. The program expects a binary tree as an input, for example : 1,-1,-2,-3 would be represented with 1 as a root node and the subsequent.getLeft() (or .getRight() if the tree was...

Dealing with TargetWithLayout in XUNIT

c#,integration-testing,moq,xunit
I have a class, public class CreateLoggingRuleFactory : ILoggingRuleFactory { public LoggingRule CreateDefaultLoggingRule(string ruleName , LogLevel minimumLevel, LogLevel maximumLevelName,TargetWithLayout targetWithoutStackTrace) { // blah blah var defaultLoggerRule = new LoggingRule(ruleName, minimumLevel targetWithoutStackTrace); return defaultLoggerRule; } TargetWithLayout is from NLog API. I want to make a integration test for it. So I...

Exception thrown by the type initializer for Moq.Proxy.CastleProxyFactory when not running test in isolation

c#,asp.net-mvc-4,mono,moq,typeinitializeexception
Using Moq the following test on a MVC 4 action method that returns a viewmodel with a Stack was created: // GET: /Home/SowingAndHarvesting public ActionResult SowingAndHarvesting() { // Months are used for the CSS classes // to add to the squares and for displayal within the square. var months =...

How to use Moq to mock up the StackExchange.Redis ConnectionMultiplexer class?

c#,.net,unit-testing,moq,stackexchange.redis
I am working to mock up behaviors related to the StackExchange.Redis library, but can't figure out how to properly mock the sealed classes it uses. A specific example is in my calling code I'm doing something like this: var cachable = command as IRedisCacheable; if (_cache.Multiplexer.IsConnected == false) { _logger.Debug("Not...

Mocking an implementation class with test class within unit test in C#

c#,unit-testing,interface,dependency-injection,moq
I'm trying to write a simple unit test where I have wrapped the HttpContext.Current.Server.MapPath with an interface and implementation. I'm not positive if the implementation is in the right place. public class FooGenerator { ServerPathProvider serverPathProvider = new ServerPathProvider(); public string generateFoo() { BarWebService bws = new BarWebService(serverPathProvider.MapPath("~/path/file")); return stuff;...

Using Selenium and ASPX.net, how to pass a Mock to codebehind?

asp.net,selenium,mocking,moq,code-behind
I am running Selenium against my local IIS to serve pages and verify application behaviour. I would like to mock out the database in some of my tests. I already use an interface "proxy", so I want to replace my implementation with a Mock, so I can merely verify the...

Using Moq to create a mock the type with constructor

c#,.net,unit-testing,mocking,moq
I'm just getting started on unit testing on a simple method and I'm stuck on the below line (specifically the web service object): public string GetToken() { WebService ws = new WebService("https://example.com/", HttpContext.Current.Server.MapPath("~/Config/agent.txt")); Token token = ws.GetToken(name, values, stuff); } At first I tried to use an interface to mock...

How to do internal interfaces visible for Moq?

c#,unit-testing,nunit,moq,internal
I have 3 project in my C# solution. Signatures Structures Tests Signatures has public and internal interfaces. Also it has [assembly: InternalsVisibleTo("Structures")] [assembly: InternalsVisibleTo("Tests")] in AssemblyInfo.cs of. Structures has public and internal classes and [assembly: InternalsVisibleTo("Tests")] in AssemblyInfo.cs of. Tests has next source: <packages> <package id="Moq" version="4.2.1409.1722" targetFramework="net45" /> <package...

Moq return same delegate as parameter

c#,generics,moq
I am very new to Moq and looking for a way to be able to mock up the following interface. public interface ICacheProveder { T GetOrAddToCache<T>(string key, Func<T> populateFunc); } This interface is currently being used to cache items such as code tables. The mock would need to return the...

Mock service that takes unitOfWork in constructor

c#,unit-testing,repository,moq,business-logic
I try to write unit tests on my business logic. What i have now : private Mock<IRepository<Theme>> _mockRepository; private IBaseService<Theme> _service; private Mock<IAdminDataContext> _mockDataContext; private List<Theme> _listTheme; [TestInitialize] public void Initialize() { _mockRepository = new Mock<IRepository<Theme>>(); _mockDataContext = new Mock<IAdminDataContext>(); _service = new ThemeService(_mockDataContext.Object); _listTheme = new List<Theme> { new...

Unit Testing Method with Moq where Collection = serivce.GetCollection()?

c#,wpf,wcf,unit-testing,moq
New to unit testing & Moq. I have a WPF client app which hooks into a WCF service via HttpBinding. I have a test class in MSTest and I'm mocking my service with Moq like so: [TestClass] public class ArticleDataGridTests { //Mock channel for WCF service. Moq mocking framework. Mock<IIsesServiceChannel>...

Using Moq to mock some constructor arguments and letting Ninject take care of the rest?

unit-testing,ninject,moq
My service takes a bunch of arguments in the constructor which are normally injected by Ninject. When writing a unit test, could I mock just one of those constructor arguments and still have Ninject do the rest?

NUnit & MOQ: Testing a try catch that calls another method when an Exception is caught

nunit,moq
I understand that the MOQ framework wasn't really designed to help in this instance, but perhaps you might be able to help... I have a method that uses a try/catch that calls a notification method whenever an exception is thrown. What I am trying to do is create an integration/unit...

How can I verify that RemoveRange has been called on a mock DbContext?

c#,entity-framework,unit-testing,moq
I am using Moq to test code that calls RemoveRange on a DbSet<T>. I have mocked the context object and DbSet, but when I attempt to Verify that RemoveRange was called, I get "Expected invocation on the mock once, but was 0 times." The method I'm testing has this code:...

Mock async Get method with MOQ

c#,.net,async-await,moq
How do I get rid of this error message: Error 5 Cannot implicitly convert type 'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>>' to 'System.Collections.Generic.IEnumerable<TGB.Business.DTO.SchoolyearDTO>'. An explicit conversion exists (are you missing a cast?) I thought my Task.FromResult would fix that but no... mockService.Setup<IEnumerable<SchoolyearDTO>>(c => c.GetSchoolyears()).Returns( Task.FromResult(Enumerable.Empty<SchoolyearDTO>()));...

how to moq simple add function that uses Unit of Work and Repository Pattern

c#,unit-testing,moq
My test looks like this [Fact] public void SimpleAddTest() { // Arrange var authorizationsToBeAdded = new List<PatientPayerAuthInfo> { new PatientPayerAuthInfo (), new PatientPayerAuthInfo () }.ToList(); var persistentAuthorizations = new List<PatientPayerAuthInfo> { new PatientPayerAuthInfo {PatientPayerAuthInfoId = 1 }, new PatientPayerAuthInfo {PatientPayerAuthInfoId = 2 }, new PatientPayerAuthInfo {PatientPayerAuthInfoId = 3 }, new...

Moq a base class function from a derived class

c#,moq
I am new to Moq and I just watched the pluralsight video on Moqing so I felt empowered to go and write some tests. I have a Base Class let’s say Sheet which implements an interface ISheet . Sheet is the base class for pages: abstract class Sheet: ISheet {...

How do I mock multiple levels of DbSet.Include lambdas?

entity-framework,unit-testing,lambda,moq
I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

How to get access to method in base interface with Moq?

c#,unit-testing,moq
I have the following interface: public interface IUserRepository : IRepositoryBase { void AddUser(User user); } IRepositoryBase has a method Update(params object[] entities). Now I want to check what goes into this method in Moq. What I tried is something like this: // ARRANGE var userRepositoryMock = new Mock<IUserRepository>(); (...) //...

Mocking stored procedure's output parameter

c#,.net,unit-testing,mocking,moq
I have following method public bool IsUserAllowedToDoThings(string userName, string thingToDo) { var outputParameter = new ObjectParameter("IsAllowed", typeof(bool?)); _context.SP_IsUserAllowedToDoThings(userName, thingToDo, outputParameter); return (bool)outputParameter.Value; } The method just calls SP using EF and return SP's output result. But I'm having problems to mock SP's output for unit testing. P.S. I'm using MOQ...

Set ContentEncoding when mocking WebResponse

c#,moq
I'm stuck on how to set the contentencoding property as it is not overridable via moq. I currently have the following: var expected = "dfgdfgdfgdfg"; var expectedBytes = Encoding.UTF8.GetBytes(expected); var responseStream = new MemoryStream(); responseStream.Write(expectedBytes, 0, expectedBytes.Length); responseStream.Seek(0, SeekOrigin.Begin); var response = new Mock<HttpWebResponse>(); response.Setup(c => c.GetResponseStream()).Returns(responseStream); response.Setup(c => c.ContentEncoding).Returns("UTF8");...

Modify Returns of existing Setup

moq
Let's say I have a standard setup that looks something like this: mock.Setup(myObj => myObj.MyMethod(It.Is<MyT>(item => IsTrue(item)))).Returns(someList) Is it possible in a separate line of code to identify the exact same Setup (mocking the same method with the same It.Is criteria), and then modify the Returns? For example, suppose under...

Set Moq CallBase to be true by default

testing,moq,abstract
See here for why I want to have CallBase set on my Mock objects: How to use moq to test a concrete method in an abstract class? It would be nice not to have to set this on every one of my mock objects. Is there any way to set...

Mocking out a specific method during a unit test

c#,unit-testing,nunit,moq
I'm relatively new to unit testing, and brand new to Moq. I have been tasked with writing up some unit tests for some pre-existing code. I am struggling with the following method, as it makes a call to model.importing.RunJob, which as the name suggests, kicks off a job. Obviously, I...

Mocking a ViewModel for unit testing with Moq?

c#,wpf,wcf,unit-testing,moq
New to unit testing. I have a WPF client app hooked into a WCF service via basicHttpbinding. Everything works great. I'm using simple constructor Dependency Injection in my viewModel, passing in an IServiceChannel which I then call me service methods on e.g: IMyserviceChannel = MyService; public MyViewModel(IMyServiceChannel myService) { this.MyService...

Setting a passed parameter to a specific value in Moq

c#,unit-testing,moq
I'm unit testing a class that talks to a hardware device through a serial port. I created an interface to isolate the SerialPort class in System.IO: public interface ISerialPort { String PortName { get; set; } bool IsOpen { get; } void Open(); void Close(); int Read(byte[] buffer, int offset,...

force relay to mocking framework

c#,moq,autofixture
I would like to create a customization that configures AutoFixture to pass types it DOES have implementations for off to Moq instead. How can I do that generically? To clarify, consider: public class test { public string foo; public test(IDictionary<string, string> stuffing) { foo = stuffing["bogus"]; } } [TestMethod] public...

Mock certain part of the method using Moq

c#,.net,moq
I'm new to Moq and I would like to mock certain part of my method to test the business logic but having problem to mock the GetCountry method. Below is the code that I used as sample. public class Class1 { public void Process() { MyClass foo = new MyClass();...

MOQ object setup scope / context being lost with builder pattern unit test and web api controller

c#,unit-testing,moq
I am writing unit test for controllers and was running into an issue where it seems the Mocked object is not getting setup when I inject it. If however I create the Mocked object in the controller end point everything works fine. Finally to further complicate things I am doing...

When should I use the .As method of Moq?

c#,unit-testing,moq
When exactly do we need to use the .As method provided by Moq? From the Quickstart documentation: // implementing multiple interfaces in mock var foo = new Mock<IFoo>(); var disposableFoo = foo.As<IDisposable>(); // now the IFoo mock also implements IDisposable :) disposableFoo.Setup(df => df.Dispose()); But I just don't get why...

How could I Mock this code?

c#,unit-testing,mocking,nunit,moq
I want to start mocking some code but I am unsure how to do it. I have read a few tutorials but I cannot apply it to my code (There maybe a reason behind it). I am using NUnit and Moq. (I have removed all other methods so I can...

I have to make a method public and virtual to using Moq Setup

c#,unit-testing,moq
I have a repository that has a few private methods in to help in some general stuff that needs to be done within that repository (don't feel you need to read all the code): public class EFBlogRepository : EFGenericRepository<Blog>, IBlogRepository { public EFBlogRepository( EFDbContext context ) : base( context )...

TypeLoadException using Moq on internal interface in signed assembly

c#,moq
I am using the latest Moq (4.2.1502.911) in Visual Studio 2013 to mock an internal interface contained in another project. Both projects are signed with the same key. After searching here and elsewhere on the web I figured I had to add InternalsVisibleTo for the test assembly and "DynamicProxyGenAssembly2", using...

How to test controller action that serializes a view

c#,asp.net-mvc,nunit,moq
Alright so I am trying to test a controller result to make sure it is returning the right values but I am running into a number of problems with mocking controller contexts. All I want to do is test if someone enters a number on a page if the JsonResult...