Ejemplo n.º 1
0
 public void VoidActionShouldNotThrowExceptionWithCorrectResponse()
 {
     MyController <MvcController>
     .Instance()
     .Calling(c => c.CustomResponseAction())
     .ShouldHave()
     .HttpResponse(response => response
                   .WithContentType(ContentType.ApplicationJson)
                   .AndAlso()
                   .WithStatusCode(HttpStatusCode.InternalServerError)
                   .AndAlso()
                   .ContainingHeader("TestHeader", "TestHeaderValue")
                   .ContainingCookie("TestCookie", "TestCookieValue", new CookieOptions
     {
         HttpOnly = true,
         Secure   = true,
         Domain   = "testdomain.com",
         Expires  = new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
         Path     = "/"
     }))
     .AndAlso()
     .ShouldReturn()
     .Ok();
 }
Ejemplo n.º 2
0
 public void AddProduct_WithValidData_ShouldReturnProductShowReceiptViewModel()
 => MyController <ReceiptController>
 .Instance()
 .WithDependencies(
     this.receiptService,
     this.productService,
     this.userManager)
 .WithUser("testUser")
 .WithHttpRequest(x =>
                  x.WithLocation("/Receipt/Add")
                  .AndAlso()
                  .WithMethod(HttpMethod.Post))
 .Calling(x => x.AddProduct(new ReceiptAddProductInputModel()
 {
     Id       = this.dbContext.Products.FirstOrDefault().Id,
     Quantity = 4
 }))
 .ShouldHave()
 .ValidModelState()
 .AndAlso()
 .ShouldReturn()
 .ResultOfType <ActionResult <ProductShowReceiptViewModel> >()
 .AndAlso()
 .ShouldPassForThe <ActionResult <ProductShowReceiptViewModel> >(x => x.Value.ProductName == "testProduct");
        public void WithJsonSerializerSettingsShouldThrowExceptionWithActionSettings()
        {
            var jsonSettings = new JsonSerializerSettings
            {
                CheckAdditionalContent = true,
                NullValueHandling      = NullValueHandling.Ignore
            };

            Test.AssertException <JsonResultAssertionException>(
                () =>
            {
                MyController <MvcController>
                .Instance()
                .Calling(c => c.JsonWithSpecificSettingsAction(jsonSettings))
                .ShouldReturn()
                .Json(json => json
                      .WithJsonSerializerSettings(settings =>
                {
                    settings.WithAdditionalContentChecking(false);
                    settings.WithNullValueHandling(NullValueHandling.Ignore);
                }));
            },
                "When calling JsonWithSpecificSettingsAction action in MvcController expected JSON result serializer settings to have disabled checking for additional content, but in fact it was enabled.");
        }
