moq

Testing EF async methods with sync methods with MOQ

回眸只為那壹抹淺笑 提交于 2019-12-03 10:16:20
I have this method: public async Task DeleteUserAsync(Guid userId) { using (var context = this.contextFactory.Create()) { var user = await context.Users.FirstOrDefaultAsync(x => x.Id.Equals(userId)); if (user == null) { throw new Exception("User doesn't exist"); } context.Users.Remove(user); await context.SaveChangesAsync(); } } I want to test it out. So I create the test: [TestMethod] public async Task DeleteUsersSuccessfulCallTest() { // Arrange var id = Guid.NewGuid(); var user = new User() { Id = id }; var context = new Mock<IDashboardContext>(); var usersDbSet = DbSetQueryMocking

Is it possible (with Moq) to stub method calls with Lambda parameters?

笑着哭i 提交于 2019-12-03 10:01:48
问题 If I do this: var repository = new Mock<IRepository<Banner>>(); repository.Setup(x => x.Where(banner => banner.Is.AvailableForFrontend())).Returns(list); "Where" is a method on my repository that takes a Func<T, ISpecification<T> . AvailableForFrontend returns an implementation of ISpecification, and list is an IEnumberable of the generic type of the repository. It compiles fine, but i get the following error when I run my tests. ---- System.NotSupportedException : Expression banner =>

How to add claims in a mock ClaimsPrincipal

血红的双手。 提交于 2019-12-03 09:37:01
I am trying to unit test my controller code which gets the information from the ClaimsPrincipal.Current. In the controller code I public class HomeController { public ActionResult GetName() { return Content(ClaimsPrincipal.Current.FindFirst("name").Value); } } And I am trying to mock my ClaimsPrincipal with claims but I still don't have any mock value from the claim. // Arrange IList<Claim> claimCollection = new List<Claim> { new Claim("name", "John Doe") }; var identityMock = new Mock<ClaimsIdentity>(); identityMock.Setup(x => x.Claims).Returns(claimCollection); var cp = new Mock

Usage of Moq When(Func<bool>) method

旧城冷巷雨未停 提交于 2019-12-03 09:35:59
I can't find an example of the usage of the When method in Moq When(Func<bool> condition); What is the purpose/usage of the method? Please give a code sample demonstrating a scenario where it would be useful. "When" gives you the option to have different setups for the same mocked object, depending on whatever you have to decide. Let's say you want to test a format provider you have written. If the program (= test) runs in the morning a certain function call should return null; in the afternoon a certain value. Then you can use "When" to write those conditional setups. var mockedService = new

Reset mock verification in Moq?

落花浮王杯 提交于 2019-12-03 09:17:39
Setup as so: public interface IFoo { void Fizz(); } [Test] public void A() { var foo = new Mock<IFoo>(MockBehavior.Loose); foo.Object.Fizz(); foo.Verify(x => x.Fizz()); // stuff here foo.Verify(x => x.Fizz(), Times.Never()); // currently this fails } Basically I'd like to enter some code at the // stuff here to make the foo.Verify(x => x.Fizz(), Times.Never()) pass. And because this probably constitutes moq/unit testing abuse, my justification is so I can do something like this: [Test] public void Justification() { var foo = new Mock<IFoo>(MockBehavior.Loose); foo.Setup(x => x.Fizz()); var

How do I go about unit testing with Entity Framework and Moq?

你离开我真会死。 提交于 2019-12-03 08:19:58
I'm new to Moq, and wanting to use it like a backing store for data - but without touching the live database. My setup is as follows: A UnitOfWork contains all repositories, and is used for data access throughout the application. A Repository represents a direct hook into a DbSet, provided by a DbContext. A DbContext contains all DbSets. Here is my test so far: // ARRANGE var user = new User() { FirstName = "Some", LastName = "Guy", EmailAddress = "some.guy@mockymoqmoq.com", }; var mockSet = new MockDbSet<User>(); var mockContext = new Mock<WebAPIDbContext>(); mockContext.Setup(c => c.Set<User

How to test asp.net core built-in Ilogger

喜你入骨 提交于 2019-12-03 08:14:17
问题 I want to verify some logs logged. I am using the asp.net core built-in ILogger, and inject it with the asp.net core built-in DI: private readonly ILogger<InvoiceApi> _logger; public InvoiceApi(ILogger<InvoiceApi> logger) { _logger = logger; } then I use it like: _logger.LogError("error)); I tried to mock it (with moq) as usual by: MockLogger = new Mock<ILogger<InvoiceApi>>(); and inject this in the service for test by: new InvoiceApi(MockLogger.Object); then tried verify: MockLogger.Verify(m

How to Unit Test HtmlHelper with Moq?

我只是一个虾纸丫 提交于 2019-12-03 08:12:20
问题 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 回答1: What you can do is

How to Unit Test a custom ModelBinder using Moq?

允我心安 提交于 2019-12-03 07:24:42
问题 I'm having some difficulty writing some Unit Tests to test a custom ModelBinder that I created. The ModelBinder I'm trying to Unit Test is the JsonDictionaryModelBinder that I posted here. The problem I'm having is getting the Mocking all setup using Moq. I keep getting Null Exceptions due to the HttpContextBase not being Mocked correctly. I think. Could someone help me figure out what I'm not doing correclty? Here's a sample of the Unit Test I'm trying to write that doesn't work: [TestMethod

Mock an update method returning a void with Moq

寵の児 提交于 2019-12-03 07:21:17
问题 In my test, I defined as data a List<IUser> with some record in. I'd like setup a moq the methode Update , this method receive the user id and the string to update. Then I get the the IUser and update the property LastName I tried this : namespace Tests.UnitTests { [TestClass] public class UsersTest { public IUsers MockUsersRepo; readonly Mock<IUsers> _mockUserRepo = new Mock<IUsers>(); private List<IUser> _users = new List<IUser>(); [TestInitialize()] public void MyTestInitialize() { _users