moq

Mock a method for test

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-04 02:36:26
Trying to mock a method that is called within another method. public virtual bool hello(string name, int age) { string lastName = GetLastName(); } public virtual string GetLastName() { return "xxx"; } Mock<program> name= new Mock<program>(); name.Setup(x => x.GetLastName()).Returns("qqq"); I want the method GetLastName to always return "qqq". Kritner This should work, assuming those are the full method implementations public class MyProgram { public bool hello(string name, int age) { string lastName = GetLastName(); return string.Format("hello {0}", lastName); } public virtual string

Moq testing void method

戏子无情 提交于 2019-12-04 02:23:37
Hi I am new to Moq testing and having hard time to do a simple assertion. I am using an interface public interface IAdd { void add(int a, int b); } Moq for the IAdd interface is: Mock<IAdd> mockadd = new Mock<IAdd>(); mockadd.Setup(x => x.add(It.IsAny<int>(), It.IsAny<int>()).callback((int a, int b) => { a+b;}); IAdd testing = mockadd.Object; Since the add method is void, it doesn't return any value to Assert with. How can I assert this setup? Why mocking is used? It used for verifying that SUT (system under test) interacts correctly with its dependencies (which should be mocked). Correct

Does this test make proper use of AutoFixture and Moq?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 02:10:07
Does this test make proper use of AutoFixture and Moq? Is it written as concisely as possible? The test fails, as expected, and passes after writing the correct implementation. [Fact] public void CustomerPropertyIsCorrect() { var fixture = new AutoMoqFixture(); var expected = fixture.Create<CardHolderCustomer>(); var builderMock = fixture .Freeze<Mock<ICustomerAdapter>>() .Setup(x => x.BuildCustomer()).Returns(expected); var sut = fixture.Create<CardHolderViewModel>(); var actual = sut.Customer; Assert.Equal(expected, actual); } Nikos Baxevanis It's looking good! However, you can also use it

Simulate a delay in execution in Unit Test using Moq

拈花ヽ惹草 提交于 2019-12-04 01:34:45
I'm trying to test the following: protected IHealthStatus VerifyMessage(ISubscriber destination) { var status = new HeartBeatStatus(); var task = new Task<CheckResult>(() => { Console.WriteLine("VerifyMessage(Start): {0} - {1}", DateTime.Now, WarningTimeout); Thread.Sleep(WarningTimeout - 500); Console.WriteLine("VerifyMessage(Success): {0}", DateTime.Now); if (CheckMessages(destination)) { return CheckResult.Success; } Console.WriteLine("VerifyMessage(Pre-Warning): {0} - {1}", DateTime.Now, ErrorTimeout); Thread.Sleep(ErrorTimeout - 500); Console.WriteLine("VerifyMessage(Warning): {0}",

How to use Moq to satisfy a MEF import dependency for unit testing?

瘦欲@ 提交于 2019-12-04 01:32:32
问题 This is my interface public interface IWork { string GetIdentifierForItem(Information information); } and my class public class A : IWork { [ImportMany] public IEnumerable<Lazy<IWindowType, IWindowTypeInfo>> WindowTypes { get; set; } public string GetIdentifierForItem(Information information) { string identifier = null; string name = information.TargetName; // Iterating through the Windowtypes // searching the 'Name' and then return its ID foreach (var windowType in WindowTypes) { if (name ==

Instantiate new System.Web.Http.OData.Query.ODataQueryOptions in nunit test of ASP.NET Web API controller

ぐ巨炮叔叔 提交于 2019-12-04 01:00:20
I have an ASP.NET MVC4 Web API project with an ApiController-inheriting controller that accepts an ODataQueryOptions parameter as one of its inputs. I am using NUnit and Moq to test the project, which allow me to setup canned responses from the relevant repository methods used by the ApiController. This works, as in: [TestFixture] public class ProjectControllerTests { [Test] public async Task GetById() { var repo = new Mock<IManagementQuery>(); repo.Setup(a => a.GetProjectById(2)).Returns(Task.FromResult<Project>(new Project() { ProjectID = 2, ProjectName = "Test project", ProjectClient = 3 })

Proper way of testing ASP.NET Core IMemoryCache

混江龙づ霸主 提交于 2019-12-04 00:17:28
I'm writing a simple test case that tests that my controller calls the cache before calling my service. I'm using xUnit and Moq for the task. I'm facing an issue because GetOrCreateAsync<T> is an extension method, and those can't be mocked by the framework. I relied on internal details to figure out I can mock TryGetValue instead and get away with my test (see https://github.com/aspnet/Caching/blob/c432e5827e4505c05ac7ad8ef1e3bc6bf784520b/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L116 ) [Theory, AutoDataMoq] public async Task GivenPopulatedCacheDoesntCallService(

Moq testing LINQ Where queries

旧街凉风 提交于 2019-12-03 23:22:15
I'm using EF 4.1 to build a domain model. I have a Task class with a Validate(string userCode) method and in it I want to ensure the user code maps to a valid user in the database, so: public static bool Validate(string userCode) { IDbSet<User> users = db.Set<User>(); var results = from u in users where u.UserCode.Equals(userCode) select u; return results.FirstOrDefault() != null; } I can use Moq to mock IDbSet no problem. But ran into trouble with the Where call: User user = new User { UserCode = "abc" }; IList<User> list = new List<User> { user }; var users = new Mock<IDbSet<User>>(); users

how to assert if a method has been called using nunit

余生颓废 提交于 2019-12-03 22:57:39
is it possible to assert whether a method has been called? I'm testing the following method and I want to assert that the _tokenManager.GetToken() has been called. I just want to know if the method has been called as the method does not return a value. I am using Moq. Thanks, Code snippet public void Subscribe(string code, string emailAddress, string columnKey) { // Request authentication token var token = _tokenManager.GetToken(code, false); if (!_tokenValidator.Validate(token)) { // Token has expired or invalid - refresh the token token = _tokenManager.GetToken(code, true); } // Subscribe

Mock IMemoryCache in unit test

我与影子孤独终老i 提交于 2019-12-03 22:54:39
I am using asp net core 1.0 and xunit. I am trying to write a unit test for some code that uses IMemoryCache . However whenever I try to set a value in the IMemoryCache I get an Null reference error. My unit test code is like this: The IMemoryCache is injected into the class I want to test. However when I try to set a value in the cache in the test I get a null reference. public Test GetSystemUnderTest() { var mockCache = new Mock<IMemoryCache>(); return new Test(mockCache.Object); } [Fact] public void TestCache() { var sut = GetSystemUnderTest(); sut.SetCache("key", "value"); //NULL Reference