Ejemplo n.º 4
0
 public void WithResponseCookieBuilderShouldNotThrowExceptionWithCorrectCookie()
 {
     MyController <MvcController>
     .Instance()
     .Calling(c => c.CustomVoidResponseAction())
     .ShouldHave()
     .HttpResponse(response => response
                   .ContainingCookie(cookie => cookie
                                     .WithName("TestCookie")
                                     .AndAlso()
                                     .WithValue("TestCookieValue")
                                     .AndAlso()
                                     .WithSecurity(true)
                                     .AndAlso()
                                     .WithHttpOnly(true)
                                     .AndAlso()
                                     .WithMaxAge(null)
                                     .AndAlso()
                                     .WithDomain("testdomain.com")
                                     .AndAlso()
                                     .WithExpiration(new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc)))
                                     .AndAlso()
                                     .WithPath("/")));
 }
 public void WithCacheOptionsShouldSetCorrectValues()
 {
     MyController <MemoryCacheController>
     .Instance()
     .WithMemoryCache(memoryCache => memoryCache
                      .WithEntry("FullEntry", "FullEntryValid", new MemoryCacheEntryOptions
     {
         AbsoluteExpiration = new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
         AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1),
         Priority          = CacheItemPriority.High,
         SlidingExpiration = TimeSpan.FromMinutes(5)
     }))
     .Calling(c => c.FullMemoryCacheAction(From.Services <IMemoryCache>()))
     .ShouldReturn()
     .Ok(ok => ok
         .WithModel(new CacheEntryMock("FullEntry")
     {
         Value = "FullEntryValid",
         AbsoluteExpiration = new DateTimeOffset(new DateTime(2016, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
         AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1),
         Priority          = CacheItemPriority.High,
         SlidingExpiration = TimeSpan.FromMinutes(5)
     }));
 }
        public void ContainingEntryWithOptionsShouldThrowExceptionWithIncorrectSlidingExpiration()
        {
            var cacheValue = new byte[] { 127, 127, 127 };

            Test.AssertException <DataProviderAssertionException>(
                () =>
            {
                MyController <MvcController>
                .Instance()
                .Calling(c => c.AddDistributedCacheAction())
                .ShouldHave()
                .DistributedCache(cache => cache
                                  .ContainingEntry("test", cacheValue, new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = new DateTimeOffset(new DateTime(2020, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1),
                    SlidingExpiration = TimeSpan.FromMinutes(3)
                }))
                .AndAlso()
                .ShouldReturn()
                .Ok();
            },
                "When calling AddDistributedCacheAction action in MvcController expected distributed cache to have entry with the given options, but in fact they were different.");
        }
        public void WithMultipleLicensesNoExceptionShouldBeThrown()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithTestConfiguration(config =>
            {
                config.AddJsonFile("multilicenseconfig.json");
            });

            LicenseValidator.ClearLicenseDetails();
            TestCounter.SetLicenseData(null, DateTime.MinValue, "MyTested.AspNetCore.Mvc.Tests");

            Task.Run(async() =>
            {
                var tasks = new List <Task>();

                for (int i = 0; i < 500; i++)
                {
                    tasks.Add(Task.Run(() =>
                    {
                        MyController <MvcController>
                        .Instance()
                        .Calling(c => c.OkResultAction())
                        .ShouldReturn()
                        .Ok();
                    }));
                }

                await Task.WhenAll(tasks);
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            MyApplication.StartsFrom <DefaultStartup>();
        }
Ejemplo n.º 8
0
        public void ClearingSessionShouldReturnCorrectEmptyCollectionOfKeys()
        {
            this.SetDefaultSession();

            IDictionary <string, string> entries = new Dictionary <string, string>
            {
                { "testKey1", "testValue1" },
                { "testKey2", "testValue2" }
            };

            MyController <MvcController>
            .Instance()
            .WithSession(session =>
            {
                session.WithEntries(entries);
            })
            .WithoutSession()
            .Calling(c => c.GetSessionKeysCount())
            .ShouldReturn()
            .Ok(ok => ok
                .WithModel(0));

            MyApplication.StartsFrom <DefaultStartup>();
        }
        public void WithoutSetReturnsCorrectDataWhenWholeRangeIsRemoved()
        {
            MyApplication
            .StartsFrom <TestStartup>()
            .WithServices(services => services.AddDbContext <CustomDbContext>());

            var models = new List <CustomModel> {
                new CustomModel
                {
                    Id   = 1,
                    Name = "Test"
                }
            };

            MyController <DbContextController>
            .Instance()
            .WithData(models)
            .WithoutData(data =>
                         data.WithoutSet <CustomModel>(
                             cm => cm.RemoveRange(models)))
            .Calling(c => c.GetAll())
            .ShouldReturn()
            .NotFound();
        }
        public void WithoutDataByProvidingNonExistingModelAndKeyInBuilderShouldRemoveTheCorrectObject()
        {
            MyApplication
            .StartsFrom <TestStartup>()
            .WithServices(services => services.AddDbContext <CustomDbContext>());

            var model = new CustomModel
            {
                Id   = 1,
                Name = "Test"
            };

            var keyToRemove = int.MaxValue;

            MyController <DbContextController>
            .Instance()
            .WithData(model)
            .WithoutData(data => data.WithoutEntityByKey <CustomModel>(keyToRemove))
            .Calling(c => c.Get(model.Id))
            .ShouldReturn()
            .Ok(ok => ok
                .WithModelOfType <CustomModel>()
                .Passing(cm => cm.Name.Equals(model.Name)));
        }
Ejemplo n.º 11
0
 public void CreateGetShouldReturnRightModelsAndRightCountriesCount()
 => MyController <PredictionsController>
 .Instance()
 .WithUser()
 .WithData(data => data
           .WithEntities(entity => entity.AddRange(
                             new Country {
     Name = "England"
 },
                             new Country {
     Name = "Finland"
 },
                             new Country {
     Name = "Russia"
 })))
 .Calling(x => x.Create())
 .ShouldReturn()
 .View(viewResult => viewResult
       .WithModelOfType <CreatePredictionInputViewModel>()
       .Passing(x =>
 {
     Assert.Equal(3, x.Countries.Count());
     Assert.IsType <List <CountriesDropDownViewModel> >(x.Countries);
 }));
        public void WithControllerContextSetupShouldSetCorrectControllerContextForPocoController()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            MyController <FullPocoController>
            .Instance()
            .WithControllerContext(controllerContext =>
            {
                controllerContext.RouteData.Values.Add("testkey", "testvalue");
            })
            .ShouldPassForThe <FullPocoController>(controller =>
            {
                Assert.NotNull(controller);
                Assert.NotNull(controller.CustomControllerContext);
                Assert.True(controller.CustomControllerContext.RouteData.Values.ContainsKey("testkey"));
            });

            MyApplication.StartsFrom <DefaultStartup>();
        }
        public void WithRequestAsObjectShouldWorkWithSetRequestActionForPocoController()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            var httpContext = new HttpContextMock();

            httpContext.Request.Form = new FormCollection(new Dictionary <string, StringValues> {
                ["Test"] = "TestValue"
            });

            MyController <FullPocoController>
            .Instance()
            .WithHttpRequest(httpContext.Request)
            .Calling(c => c.WithRequest())
            .ShouldReturn()
            .Ok();

            MyApplication.StartsFrom <DefaultStartup>();
        }
