public void Setup() { this.moqer = new AutoMoq.AutoMoqer(); mockRssChannelsRepository = moqer.GetMock<IRssChannelsRepository>(); this.mockMapper = moqer.GetMock<IMapper>(); this.sut = this.moqer.Resolve<RssChannelsService>(); }
public void UsesRegistryToGetNewComics() { var mocker = new AutoMoqer(); var lastExplosmComic = new Comic(); var newExplosmComic1 = new Comic(); var newExplosmComic2 = new Comic(); var explosm = new Mock<IComicDownloader>(); explosm.Setup(m => m.GetNewComicsSince(lastExplosmComic)) .Returns(new[] { newExplosmComic1, newExplosmComic2 }); mocker.GetMock<IComicsRepository>() .Setup(m => m.GetLastImportedComic(ComicType.Explosm)) .Returns(lastExplosmComic) .Verifiable(); var registry = new ComicConfigRegistry(); registry.Add(new ComicConfig(ComicType.Explosm, explosm.Object)); // ReSharper disable once RedundantTypeArgumentsOfMethod mocker.SetInstance<ComicConfigRegistry>(registry); mocker.Create<ImportProcess>() .Run(); mocker.GetMock<IComicsRepository>().VerifyAll(); mocker.GetMock<IComicsRepository>() .Verify(m => m.InsertComic(newExplosmComic1), Times.Once); mocker.GetMock<IComicsRepository>() .Verify(m => m.InsertComic(newExplosmComic2), Times.Once); }
public void Setup() { _mocker = new AutoMoqer(); var mockFileSystem = new MockFileSystem(); _mocker.SetInstance<IFileSystem>(mockFileSystem); // GetMock of the abstract class before create to prevent automoq bugs _mocker.GetMock<FileSystemWatcherBase>(); _instance = _mocker.Create<DirectoryWatcher>(); // Mocked files var content = new byte[] {1, 1, 1}; _expectedFileLength = content.Length; _expectedWriteDate = DateTime.Now.ToUniversalTime(); var nameWithPath = mockFileSystem.Path.Combine(Path, FileName); mockFileSystem.AddFile(nameWithPath, new MockFileData(content) { LastWriteTime = _expectedWriteDate }); _trackedFile = new TrackedFile(); _mocker.GetMock<ITrackedFileStore>() .Setup(x => x.GetTrackedFileByFullPath(nameWithPath)) .Returns(_trackedFile); }
public void WhenAccessTokenIsExpired_ThenReturnFalse() { var mocker = new AutoMoqer(); mocker.MockServiceLocator(); var issuer = new OAuthIssuer(); mocker.GetMock<IOAuthServiceLocator>().Setup(x => x.Issuer).Returns(issuer); mocker.GetMock<IConfiguration>().Setup(x => x.AccessTokenExpirationLength).Returns(3600); var validator = mocker.Resolve<ResourceRequestAuthorizer>(); var token = issuer.GenerateAccessToken(new TokenData { ConsumerId = 1, ResourceOwnerId = 5, Timestamp = DateTimeOffset.UtcNow.AddMinutes(-65).Ticks }); mocker.GetMock<IOAuthRequest>().Setup(x => x.AccessToken).Returns(token); var result = validator.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.IsFalse(result); }
public void RequiresClientSecret() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.Method).Returns(HttpMethod.Post); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.ClientCredentials); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns<string>(null); mocker.GetMock<IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); var validator = mocker.Resolve<ClientCredentialsRequestValidator>(); var result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsNotNull(result); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsFalse(string.IsNullOrWhiteSpace(result.ErrorDescription)); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns(" "); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsNotNull(result); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsFalse(string.IsNullOrWhiteSpace(result.ErrorDescription)); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns("asdffa"); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsTrue(result.Success); }
public void RequiresAuthorizationCodeGrantType() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns<string>(null); var validator = mocker.Resolve<AuthorizationCodeRequestValidator>(); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(""); var result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsTrue(result.ErrorDescription.HasValue()); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(" "); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsTrue(result.ErrorDescription.HasValue()); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns("bad"); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.AreEqual(ErrorCode.InvalidGrant, result.ErrorCode); Assert.IsTrue(result.ErrorDescription.HasValue()); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.AuthorizationCode); mocker.GetMock<IOAuthRequest>().Setup(x => x.AuthorizationCode).Returns("authcode"); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsTrue(result.Success); }
public void TestWithListener() { var mocker = new AutoMoqer(); var mockConnectionFactory = mocker.GetMock<RabbitMQ.Client.ConnectionFactory>(); var mockConnection = mocker.GetMock<RabbitMQ.Client.IConnection>(); mockConnectionFactory.Setup(c => c.CreateConnection()).Returns(mockConnection.Object); var called = new AtomicInteger(0); var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object); var mockConnectionListener = new Mock<IConnectionListener>(); mockConnectionListener.Setup(m => m.OnCreate(It.IsAny<IConnection>())).Callback((IConnection conn) => called.IncrementValueAndReturn()); mockConnectionListener.Setup(m => m.OnClose(It.IsAny<IConnection>())).Callback((IConnection conn) => called.DecrementValueAndReturn()); connectionFactory.ConnectionListeners = new List<IConnectionListener>() { mockConnectionListener.Object }; var con = connectionFactory.CreateConnection(); Assert.AreEqual(1, called.Value); con.Close(); Assert.AreEqual(1, called.Value); mockConnection.Verify(c => c.Close(), Times.Never()); connectionFactory.CreateConnection(); Assert.AreEqual(1, called.Value); connectionFactory.Dispose(); Assert.AreEqual(0, called.Value); mockConnection.Verify(c => c.Close(), Times.AtLeastOnce()); mockConnectionFactory.Verify(c => c.CreateConnection(), Times.Exactly(1)); }
public void RequiresValidRedirectUrl() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.ResponseType).Returns(ResponseType.Code); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns("12345"); var validator = mocker.Resolve<AuthorizationRequestValidator>(); var result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsTrue(result.Success); mocker.GetMock<IOAuthRequest>().Setup(x => x.RedirectUri).Returns(""); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsFalse(result.Success); Assert.IsNotNull(result); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsFalse(string.IsNullOrWhiteSpace(result.ErrorDescription)); mocker.GetMock<IOAuthRequest>().Setup(x => x.RedirectUri).Returns("/test/whatever"); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsFalse(result.Success); Assert.IsNotNull(result); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsFalse(string.IsNullOrWhiteSpace(result.ErrorDescription)); mocker.GetMock<IOAuthRequest>().Setup(x => x.RedirectUri).Returns(""); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsFalse(result.Success); Assert.IsNotNull(result); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsFalse(string.IsNullOrWhiteSpace(result.ErrorDescription)); mocker.GetMock<IOAuthRequest>().Setup(x => x.RedirectUri).Returns("tcp://whatnow.com"); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsFalse(result.Success); Assert.IsNotNull(result); Assert.AreEqual(ErrorCode.InvalidRequest, result.ErrorCode); Assert.IsFalse(string.IsNullOrWhiteSpace(result.ErrorDescription)); mocker.GetMock<IOAuthRequest>().Setup(x => x.RedirectUri).Returns("http://something.com"); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsTrue(result.Success); mocker.GetMock<IOAuthRequest>().Setup(x => x.RedirectUri).Returns("https://something.com"); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsTrue(result.Success); }
public void Setup() { mocker = new AutoMoqer(); mocker.GetMock<IMongoCollectionBuilder>() .Setup(x => x.GetCollection<Sample>()) .Returns(mocker.GetMock<IMongoCollection<Sample>>().Object); }
public void Setup() { mocker = new AutoMoqer(); mocker.GetMock<IMongoFactory>() .Setup(x => x.CreateMongo()) .Returns(mocker.GetMock<IMongo>().Object); }
public void Init() { mocker = new AutoMoqer(); guid = Guid.NewGuid(); mocker.GetMock<IGuidGetter>().Setup(a => a.GetGuid()).Returns(guid); mocker.GetMock<IGetWorkingFolderPath>().Setup(a => a.GetPathToWorkingFolder()) .Returns("pathToWorkingFolder"); }
public void TestCacheSizeExceeded() { var mocker = new AutoMoqer(); var mockConnectionFactory = mocker.GetMock<RabbitMQ.Client.ConnectionFactory>(); var mockConnection = mocker.GetMock<RabbitMQ.Client.IConnection>(); var mockChannel1 = new Mock<IModel>(); var mockChannel2 = new Mock<IModel>(); var mockChannel3 = new Mock<IModel>(); mockConnectionFactory.Setup(c => c.CreateConnection()).Returns(mockConnection.Object); mockConnection.Setup(c => c.CreateModel()).ReturnsInOrder(mockChannel1.Object, mockChannel2.Object, mockChannel3.Object); mockConnection.Setup(c => c.IsOpen).Returns(true); // Called during physical close mockChannel1.Setup(c => c.IsOpen).Returns(true); mockChannel2.Setup(c => c.IsOpen).Returns(true); mockChannel3.Setup(c => c.IsOpen).Returns(true); var ccf = new CachingConnectionFactory(mockConnectionFactory.Object); ccf.ChannelCacheSize = 1; var con = ccf.CreateConnection(); var channel1 = con.CreateChannel(false); // cache size is 1, but the other connection is not released yet so this creates a new one var channel2 = con.CreateChannel(false); Assert.AreNotSame(channel1, channel2); // should be ignored, and added last into channel cache. channel1.Close(); // should be physically closed channel2.Close(); // remove first entry in cache (channel1) var ch1 = con.CreateChannel(false); // create a new channel var ch2 = con.CreateChannel(false); Assert.AreNotSame(ch1, ch2); Assert.AreSame(ch1, channel1); Assert.AreNotSame(ch2, channel2); ch1.Close(); ch2.Close(); mockConnection.Verify(c => c.CreateModel(), Times.Exactly(3)); con.Close(); // should be ignored mockConnection.Verify(c => c.Close(), Times.Never()); mockChannel1.Verify(c => c.Close(), Times.Never()); mockChannel2.Verify(c => c.Close(), Times.AtLeastOnce()); mockChannel3.Verify(c => c.Close(), Times.AtLeastOnce()); }
public void RequiresAuthorizationCodeGrantType() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns<string>(null); var authorizer = mocker.Resolve<AuthorizationCodeAuthorizer>(); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown."); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(""); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown."); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(" "); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown."); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns("asdf"); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown."); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidGrant, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } }
public void GetRedirectUrl() { var mocker = new AutoMoqer(); var properties = new Dictionary<string, IList<string>> { {OAuthTokens.ResponseType, new[] {ResponseType.Code}}, {OAuthTokens.ClientId, new[]{"1"}}, {OAuthTokens.RedirectUri, new[]{"http://mydomain.com"}} }; mocker.GetMock<IRequest>().Setup(x => x.Values).Returns(properties); var request = new AuthorizationRequest(mocker.GetMock<IRequest>().Object, mocker.GetMock<IOAuthServiceLocator>().Object); try { properties[OAuthTokens.RedirectUri] = new[] { "http://wrong.com" }; request.GetRedirectUri(new ConsumerImpl {Domain = "test.com"}); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } try { properties[OAuthTokens.RedirectUri] = new[] { "wrong.com" }; request.GetRedirectUri(new ConsumerImpl { Domain = "test.com" }); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } try { properties[OAuthTokens.RedirectUri] = new[]{"/test.com/test"}; request.GetRedirectUri(new ConsumerImpl { Domain = "test.com" }); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } properties[OAuthTokens.RedirectUri] = new[] { "http://test.com/response" }; var result = request.GetRedirectUri(new ConsumerImpl { Domain = "test.com" }); Assert.AreEqual("http://test.com/response", result); result = request.GetRedirectUri(new ConsumerImpl { Domain = "test.com", RedirectUrl = "http://test.com/response" }); Assert.AreEqual("http://test.com/response", result); }
public void WhenClientIdIsInvalid_ThenThrowsException() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns(""); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.GetMock<IOAuthRequest>().Setup(x => x.Username).Returns("username"); mocker.GetMock<IOAuthRequest>().Setup(x => x.Password).Returns("password"); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.Password); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock<IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns<ConsumerImpl>(null); var authorizer = mocker.Resolve<PasswordTokenRequestAuthorizer>(); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidClient, ex.ErrorCode); Assert.IsTrue(!string.IsNullOrWhiteSpace(ex.ErrorDescription)); } }
public void WhenAccessTokenIsIncluded_ThenValidationSucceeds() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.AccessToken).Returns("accesstoken"); var validator = mocker.Resolve<ResourceRequestValidator>(); var result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsTrue(result.Success); }
/// <summary> /// Sets a mock HttpRequestBase onto the controller provided. /// </summary> /// <param name="controller"></param> public static void SetMockContext(AutoMoqer autoMoqer, Controller controller) { var context = autoMoqer.GetMock<HttpContextBase>(); var request = autoMoqer.GetMock<HttpRequestBase>(); request.Setup(x => x.QueryString).Returns(new NameValueCollection()); context.Setup(x => x.Request).Returns(request.Object); var requestContext = new RequestContext(context.Object, new RouteData()); controller.ControllerContext = new ControllerContext(requestContext, controller); }
public void ItRunsTheImports() { var mocker = new AutoMoqer(); mocker.GetMock<IImportProcess>() .Setup(m => m.ImportedComics) .Returns(new Comic[] {}); mocker.Create<AdminController>().Refresh(authToken: ConfigurationManager.AppSettings["AdminAuthToken"]); mocker.GetMock<IImportProcess>() .Verify(m => m.Run(), Times.Once); }
public void ItSearchesForTheReferencedComic(ComicType type) { var mocker = new AutoMoqer(); mocker.GetMock<IComicsRepository>() .Setup(m => m.GetLatestComics(type, It.IsAny<int>())) .Returns(Enumerable.Empty<Comic>().ToList()) .Verifiable(); mocker.Create<FeedController>().Feed(type); mocker.GetMock<IComicsRepository>().Verify(); }
public void DecodesBasicAuthentication() { var header = Convert.ToBase64String(Encoding.ASCII.GetBytes("user:password")); var mocker = new AutoMoqer(); var requestMock = mocker.GetMock<IRequest>(); requestMock.SetupGet(x => x.Headers).Returns(new Dictionary<string, IList<string>> { {"Authorization", new List<string> { "Basic " + header }}}); var basicAuth = new HttpBasicAuthenticationScheme(mocker.GetMock<IRequest>().Object); Assert.AreEqual("user", basicAuth.Username); Assert.AreEqual("password", basicAuth.Password); }
public void Init() { mocker = new AutoMoqer(); mocker.GetMock<IGetPathToDataDirectoryService>().Setup(a => a.GetPathToDirectory()).Returns("path"); mocker.GetMock<IXmlFileSerializationHelper>().Setup(a => a.DeserializeListFromPath<ContentNodeProviderDraft>("path\\ContentNodeProviderDrafts.xml")) .Returns(new List<ContentNodeProviderDraft>() { new ContentNodeProviderDraft() { PageId = "1", }, }); }
public void Init() { mocker = new AutoMoqer(); mocker.GetMock<IGetPathToDataDirectoryService>().Setup(a => a.GetPathToDirectory()) .Returns("path"); mocker.GetMock<IXmlFileSerializationHelper>().Setup(a => a.DeserializeListFromPath<TreeNode>("path" + Path.DirectorySeparatorChar + "TreeNodes.xml")) .Returns(new List<TreeNode>() { new TreeNode() { Id = "1", }, }); }
public void Init() { mocker = new AutoMoqer(); mocker.GetMock<IGetPathToDataDirectoryService>().Setup(a => a.GetPathToDirectory()) .Returns("path"); mocker.GetMock<IXmlFileSerializationHelper>().Setup(a => a.DeserializeListFromPath<SectionNodeProviderDraft>("path" + Path.DirectorySeparatorChar + "SectionNodeProviderDrafts.xml")) .Returns(new List<SectionNodeProviderDraft>() { new SectionNodeProviderDraft() { SectionId = "1", }, }); }
public void Init() { mocker = new AutoMoqer(); mocker.GetMock<IGetPathToDataDirectoryService>().Setup(a => a.GetPathToDirectory()) .Returns("path"); mocker.GetMock<IXmlFileSerializationHelper>().Setup(a => a.DeserializeListFromPath<ContentNodeProviderPublishedVersion>("path" + Path.DirectorySeparatorChar + "ContentNodeProviderPublishedVersions.xml")) .Returns(new List<ContentNodeProviderPublishedVersion>() { new ContentNodeProviderPublishedVersion() { PageId = "1", }, }); }
public void TestGetIndexShouldReturnListOfSales() { var model = new SalesListItemModel(); _mocker.GetMock <IGetSalesListQuery>() .Setup(p => p.Execute()) .Returns(new List <SalesListItemModel> { model }); var viewResult = _controller.Index(); var results = (List <SalesListItemModel>)viewResult.Model; Assert.That(results.Single(), Is.EqualTo(model)); }
public async void IniciaEntrega_test_BadRequest() { //Given var mocker = new AutoMoqer(); var baseControllerMock = mocker.Create <EntregaController>(); var faker = AutoFaker.Create(); var response = false; var responseTask = Task.Factory.StartNew(() => response); var expectResponse = baseControllerMock.BadRequest("Erro ao iniciar a Entrega!"); var service = mocker.GetMock <IEntregaCommand>(); service.Setup(r => r.Inicia()).Returns(responseTask).Verifiable(); //When var result = await baseControllerMock.IniciaEntrega(); //Then var comparison = new CompareLogic(); service.Verify(mock => mock.Inicia(), Times.Once()); var comp = comparison.Compare(result, expectResponse); Assert.True(comp.AreEqual); }
public void DecorateLineTests_ColorTesting_ExpectedBehavior(string text) { int itCount = text.Length / FSI.Length; MockSequence sequence = new MockSequence(); Mock <IBackgroundTextIndexDrawer> colorMock = mocker.GetMock <IBackgroundTextIndexDrawer>(); for (int i = 0; i < itCount; i++) { colorMock.InSequence(sequence).Setup( p => p.DrawBackground( It.IsAny <int>(), It.IsAny <int>(), It.IsAny <Brush>() ) ); } decorator.DecorateLine(text, 0, text.Length); for (int i = 0; i < itCount; i++) { colorMock.InSequence(sequence).Setup( p => p.DrawBackground( It.IsAny <int>(), It.IsAny <int>(), rainbowgetter.GetColorByIndex(i) ) ); } }
public void InitialiseLogStream_Verify_CreateLogStream() { //arrange var container = new AutoMoqer(); var amazonclientMock = container.GetMock <IAmazonCloudWatchLogs>(); amazonclientMock.SetupSequence(x => x.DescribeLogStreams(It.IsAny <DescribeLogStreamsRequest>())) .Returns(new DescribeLogStreamsResponse { LogStreams = new List <LogStream>() }) .Returns(new DescribeLogStreamsResponse { LogStreams = new List <LogStream> { new LogStream { LogStreamName = Logstream } } }); var target = new CloudWatchLogsClientWrapper(amazonclientMock.Object, LogGroup, Logstream); //act target.InitialiseLogStream(); //assert amazonclientMock.Verify(x => x.CreateLogStream(It.IsAny <CreateLogStreamRequest>())); }
public void SendShout_should_return_a_success_response_for_a_movie_shout() { //Setup var expectedUrl = String.Format("{0}{1}", Url.ShoutMovie, Constants.ApiKey); var expectedJson = "{\"username\": \"username\",\"password\": \"sha1hash\",\"imdb_id\": \"tt0082971\",\"title\": \"Indiana Jones and the Raiders of the Lost Ark\",\"year\": 1981,\"shout\": \"I grew up with this movie and even today it is EPIC.\"}"; var jsonResult = "{\"status\":\"success\",\"message\":\"shout added to Indiana Jones and the Raiders of the Lost Ark (1981)\"}"; var mocker = new AutoMoqer(); mocker.GetMock<HttpProvider>().Setup(s => s.DownloadString(expectedUrl, It.Is<string>(e => e.Replace(" ", "").Replace("\r\n", "").Replace("\t", "") == expectedJson.Replace(" ", "")))).Returns(jsonResult); var shout = new ShoutMovie { Username = "******", Password = "******", ImdbId = "tt0082971", Title = "Indiana Jones and the Raiders of the Lost Ark", Year = 1981, Shout = "I grew up with this movie and even today it is EPIC." }; //Act var result = mocker.Resolve<ShoutProvider>().SendShout(Constants.ApiKey, shout); //Assert result.Should().NotBeNull(); result.Status.Should().Be(ResultStatusType.Success); result.Message.Should().Be("shout added to Indiana Jones and the Raiders of the Lost Ark (1981)"); }
public void HighScore_ReturnsTrue_WhenHighScoreMatchesMaxValue() { _mocker.GetMock <IHighScore>() .Setup(x => x.Value()) .Returns(HighScore = 1); var player1 = new PersonViewModel { PersonId = Guid.NewGuid(), FirstName = "Rob", LastName = "Dunavan", HighScore = 555 }; var player2 = new PersonViewModel { PersonId = Guid.NewGuid(), FirstName = "jeff", LastName = "george", HighScore = 4 }; var PlayerScore = _mocker.Create <PlayerScore>(); var isMaxValue = PlayerScore.IsThisYourHighScore(player1); var isMaxValue1 = PlayerScore.IsThisYourHighScore(player2); Assert.IsTrue(isMaxValue); Assert.IsTrue(isMaxValue1); }
public void Init() { mocker = new AutoMoqer(); mocker.GetMock<ICurrentUserContext>() .Setup(a => a.GetCurrentPrincipal()) .Returns(new GenericPrincipal(new GenericIdentity("test"), new string[] { })); }
public void WhenAccessTokenIsMissing_ThenValidationFails() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.AccessToken).Returns(""); var validator = mocker.Resolve<ResourceRequestValidator>(); var result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsFalse(result.Success); mocker.GetMock<IOAuthRequest>().Setup(x => x.AccessToken).Returns<string>(null); result = validator.ValidateRequest(mocker.GetMock<IOAuthRequest>().Object); Assert.IsFalse(result.Success); }
public void SetUp() { _moqer = new AutoMoqer(); _courseElectrician = new ApprenticeshipCourse { CourseType = ApprenticeshipCourseType.Standard, Duration = 23, FundingCap = 12000, Id = "567", Level = 4, Title = "Electrician" }; _courseCarpentry = new ApprenticeshipCourse { CourseType = ApprenticeshipCourseType.Standard, Duration = 36, FundingCap = 9000, Id = "123", Level = 4, Title = "Carpentry" }; _apprenticeshipCourses = new List <ApprenticeshipCourse> { _courseElectrician, _courseCarpentry, }; _moqer.GetMock <IApprenticeshipCourseDataService>() .Setup(x => x.GetAllStandardApprenticeshipCourses()) .Returns(_apprenticeshipCourses); }
public void SetUp() { _automoqer = new AutoMoqer(); _automoqer.GetMock <IEmployeeClient>() .Setup(p => p.GetEmployees()) .Returns(new List <Employee>() { new Employee() { Name = "Mocked", HourlySalary = 10, MonthlySalary = 100, ContractType = ContractType.Hourly, Id = 1 }, new Employee() { Name = "Mocked", HourlySalary = 10, MonthlySalary = 100, ContractType = ContractType.Monthly, Id = 2 } }); _EmployeeProvider = _automoqer.Resolve <EmployeeProvider>(); }
public async void GetAll_test() { //Given var mocker = new AutoMoqer(); var baseControllerMock = mocker.Create <UsuarioController>(); var faker = AutoFaker.Create(); var response = faker.Generate <List <UsuarioEntity> >(); var responseTask = Task.Factory.StartNew(() => response); var expectResponse = baseControllerMock.Ok(response); var service = mocker.GetMock <IUsuarioQuery>(); service.Setup(r => r.GetAll()).Returns(responseTask).Verifiable(); //When var result = await baseControllerMock.GetAll(); //Then var comparison = new CompareLogic(); service.Verify(mock => mock.GetAll(), Times.Once()); Assert.True(comparison.Compare(result, expectResponse).AreEqual); }
public async void GetToken_test_Unauthorized() { //Given(Preparação) var mocker = new AutoMoqer(); var baseControllerMock = mocker.Create <AuthController>(); var faker = AutoFaker.Create(); var param = new AuthParam() { Login = "******", Senha = "123456" }; var response = faker.Generate <TokenDTO>(); response.Authenticated = false; var responseTask = Task.Factory.StartNew(() => response); var expectResponse = baseControllerMock.Unauthorized(response); var service = mocker.GetMock <IAuthService>(); service.Setup(r => r.GetToken(param)).Returns(responseTask).Verifiable(); //When var result = await baseControllerMock.GetToken(param); //Then var comparison = new CompareLogic(); service.Verify(mock => mock.GetToken(param), Times.Once()); Assert.True(comparison.Compare(result, expectResponse).AreEqual); }
public void SetUp() { _moqer = new AutoMoqer(); _summaries = new ApprenticeshipCourseStandardsResponse { Standards = new List <ApprenticeshipCourse> { new ApprenticeshipCourse { Id = "test-123", Level = 1, Duration = 18, CourseType = ApprenticeshipCourseType.Standard, FundingCap = 10000, Title = "Test course", FundingPeriods = new List <Models.Estimation.FundingPeriod>() }, new ApprenticeshipCourse { Id = "test-789", Level = 1, Duration = 24, CourseType = ApprenticeshipCourseType.Standard, FundingCap = 10000, Title = "Test course", FundingPeriods = new List <Models.Estimation.FundingPeriod>() } } }; _moqer.GetMock <IApiClient>() .Setup(x => x.Get <ApprenticeshipCourseStandardsResponse>(It.IsAny <GetStandardsApiRequest>())) .ReturnsAsync(_summaries); }
public async Task AtualizaStatusPagamento_Test() { var mocker = new AutoMoqer(); var baseCommandMock = mocker.Create <DeliveryExternalContext>(); var deliveryParam = new AutoFaker <DeliveryExternalParam>().Generate(); var result = new AutoFaker <DeliveryResult <Null, string> >().Generate(); var deliveryMock = mocker.GetMock <IProducer <Null, string> >(); deliveryMock.Setup(r => r.ProduceAsync(It.IsAny <string>(), It.IsAny <Message <Null, string> >(), It.IsAny <CancellationToken>())).ReturnsAsync(result).Verifiable(); //When await baseCommandMock.AtualizaStatusPagamento(deliveryParam); //Then deliveryMock.Verify(mock => mock.ProduceAsync(It.IsAny <string>(), It.IsAny <Message <Null, string> >(), It.IsAny <CancellationToken>()), Times.Once()); }
public void TestWriteShouldDisplayResultsToConsole() { _consoleWriter.Write(Id, Age); _mocker.GetMock <IUserService>() .Verify(p => p.GetUserById(Id), Times.Once); _mocker.GetMock <IUserService>() .Verify(p => p.GetUsersByAge(Age), Times.Once); _mocker.GetMock <IUserService>() .Verify(p => p.GetUsersGroupByAge(), Times.Once); }
public async Task SinalizaStatusPagamento_Test() { //Given var mocker = new AutoMoqer(); var baseExternalMock = mocker.Create <DeliveryExternalService>(); var param = new GatewayDTO { IdPedido = Guid.NewGuid(), StatusPagamento = StatusPagamentoEnum.Aprovado }; var response = Task.Factory.StartNew(() => string.Empty); var externalContext = mocker.GetMock <IDeliveryExternalContext>(); externalContext.Setup(e => e.AtualizaStatusPagamento(It.IsAny <DeliveryExternalParam>())).Returns(response).Verifiable(); //When await baseExternalMock.SinalizaStatusPagamento(param); //Then var comparison = new CompareLogic(); externalContext.Verify(mock => mock.AtualizaStatusPagamento(It.IsAny <DeliveryExternalParam>()), Times.Once()); }
public void Calls_Delete_method_of_repository_with_id() { mocker.Resolve <DeploymentManagerController>().Delete("id"); mocker.GetMock <IDeploymentRepository>() .Verify(a => a.Delete("id"), Times.Once()); }
public void StarshipReadOnlyRepository_GetAll_MustReturn2Starships() { // Arrange var starships = new Faker <Domain.Entities.Starship>() .CustomInstantiator(s => new Domain.Entities.Starship { Name = s.Name.LastName(), MGLT = s.Random.Decimal(0.000001M, 1000) } ).Generate(2); mocker.Create <IHttpRestClient>(); var httpRestClientMock = mocker.GetMock <IHttpRestClient>(); var mockResponse = TestHelper.MockWebResponse( new JavaScriptSerializer().Serialize(starships)); httpRestClientMock.Setup(h => h.Get(RESOURCE)).Returns(mockResponse); var httpAlbumFinder = new StarshipReadOnlyRepository(RESOURCE, httpRestClientMock.Object); // Act var result = httpAlbumFinder.GetAll().ToList(); // Assert Assert.Equal(2, result.Count); }
public void ProcessNotification_HasNoNotifications_ShouldNotGetTokens() { //Arrange var mocker = new AutoMoqer(); //Act var sut = mocker.Resolve <NotificationService>(); sut.ProcessNotifications(); //Assert mocker.GetMock <ITokenisedHttpClientFactory>() .Verify(x => x.GetOutlookResourceClient(), Times.Never); mocker.GetMock <ITokenisedHttpClientFactory>() .Verify(x => x.GetGraphResourceClient(), Times.Never); }
public async void Cadastrar_test_InternalServerError() { //Given var mocker = new AutoMoqer(); var baseControllerMock = mocker.Create <UsuarioController>(); var faker = AutoFaker.Create(); var param = new UsuarioParam() { Nome = "", Senha = "" }; var responseTask = new Exception(); var expectResponse = baseControllerMock.StatusCode(500); var service = mocker.GetMock <IUsuarioCommand>(); service.Setup(r => r.Criar(param)).ThrowsAsync(responseTask).Verifiable(); //When var result = await baseControllerMock.Cadastrar(param); //Then var comparison = new CompareLogic(); service.Verify(mock => mock.Criar(param), Times.Once()); Assert.True(((ObjectResult)result).StatusCode == expectResponse.StatusCode); }
public ExplosmDownloaderTests() { var mocker = new AutoMoqer(); // depends on 4125 fixture not having a next link var result4124 = new ComicDownloadResult(Fixture.Load("explosm-4124"), 4124, new Uri("http://explosm.net/comics/4124/")); var result4125 = new ComicDownloadResult(Fixture.Load("explosm-4125"), 4125, new Uri("http://explosm.net/comics/4125/")); mocker.GetMock<IExplosmWebClient>() .Setup(m => m.GetComicHtml(4124)) .Returns(result4124); mocker.GetMock<IExplosmWebClient>() .Setup(m => m.GetComicHtml(4125)) .Returns(result4125); _mocker = mocker; }
public async void GetToken_test_InternalServerError() { //Given(Preparação) var mocker = new AutoMoqer(); var baseControllerMock = mocker.Create <AuthController>(); var faker = AutoFaker.Create(); var param = new AuthParam() { Login = "******", Senha = "123456" }; var response = faker.Generate <TokenDTO>(); response.Authenticated = false; var responseTask = new Exception(); var expectResponse = baseControllerMock.StatusCode(500); var service = mocker.GetMock <IAuthService>(); service.Setup(r => r.GetToken(param)).ThrowsAsync(responseTask).Verifiable(); //When var result = await baseControllerMock.GetToken(param); //Then //var comparison = new CompareLogic(); service.Verify(mock => mock.GetToken(param), Times.Once()); Assert.True(((ObjectResult)result).StatusCode == expectResponse.StatusCode); }
public void Setup() { Mocker = new AutoMoqer(); BackingStore = Mocker.GetMock <IBackingStore>(); Feature = new Feature(BackingStore.Object, FeatureName); }
public void SetUp() { _moqer = new AutoMoqer(); _moqer.GetMock <IPayrollDateService>() .Setup(svc => svc.GetPayrollDate(It.IsAny <string>(), It.IsAny <short>())) .Returns(DateTime.Today); }
public void TestExecuteShoulPrintLine(string line) { _command.Execute(InvoiceId); _mocker.GetMock <IPrinter>() .Verify(p => p.WriteLine(line), Times.Once); }
public CalculadoraJurosHandlerTests() { var autoMoqer = new AutoMoqer(); handler = autoMoqer.Create <CalculadoraJurosHandler>(); jurosClient = autoMoqer.GetMock <IJurosClient>(); }
public void TestCloseInvalidConnection() { var mocker = new AutoMoqer(); var mockConnectionFactory = mocker.GetMock<RabbitMQ.Client.ConnectionFactory>(); var mockConnection1 = new Mock<RabbitMQ.Client.IConnection>(); var mockConnection2 = new Mock<RabbitMQ.Client.IConnection>(); mockConnectionFactory.Setup(c => c.CreateConnection()).ReturnsInOrder(mockConnection1.Object, mockConnection2.Object); // simulate a dead connection mockConnection1.Setup(c => c.IsOpen).Returns(false); var connectionFactory = new SingleConnectionFactory(mockConnectionFactory.Object); var connection = connectionFactory.CreateConnection(); // the dead connection should be discarded connection.CreateChannel(false); mockConnectionFactory.Verify(c => c.CreateConnection(), Times.Exactly(2)); mockConnection2.Verify(c => c.CreateModel(), Times.Exactly(1)); connectionFactory.Dispose(); mockConnection2.Verify(c => c.Close(), Times.Exactly(1)); }
public async void SituacaoDrone_test() { //Given var mocker = new AutoMoqer(); var baseControllerMock = mocker.Create <DroneController>(); var faker = AutoFaker.Create(); var response = faker.Generate <List <ConsultaDronePedidoDTO> >(); var expectResponse = baseControllerMock.Ok(response); var service = mocker.GetMock <IDroneQuery>(); service.Setup(r => r.ConsultaDrone()).ReturnsAsync(response).Verifiable(); //When var result = await baseControllerMock.SituacaoDrone(); //Then var comparison = new CompareLogic(); service.Verify(mock => mock.ConsultaDrone(), Times.Once()); Assert.True(comparison.Compare(result, expectResponse).AreEqual); }
public void DeveRetornarCadastroHanlderValido() { // Arrange // Criando o faker do objeto do command para salvar uma nova escola createSchool = CreateSchoolCommandFaker.Gerar(); var command = createSchool.Generate(); // Criando o mock do handler var mocker = new AutoMoqer(); mocker.Create <SchoolCommandHandler>(); // Resolvendo as dependencias do construtor var schoolCommandHandler = mocker.Resolve <SchoolCommandHandler>(); // Mockando o respositorio var repository = mocker.GetMock <ISchoolRepository>(); // Act // Chamando a rotina para cadastrar uma nova escola mockada schoolCommandHandler.Handle(command); // Asset // Verificando se deu certo a inserção chamando o repositorio repository.Verify(r => r.Add(It.IsAny <Domain.Entities.School>()), Times.Exactly(1)); }
public FizzBuzzTests() { var mocker = new AutoMoqer(); _testObject = mocker.Create <FizzBuzzController>(); _logger = mocker.GetMock <IGameLogger>(); }
public async void Cadastrar_test() { //Given var mocker = new AutoMoqer(); var baseControllerMock = mocker.Create <UsuarioController>(); var faker = AutoFaker.Create(); var param = faker.Generate <UsuarioParam>(); var response = string.Empty; var responseTask = Task.Factory.StartNew(() => response); var expectResponse = baseControllerMock.Ok("Usuário cadastrado com sucesso!"); var service = mocker.GetMock <IUsuarioCommand>(); service.Setup(r => r.Criar(param)).Returns(responseTask).Verifiable(); //When var result = await baseControllerMock.Cadastrar(param); //Then var comparison = new CompareLogic(); service.Verify(mock => mock.Criar(param), Times.Once()); Assert.True(comparison.Compare(result, expectResponse).AreEqual); }
public void SetUp() { _invoice = new Invoice(); _mocker = new AutoMoqer(); _mocker.GetMock <IDatabase>() .Setup(p => p.GetInvoice(InvoiceId)) .Returns(_invoice); _mocker.GetMock <IIdentityService>() .Setup(p => p.GetUserName()) .Returns(UserName); _command = _mocker.Create <PrintInvoiceCommand>(); }
public void TestMethod1() { // Arrange var mocker = new AutoMoqer(); var service = mocker.Create <UserController>(); var controllerMock = mocker.GetMock <IPublicEntityController <User> >(); var user = new User() { Email = "*****@*****.**" }; var queryResponse = new QueryResponse() { errorCode = "NoErrorCode", errorMessage = "NoErrorMessage", success = false }; controllerMock.Setup(f => f.Single(It.IsAny <string>(), out queryResponse)).Returns(user); // Act var response = (UserResponse)service.Any(new UserIdRequest { Id = "12345" }); // Assert Assert.That(response, Is.Not.Null); Assert.That(response.Result.Email, Is.EqualTo("*****@*****.**")); }
public void SetUp() { _moqer = new AutoMoqer(); _moqer.GetMock <IApprenticeshipCourseDataService>() .Setup(svc => svc.Store(It.IsAny <ApprenticeshipCourse>())) .Returns(Task.CompletedTask); }
public void EpisodeAction_should_return_success_for_Library() { //Setup var expectedUrl = String.Format("{0}{1}", Url.ShowEpisodeLibrary, Constants.ApiKey); var expectedJson = "{\"username\": \"username\",\"password\": \"sha1hash\",\"tvdb_id\": 80379,\"imdb_id\": \"tt0898266\",\"title\": \"The Big Bang Theory\",\"year\": 2007,\"episodes\": [{\"season\": 1,\"episode\": 1}]}"; var jsonResult = "{\"status\":\"success\",\"message\":\"1 episodes added to your library\"}"; var mocker = new AutoMoqer(); mocker.GetMock<HttpProvider>().Setup(s => s.DownloadString(expectedUrl, It.Is<string>(e => e.Replace(" ", "").Replace("\r\n", "").Replace("\t", "") == expectedJson.Replace(" ", "")))).Returns(jsonResult); //Act var result = mocker.Resolve<ShowProvider>().EpisodeAction( Constants.ApiKey, "username", "sha1hash", ActionType.Library, new List<SeasonEpisodePair> { new SeasonEpisodePair { Season = 1, Episode = 1 } }, 80379, "tt0898266", "The Big Bang Theory", 2007 ); //Assert result.Should().NotBeNull(); result.Status.Should().Be(ResultStatusType.Success); result.Message.Should().Be("1 episodes added to your library"); }
public void Init() { mocker = new AutoMoqer(); mocker.GetMock <IFileSystem>() .Setup(a => a.DirectoryExists(It.IsAny <string>())) .Returns(false); }