I use NUnitAdapter. I have unit test for my update method:
[Test]
public void UpdateBuisness()
{
var buis = new Buisness()
{
Name = "a",
Id = 4,
Enabled = true
};
_buisnessRepository.Insert(buis);
buis.Name = "b";
_buisnessRepository.Update(buis);
Assert.AreEqual(buis.Name, _buisnesses.Last().Name);
}
Update method:
public void Update(Buisness entity)
{
_context.Entry(entity).State = EntityState.Modified;
}
And I get error:
This is weird, because for my co-workers all works.
My mock:
var mockBuisnessesDbSet = new Mock<DbSet<Buisness>>();
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.Provider)
.Returns(new TestDbAsyncQueryProvider<Buisness>(_buisnesses.Provider));
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.Expression).Returns(_buisnesses.Expression);
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.ElementType).Returns(_buisnesses.ElementType);
mockBuisnessesDbSet.As<IDbAsyncEnumerable<Buisness>>()
.Setup(m => m.GetAsyncEnumerator())
.Returns(new TestDbAsyncEnumerator<Buisness>(_buisnesses.GetEnumerator()));
mockBuisnessesDbSet.As<IQueryable<Buisness>>().Setup(m => m.GetEnumerator()).Returns(_buisnesses.GetEnumerator());
mockBuisnessesDbSet.Setup(x => x.Add(It.IsAny<Buisness>()))
.Callback((Buisness bis) => _buisnesses = _buisnesses.Concat(new[] { bis }));
mockBuisnessesDbSet.Setup(x => x.Remove(It.IsAny<Buisness>()))
.Callback((Buisness bis) => _buisnesses = _buisnesses.Where(x => x.Id != bis.Id));
_mockContex = new Mock<ApplicationDbContext>() { CallBase = true };
_mockContex.Setup(x => x.Buisnesses).Returns(mockBuisnessesDbSet.Object);
_buisnessRepository = new BuisnessRepository(_mockContex.Object);
I have no idea what is causing this.
Related
I'm using PS 1.6.1.16 and I'm wondering if there is a way to display "additional" or "different" content on product.tpl if the product type is "Virtual" (set in BO).
Additionally, is there a way to create a category page for all these "Virtual" products?
Thanks in advance.
In tpl condition is :
{if $product->is_virtual} IS VIRTUAL PRODUCT {else} NO VIRTUAL PRODUCT {/if}
To have a dedicated page is different, here is an example of product override to put in ROOT/override/controllers/front/ProductController.php which allows you to load a new TPL for virtual products. It is therefore necessary in the theme to add a product_virtual.tpl file
<?php
class ProductController extends ProductControllerCore
{
public function initContent()
{
parent::initContent();
if (!$this->errors) {
if (Pack::isPack((int)$this->product->id) && !Pack::isInStock((int)$this->product->id)) {
$this->product->quantity = 0;
}
$this->product->description = $this->transformDescriptionWithImg($this->product->description);
// Assign to the template the id of the virtual product. "0" if the product is not downloadable.
$this->context->smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int)$this->product->id));
$this->context->smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
if (Tools::isSubmit('submitCustomizedDatas')) {
// If cart has not been saved, we need to do it so that customization fields can have an id_cart
// We check that the cookie exists first to avoid ghost carts
if (!$this->context->cart->id && isset($_COOKIE[$this->context->cookie->getName()])) {
$this->context->cart->add();
$this->context->cookie->id_cart = (int)$this->context->cart->id;
}
$this->pictureUpload();
$this->textRecord();
$this->formTargetFormat();
} elseif (Tools::getIsset('deletePicture') && !$this->context->cart->deleteCustomizationToProduct($this->product->id, Tools::getValue('deletePicture'))) {
$this->errors[] = Tools::displayError('An error occurred while deleting the selected picture.');
}
$pictures = array();
$text_fields = array();
if ($this->product->customizable) {
$files = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_FILE, true);
foreach ($files as $file) {
$pictures['pictures_'.$this->product->id.'_'.$file['index']] = $file['value'];
}
$texts = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_TEXTFIELD, true);
foreach ($texts as $text_field) {
$text_fields['textFields_'.$this->product->id.'_'.$text_field['index']] = str_replace('<br />', "\n", $text_field['value']);
}
}
$this->context->smarty->assign(array(
'pictures' => $pictures,
'textFields' => $text_fields));
$this->product->customization_required = false;
$customization_fields = $this->product->customizable ? $this->product->getCustomizationFields($this->context->language->id) : false;
if (is_array($customization_fields)) {
foreach ($customization_fields as $customization_field) {
if ($this->product->customization_required = $customization_field['required']) {
break;
}
}
}
// Assign template vars related to the category + execute hooks related to the category
$this->assignCategory();
// Assign template vars related to the price and tax
$this->assignPriceAndTax();
// Assign template vars related to the images
$this->assignImages();
// Assign attribute groups to the template
$this->assignAttributesGroups();
// Assign attributes combinations to the template
$this->assignAttributesCombinations();
// Pack management
$pack_items = Pack::isPack($this->product->id) ? Pack::getItemTable($this->product->id, $this->context->language->id, true) : array();
$this->context->smarty->assign('packItems', $pack_items);
$this->context->smarty->assign('packs', Pack::getPacksTable($this->product->id, $this->context->language->id, true, 1));
if (isset($this->category->id) && $this->category->id) {
$return_link = Tools::safeOutput($this->context->link->getCategoryLink($this->category));
} else {
$return_link = 'javascript: history.back();';
}
$accessories = $this->product->getAccessories($this->context->language->id);
if ($this->product->cache_is_pack || count($accessories)) {
$this->context->controller->addCSS(_THEME_CSS_DIR_.'product_list.css');
}
if ($this->product->customizable) {
$customization_datas = $this->context->cart->getProductCustomization($this->product->id, null, true);
}
$this->context->smarty->assign(array(
'stock_management' => Configuration::get('PS_STOCK_MANAGEMENT'),
'customizationFields' => $customization_fields,
'id_customization' => empty($customization_datas) ? null : $customization_datas[0]['id_customization'],
'accessories' => $accessories,
'return_link' => $return_link,
'product' => $this->product,
'product_manufacturer' => new Manufacturer((int)$this->product->id_manufacturer, $this->context->language->id),
'token' => Tools::getToken(false),
'features' => $this->product->getFrontFeatures($this->context->language->id),
'attachments' => (($this->product->cache_has_attachments) ? $this->product->getAttachments($this->context->language->id) : array()),
'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int)$this->product->out_of_stock),
'last_qties' => (int)Configuration::get('PS_LAST_QTIES'),
'HOOK_EXTRA_LEFT' => Hook::exec('displayLeftColumnProduct'),
'HOOK_EXTRA_RIGHT' => Hook::exec('displayRightColumnProduct'),
'HOOK_PRODUCT_OOS' => Hook::exec('actionProductOutOfStock', array('product' => $this->product)),
'HOOK_PRODUCT_ACTIONS' => Hook::exec('displayProductButtons', array('product' => $this->product)),
'HOOK_PRODUCT_TAB' => Hook::exec('displayProductTab', array('product' => $this->product)),
'HOOK_PRODUCT_TAB_CONTENT' => Hook::exec('displayProductTabContent', array('product' => $this->product)),
'HOOK_PRODUCT_CONTENT' => Hook::exec('displayProductContent', array('product' => $this->product)),
'display_qties' => (int)Configuration::get('PS_DISPLAY_QTIES'),
'display_ht' => !Tax::excludeTaxeOption(),
'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM'),
'ENT_NOQUOTES' => ENT_NOQUOTES,
'outOfStockAllowed' => (int)Configuration::get('PS_ORDER_OUT_OF_STOCK'),
'errors' => $this->errors,
'body_classes' => array(
$this->php_self.'-'.$this->product->id,
$this->php_self.'-'.$this->product->link_rewrite,
'category-'.(isset($this->category) ? $this->category->id : ''),
'category-'.(isset($this->category) ? $this->category->getFieldByLang('link_rewrite') : '')
),
'display_discount_price' => Configuration::get('PS_DISPLAY_DISCOUNT_PRICE'),
));
}
if (ProductDownload::getIdFromIdProduct((int)$this->product->id) == 0)
$this->setTemplate(_PS_THEME_DIR_.'product.tpl');
else
$this->setTemplate(_PS_THEME_DIR_.'product_virtual.tpl');
}
}
I tried following code but it's give exceptions:
var mockIdsDbContext = new Mock<IdentityServerDbContext>();
var applicationUser = new ApplicationUser()
{
Id = Guid.NewGuid().ToString(),
Email = "shashikant0423#gmail.com",
PhoneNumber = "999999999"
};
var usersTestData = new List<ApplicationUser>() { applicationUser };
var users = MockDbSet(usersTestData);
mockIdsDbContext.Setup(x => x.Users).Returns(userManager.Object.Users);
Mock<DbSet<T>> MockDbSet<T>(IEnumerable<T> list) where T : class, new()
{
IQueryable<T> queryableList = list.AsQueryable();
Mock<DbSet<T>> dbSetMock = new Mock<DbSet<T>>();
dbSetMock.As<IQueryable<T>>().Setup(x => x.Provider).Returns(queryableList.Provider);
dbSetMock.As<IQueryable<T>>().Setup(x => x.Expression).Returns(queryableList.Expression);
dbSetMock.As<IQueryable<T>>().Setup(x => x.ElementType).Returns(queryableList.ElementType);
dbSetMock.As<IQueryable<T>>().Setup(x => x.GetEnumerator()).Returns(() => queryableList.GetEnumerator());
//dbSetMock.Setup(x => x.Create()).Returns(new T());
return dbSetMock;
}
but I got error like:
Can not instantiate proxy of class: RenewPlus.IdentityServer.Data.IdentityServerDbContext. Could not find a parameterless constructor
Instead of mocking the rather complex DbContext I'd recommend instead using the Microsoft.EntityFrameworkCore.InMemory driver.
https://learn.microsoft.com/en-us/ef/core/providers/in-memory/
I have the following controller action method.
[HttpPost]
public ActionResult CreateProvider(Provider provider)
{
try
{
int providerCreationSuccessful = _repository.CreateProvider(provider);
if (providerCreationSuccessful == 2)
TempData["userIntimation"] = "Provider Registered Successfully";
//return RedirectToAction("ShowTheListOfProviders");
}
catch (Exception Ex)
{
_logger.Error(Ex.Message);
return View("Error");
}
return Json(new { url = Url.Action("ShowTheListOfProviders", "Provider") });
}
I had written the following Test case for the above method,which was working
[TestMethod()]
public void CreateProviderTest()
{
mockProviderRepository.Setup(provider => provider.CreateProvider(_provider)).Returns(new int());
var providerCreationResult = _providerController.CreateProvider(_provider) as ActionResult;
Assert.IsNotNull(providerCreationResult);
}
As can be seen from my code in the action method,I am redirecting using AJAX,hence returning JSON of the url to be redirected to.
Now,the test is obviously failing.I am new to unit tests and was wondering,what updates I needed to make to the Testmethod for it to pass.Please guide me.Thanks.
If you want test the Json Result contains the expected URL, you can write a test like below.
[TestMethod]
public void CreateProvider_Execute_EnsureJsonContainsExpectedUrl()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
context.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
response.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);
RouteConfig.RegisterRoutes(new RouteCollection());
var repoStub = new Mock<IRepository>();
repoStub.Setup(x => x.CreateProvider(new Provider())).Returns(1);
var sut = new HomeController(repoStub.Object, new Mock<ILogger>().Object);
sut.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
var result = sut.CreateProvider(new Provider()) as JsonResult;
var actualUrl = GetValueFromJsonResult<string>(result, "url");
Assert.AreEqual<string>("/Provider/ShowTheListOfProviders", actualUrl);
}
private T GetValueFromJsonResult<T>(JsonResult jsonResult, string propertyName)
{
var property =
jsonResult.Data.GetType().GetProperties()
.Where(p => string.Compare(p.Name, propertyName) == 0)
.FirstOrDefault();
if (null == property)
throw new ArgumentException("propertyName not found", "propertyName");
return (T)property.GetValue(jsonResult.Data, null);
}
I would like to mock a WebViewPage and compare the output with an expected result.
here are my mockhelpers I'm using
public static class MockHelpers
{
public static HttpContextBase MockHttpContext(NameValueCollection queryStringCollection = null)
{
var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
if(queryStringCollection != null)
SetupMockRequestQuerystringValues(request, queryStringCollection);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
response.Setup(x => x.ApplyAppPathModifier(Moq.It.IsAny<String>())).Returns((String url) => url);
// response.SetupGet(x => x.Cookies).Returns(new HttpCookieCollection()); // This also failed to work
var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);
context.SetupGet(x => x.Response.Cookies).Returns(new HttpCookieCollection()); // still can't call the Clear() method
context.SetupGet(p => p.User.Identity.Name).Returns("blah");
context.SetupGet(p => p.User.Identity.IsAuthenticated).Returns(true);
return context.Object;
}
private static void SetupMockRequestQuerystringValues( Mock<HttpRequestBase> request, NameValueCollection queryStringCollection)
{
request.SetupGet(x => x.QueryString).Returns(queryStringCollection);
}
public static ViewContext MockViewContext()
{
return CreateSimpleGenericMock<ViewContext>();
}
public static T MockWebViewPage<T>() where T : WebViewPage
{
var mock = new Mock<T>(MockBehavior.Loose) { CallBase = true };
mock.SetupGet(x => x.Context).Returns(MockHttpContext());
mock.SetupGet(x => x.Layout).Returns("layoutName");
mock.SetupGet(x => x.VirtualPath).Returns("virtualPathName");
mock.SetupGet(x => x.Page).Returns(new object{});
mock.SetupGet(x => x.PageData).Returns(new Dictionary<object, dynamic>()
{
{new object(), new object()}
});
var page = mock.Object;
//var helper = new HtmlHelper<object>(new ViewContext { ViewData = CreateSimpleGenericMock<ViewDataDictionary>() }, page, CreateSimpleGenericMock<RouteCollection>());
var helper = new HtmlHelper<object>(new ViewContext { ViewData = new ViewDataDictionary() }, page, new RouteCollection());
page.ViewContext = MockViewContext();
page.Html = helper;
return page;
}
public static T CreateSimpleGenericMock<T>() where T : class
{
var mock = new Mock<T>();
return mock.Object;
}
}
In the MockWebViewPage method you can see all that I have faked. My test method looks like so
[TestMethod]
public void TestMethod1()
{
var coreMasterTestClass = MockHelpers.MockWebViewPage<CoreMaster<object>>();
coreMasterTestClass.ExecutePageHierarchy();
var output = coreMasterTestClass.Html;
}
Is it possible to test the output that will be generated with mocking, and if not does anyone have any possible clues how I could test this. Please note that I'm not testing actual chstml pages but core pages within our own framework.
I got this really cool Moq method that fakes out my GetService, looks like this
private Mock<IGetService<TEntity>> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
var mockGet = new Mock<IGetService<TEntity>>();
mockGet.Setup(mock => mock.GetAll()).Returns(fakeList);
mockGet.Setup(mock => mock.Get(It.IsAny<int>())).Returns((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEntity, bool>>>())).Returns((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));
return mockGet;
}
and to use this...
var fakeList = new List<Something>();
fakeList.Add(new Something { Whatever = "blah" });
//do this a buncha times
_mockGetService = FakeGetServiceFactory(fakeList);
_fakeGetServiceToInject = _mockGetService.Object;
How do I toss this into Rhino.Mock?
Something along these lines (sorry, I don't have VS handy, so I can't test it):
private IGetService<TEntity> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new()
{
var mockGet = MockRepository.GenerateMock<IGetService<TEntity>>();
mockGet.Expect(mock => mock.GetAll()).Return(fakeList);
mockGet.Expect(mock => mock.Get(Arg<int>.Is.Anything)).Do((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString()));
mockGet.Expect(mock => mock.Get(Arg<Expression<Func<TEntity, bool>>>.Is.Anything)).Do((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression));
return mockGet;
}