Ejemplo n.º 14
0
        public void Result_WithValidISIN_ShouldRedirectToDetailsView(string searchTerm)
        {
            var shareClass = ShareClassTestData
                             .GenerateShareClasses()
                             .FirstOrDefault(sc => sc.ScIsinCode == searchTerm);

            var date = DateTime.Today.ToString(GlobalConstants.RequiredWebDateTimeFormat);

            var routeValues = new
            {
                area = EndpointsConstants.ShareClassArea,
                id   = shareClass.ScId,
                date = date
            };

            MyController <SearchController>
            .Instance()
            .WithData(data => data.WithEntities <ApplicationDbContext>(shareClass))
            .Calling(c => c.Result(searchTerm))
            .ShouldReturn()
            .RedirectToRoute(
                EndpointsConstants.RouteDetails + EndpointsConstants.ShareClassArea,
                routeValues);
        }
        public void WithIdShouldSetIdCorrectly()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithServices(services =>
            {
                services.AddMemoryCache();
                services.AddDistributedMemoryCache();
                services.AddSession();
            });

            MyController <MvcController>
            .Instance()
            .WithSession(session => session
                         .WithId("TestId")
                         .AndAlso()
                         .WithEntry("HasId", "HasIdValue"))
            .Calling(c => c.FullSessionAction())
            .ShouldReturn()
            .Ok(ok => ok
                .WithModel("TestId"));

            MyApplication.StartsFrom <DefaultStartup>();
        }
Ejemplo n.º 16
0
 public void CreateShouldReturnCreatedResultWhenValidModelState(
     string country,
     string state,
     string city,
     string description,
     string postalCode,
     string phoneNumber)
 => MyController <AddressesController>
 .Instance(instance => instance
           .WithUser())
 .Calling(c => c.Create(new AddressesRequestModel
 {
     Country     = country,
     State       = state,
     City        = city,
     Description = description,
     PostalCode  = postalCode,
     PhoneNumber = phoneNumber
 }))
 .ShouldHave()
 .ValidModelState()
 .AndAlso()
 .ShouldReturn()
 .Created();
Ejemplo n.º 17
0
 public void HomeControllerShouldReturnView()
 => MyController <HomeController>
 .Instance()
 .Calling(c => c.Index())
 .ShouldReturn()
 .View();
 public void DetailsShouldReturnNotFoundWhenInvalidArticleId()
 => MyController <ArticlesController>
 .Instance()
 .Calling(c => c.Details(int.MaxValue))
 .ShouldReturn()
 .NotFound();
Ejemplo n.º 19
0
        public void IHttpContextAccessorShouldWorkCorrectlyAsynchronously()
        {
            MyApplication
            .StartsFrom <DefaultStartup>()
            .WithServices(services =>
            {
                services.AddHttpContextAccessor();
            });

            Task
            .Run(async() =>
            {
                HttpContext firstContextAsync  = null;
                HttpContext secondContextAsync = null;
                HttpContext thirdContextAsync  = null;
                HttpContext fourthContextAsync = null;
                HttpContext fifthContextAsync  = null;

                var tasks = new List <Task>
                {
                    Task.Run(() =>
                    {
                        MyController <HttpContextController>
                        .Instance()
                        .ShouldPassForThe <HttpContextController>(controller =>
                        {
                            firstContextAsync = controller.Context;
                        });
                    }),
                    Task.Run(() =>
                    {
                        MyController <HttpContextController>
                        .Instance()
                        .ShouldPassForThe <HttpContextController>(controller =>
                        {
                            secondContextAsync = controller.Context;
                        });
                    }),
                    Task.Run(() =>
                    {
                        MyController <HttpContextController>
                        .Instance()
                        .ShouldPassForThe <HttpContextController>(controller =>
                        {
                            thirdContextAsync = controller.Context;
                        });
                    }),
                    Task.Run(() =>
                    {
                        MyController <HttpContextController>
                        .Instance()
                        .ShouldPassForThe <HttpContextController>(controller =>
                        {
                            fourthContextAsync = controller.Context;
                        });
                    }),
                    Task.Run(() =>
                    {
                        MyController <HttpContextController>
                        .Instance()
                        .ShouldPassForThe <HttpContextController>(controller =>
                        {
                            fifthContextAsync = controller.Context;
                        });
                    })
                };

                await Task.WhenAll(tasks);

                Assert.NotNull(firstContextAsync);
                Assert.NotNull(secondContextAsync);
                Assert.NotNull(thirdContextAsync);
                Assert.NotNull(fourthContextAsync);
                Assert.NotNull(fifthContextAsync);
                Assert.IsAssignableFrom <HttpContextMock>(firstContextAsync);
                Assert.IsAssignableFrom <HttpContextMock>(secondContextAsync);
                Assert.IsAssignableFrom <HttpContextMock>(thirdContextAsync);
                Assert.IsAssignableFrom <HttpContextMock>(fourthContextAsync);
                Assert.IsAssignableFrom <HttpContextMock>(fifthContextAsync);
                Assert.NotSame(firstContextAsync, secondContextAsync);
                Assert.NotSame(firstContextAsync, thirdContextAsync);
                Assert.NotSame(secondContextAsync, thirdContextAsync);
                Assert.NotSame(thirdContextAsync, fourthContextAsync);
                Assert.NotSame(fourthContextAsync, fifthContextAsync);
                Assert.NotSame(thirdContextAsync, fifthContextAsync);
            })
            .ConfigureAwait(false)
            .GetAwaiter()
            .GetResult();

            MyApplication.StartsFrom <DefaultStartup>();
        }
 public void EditGetShouldReturnNotFoundWhenInvalidId()
 => MyController <ArticlesController>
 .Instance()
 .Calling(c => c.Edit(With.Any <int>()))
 .ShouldReturn()
 .NotFound();
 public void ConfirmDeleteShouldReturnNotFoundWhenInvalidId()
 => MyController <ArticlesController>
 .Instance()
 .Calling(c => c.ConfirmDelete(With.Any <int>()))
 .ShouldReturn()
 .NotFound();
Ejemplo n.º 22
0
 public void IndexShouldReturnView()
 => MyController <ContactsController>
 .Instance()
 .Calling(c => c.Index())
 .ShouldReturn()
 .View();
Ejemplo n.º 23
0
 public void ErrorShouldReturnErrorView()
 => MyController <HomeController>
 .Instance()
 .Calling(c => c.Error())
 .ShouldReturn()
 .View(v => v.WithModelOfType(typeof(ErrorViewModel)));
Ejemplo n.º 24
0
 public void PrivacyShouldReturnView()
 => MyController <HomeController>
 .Instance()
 .Calling(c => c.Privacy())
 .ShouldReturn()
 .View();
Ejemplo n.º 25
0
 public void UserControllerActions_ShouldBeAllowedOnlyForAuthorizedUsers() =>
 MyController <UserController>
 .Instance()
 .ShouldHave()
 .Attributes(attributes => attributes.RestrictingForAuthorizedRequests());
        public void WithEntitiesShouldSetupDbContext()
        {
            MyApplication
            .StartsFrom <TestStartup>()
            .WithServices(services =>
            {
                services.AddDbContext <CustomDbContext>(options =>
                                                        options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=TestDb;Trusted_Connection=True;MultipleActiveResultSets=true;Connect Timeout=30;"));
            });

            MyController <DbContextController>
            .Instance()
            .WithData(data => data
                      .WithEntities <CustomDbContext>(db => db
                                                      .Models.Add(new CustomModel
            {
                Id = 1, Name = "Test"
            })))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .Ok(ok => ok
                .WithModelOfType <CustomModel>()
                .Passing(m => m.Name == "Test"));

            MyController <DbContextController>
            .Instance()
            .WithData(data => data
                      .WithEntities(db => db.Add(new CustomModel
            {
                Id   = 1,
                Name = "Test"
            })))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .Ok(ok => ok
                .WithModelOfType <CustomModel>()
                .Passing(m => m.Name == "Test"));

            MyController <DbContextController>
            .Instance()
            .WithData(data => data
                      .WithEntities(
                          new CustomModel
            {
                Id   = 1,
                Name = "Test 1"
            },
                          new CustomModel
            {
                Id   = 2,
                Name = "Test 2"
            }))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .Ok(ok => ok
                .WithModelOfType <CustomModel>()
                .Passing(m => m.Name == "Test 1"));

            MyController <DbContextController>
            .Instance()
            .WithData(data => data
                      .WithEntities <CustomDbContext>(db => db
                                                      .Models.Add(new CustomModel
            {
                Id   = 2,
                Name = "Test"
            })))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .NotFound();

            MyController <DbContextController>
            .Instance()
            .WithData(data => data
                      .WithEntities <CustomDbContext>(
                          new CustomModel
            {
                Id   = 2,
                Name = "Test 2"
            },
                          new CustomModel
            {
                Id   = 3,
                Name = "Test 3"
            }))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .NotFound();

            MyController <DbContextController>
            .Instance()
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .NotFound();

            MyApplication.StartsFrom <DefaultStartup>();
        }
        public void WithSetShouldSetupMultipleDbContext()
        {
            MyApplication
            .StartsFrom <TestStartup>()
            .WithServices(services =>
            {
                services.AddDbContext <CustomDbContext>(options =>
                                                        options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=TestDb;Trusted_Connection=True;MultipleActiveResultSets=true;Connect Timeout=30;"));

                services.AddDbContext <AnotherDbContext>(options =>
                                                         options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=AnotherTestDb;Trusted_Connection=True;MultipleActiveResultSets=true;Connect Timeout=30;"));
            });

            var modelName        = "Test";
            var anotherModelName = "Another Test";

            MyController <MultipleDbContextController>
            .Instance()
            .WithData(data => data
                      .WithSet <CustomDbContext, CustomModel>(set => set
                                                              .Add(new CustomModel
            {
                Id   = 1,
                Name = modelName
            }))
                      .WithSet <AnotherDbContext, AnotherModel>(set => set
                                                                .Add(new AnotherModel
            {
                Id       = 1,
                FullName = anotherModelName
            })))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .Ok(ok => ok
                .WithModel(new
            {
                Model        = modelName,
                AnotherModel = anotherModelName
            }));

            MyController <MultipleDbContextController>
            .Instance()
            .WithData(data => data
                      .WithSet <CustomDbContext, CustomModel>(set => set
                                                              .Add(new CustomModel
            {
                Id   = 2,
                Name = modelName
            })))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .NotFound();

            MyController <MultipleDbContextController>
            .Instance()
            .WithData(data => data
                      .WithSet <AnotherDbContext, AnotherModel>(set => set
                                                                .Add(new AnotherModel
            {
                Id       = 2,
                FullName = anotherModelName
            })))
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .NotFound();

            MyController <DbContextController>
            .Instance()
            .Calling(c => c.Find(1))
            .ShouldReturn()
            .NotFound();

            MyApplication.StartsFrom <DefaultStartup>();
        }
Ejemplo n.º 28
0
        public void WithStatusCodeShouldNotThrowExceptionWithCorrectStatusCode()
        {
            MyApplication
            .StartsFrom <TestStartup>()
            .WithServices(services =>
            {
                services.AddActionContextAccessor();
            });
            var context = new PCHUBDbContext();

            var mock = new Mock <ILogger <HomeController> >();
            ILogger <HomeController> logger = mock.Object;

            var model = new IndexViewModel();

            //or use this short equivalent
            logger = Mock.Of <ILogger <HomeController> >();

            var service = new HomeService(context);

            var mapperConfiguration = new MapperConfiguration(config =>
            {
                config.AddProfile <AdminProfile>();
                config.AddProfile <ProductsProfile>();
                config.AddProfile <UsersProfile>();
                config.AddProfile <ApiProfile>();
            });

            var mapper = new Mapper(mapperConfiguration);


            MyController <HomeController>
            .Instance(
                instance => instance
                .WithDependencies(
                    logger,
                    service,
                    mapper
                    ))
            .Calling(c => c.Index())
            .ShouldReturn()
            .View(view => view.WithModelOfType <IndexViewModel>().Passing(model => model.Boxes.Any()));

            MyRouting
            .Configuration()
            .ShouldMap(request => request
                       .WithLocation("/Home/Index")
                       .WithMethod(HttpMethod.Get))
            .To <HomeController>(c => c.Index());

            MyController <HomeController>
            .Instance(instance => instance
                      .WithDependencies(
                          logger,
                          service,
                          mapper
                          )
                      .WithUser(user => user
                                .WithUsername("obelix")))
            .Calling(c => c.Index())
            .ShouldReturn()
            .View(view => view.WithModelOfType <IndexViewModel>().Passing(model => model.Categories.Any()));

            MyRouting
            .Configuration()
            .ShouldMap(request => request
                       .WithLocation("/Home/Error")
                       .WithMethod(HttpMethod.Get))
            .To <HomeController>(c => c.Error());

            MyRouting
            .Configuration()
            .ShouldMap(request => request
                       .WithLocation("/Home/Privacy")
                       .WithMethod(HttpMethod.Get))
            .To <HomeController>(c => c.Privacy());


            // Task<ActionResult<List<ApiProductHistoryViewModel>>> ReviewedProducts()

            MyController <HomeController>
            .Instance(instance => instance
                      .WithDependencies(
                          logger,
                          service,
                          mapper
                          )
                      .WithUser(user => user
                                .WithUsername("obelix")))
            .Calling(c => c.ReviewedProducts())
            .ShouldReturn()
            .ActionResult(result => result.Object(obj => obj.WithModelOfType <List <ApiProductHistoryViewModel> >().Passing(x => x.Any())));
        }
Ejemplo n.º 29
0
 public void ErrorReturnsView()
 => MyController <HomeController>
 .Instance()
 .Calling(c => c.Error())
 .ShouldReturn()
 .View();
        public void WithHttpRequestShouldWorkCorrectlyWithDefaultValues()
        {
            var stream         = new MemoryStream();
            var requestCookies = new CustomRequestCookieCollection
            {
                ["MyRequestCookie"]      = "MyRequestCookieValue",
                ["AnotherRequestCookie"] = "AnotherRequestCookieValue"
            };

            var files = new[]
            {
                new FormFile(stream, 0, 0, "FirstFile", "FirstFileName"),
                new FormFile(stream, 0, 0, "SecondFile", "SecondFileName"),
            };

            MyController <MvcController>
            .Instance()
            .WithHttpRequest(request => request
                             .WithBody(stream)
                             .WithContentLength(1)
                             .WithContentType(ContentType.ApplicationJson)
                             .AndAlso()
                             .WithCookie("MyCookie", "MyCookieValue")
                             .WithCookies(new Dictionary <string, string>
            {
                { "MyDictCookie", "MyDictCookieValue" },
                { "AnotherDictCookie", "AnotherDictCookieValue" }
            })
                             .WithCookies(requestCookies)
                             .WithCookies(new
            {
                ObjectCookie        = "ObjectCookieValue",
                AnotherObjectCookie = "AnotherObjectCookieValue"
            })
                             .AndAlso()
                             .WithFormField("Field", "FieldValue")
                             .WithFormField("MultiField", "FirstFieldValue", "SecondFieldValue")
                             .WithFormFields(new Dictionary <string, IEnumerable <string> >
            {
                { "MyDictField", new[] { "MyDictFieldValue" } },
                { "AnotherDictField", new[] { "AnotherDictFieldValue" } }
            })
                             .AndAlso()
                             .WithFormFiles(files)
                             .AndAlso()
                             .WithHeader("MyHeader", "MyHeaderValue")
                             .WithHeader("MultiHeader", "FirstHeaderValue", "SecondHeaderValue")
                             .WithHeaders(new Dictionary <string, IEnumerable <string> >
            {
                { "MyDictHeader", new[] { "MyDictHeaderValue" } },
                { "AnotherDictHeader", new[] { "AnotherDictHeaderValue" } }
            })
                             .AndAlso()
                             .WithHost("mytestedasp.net")
                             .WithMethod("POST")
                             .WithPath("/all")
                             .WithPathBase("/api")
                             .WithProtocol("protocol")
                             .WithQueryString("?key=value&another=yetanother")
                             .WithHttps())
            .ShouldPassForThe <HttpRequest>(builtRequest =>
            {
                Assert.Same(stream, builtRequest.Body);
                Assert.Equal(1, builtRequest.ContentLength);
                Assert.Same(ContentType.ApplicationJson, builtRequest.ContentType);

                Assert.Equal(7, builtRequest.Cookies.Count);
                Assert.Equal("MyCookieValue", builtRequest.Cookies["MyCookie"]);
                Assert.Equal("MyDictCookieValue", builtRequest.Cookies["MyDictCookie"]);
                Assert.Equal("AnotherDictCookieValue", builtRequest.Cookies["AnotherDictCookie"]);
                Assert.Equal("MyRequestCookieValue", builtRequest.Cookies["MyRequestCookie"]);
                Assert.Equal("AnotherRequestCookieValue", builtRequest.Cookies["AnotherRequestCookie"]);
                Assert.Equal("ObjectCookieValue", builtRequest.Cookies["ObjectCookie"]);
                Assert.Equal("AnotherObjectCookieValue", builtRequest.Cookies["AnotherObjectCookie"]);

                Assert.Equal(4, builtRequest.Form.Count);
                Assert.Equal("FieldValue", builtRequest.Form["Field"]);
                Assert.Equal("FirstFieldValue,SecondFieldValue", builtRequest.Form["MultiField"]);
                Assert.Equal("MyDictFieldValue", builtRequest.Form["MyDictField"]);
                Assert.Equal("AnotherDictFieldValue", builtRequest.Form["AnotherDictField"]);

                Assert.Equal(2, builtRequest.Form.Files.Count);
                Assert.Same(files[0], builtRequest.Form.Files[0]);
                Assert.Same(files[1], builtRequest.Form.Files[1]);

                Assert.Equal(8, builtRequest.Headers.Count);
                Assert.Equal("MyHeaderValue", builtRequest.Headers["MyHeader"]);
                Assert.Equal("FirstHeaderValue,SecondHeaderValue", builtRequest.Headers["MultiHeader"]);
                Assert.Equal("MyDictHeaderValue", builtRequest.Headers["MyDictHeader"]);
                Assert.Equal("AnotherDictHeaderValue", builtRequest.Headers["AnotherDictHeader"]);

                Assert.Equal("mytestedasp.net", builtRequest.Host.Value);
                Assert.Equal("POST", builtRequest.Method);
                Assert.Equal("/all", builtRequest.Path);
                Assert.Equal("/api", builtRequest.PathBase);
                Assert.Equal("protocol", builtRequest.Protocol);
                Assert.Equal("?key=value&another=yetanother", builtRequest.QueryString.Value);
                Assert.Equal("https", builtRequest.Scheme);

                Assert.Equal(2, builtRequest.Query.Count);
                Assert.Equal("value", builtRequest.Query["key"]);
                Assert.Equal("yetanother", builtRequest.Query["another"]);
            });
        }