Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Tests - Code cleanup (ReSharper)

support1f99c1801fa2
diff --git a/src/Tests/Grand.Business.Authentication.Tests/AuthSchemaMock.cs b/src/Tests/Grand.Business.Authentication.Tests/AuthSchemaMock.cs
index 8ec665c59..189739d91 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/AuthSchemaMock.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/AuthSchemaMock.cs
@@ -1,28 +1,27 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
-namespace Grand.Business.Authentication.Tests
+namespace Grand.Business.Authentication.Tests;
+
+public class AuthSchemaMock : IAuthenticationHandler
{
- public class AuthSchemaMock : IAuthenticationHandler
+ public Task<AuthenticateResult> AuthenticateAsync()
{
- public Task<AuthenticateResult> AuthenticateAsync()
- {
- throw new NotImplementedException();
- }
+ throw new NotImplementedException();
+ }
- public Task ChallengeAsync(AuthenticationProperties properties)
- {
- throw new NotImplementedException();
- }
+ public Task ChallengeAsync(AuthenticationProperties properties)
+ {
+ throw new NotImplementedException();
+ }
- public Task ForbidAsync(AuthenticationProperties properties)
- {
- throw new NotImplementedException();
- }
+ public Task ForbidAsync(AuthenticationProperties properties)
+ {
+ throw new NotImplementedException();
+ }
- public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
- {
- throw new NotImplementedException();
- }
+ public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context)
+ {
+ throw new NotImplementedException();
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Events/CustomerDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Events/CustomerDeletedEventHandlerTests.cs
index 893a4c2de..cc870b7f5 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Events/CustomerDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Events/CustomerDeletedEventHandlerTests.cs
@@ -1,33 +1,33 @@
using Grand.Business.Authentication.Events;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Authentication.Tests.Events
+namespace Grand.Business.Authentication.Tests.Events;
+
+[TestClass]
+public class CustomerDeletedEventHandlerTests
{
- [TestClass()]
- public class CustomerDeletedEventHandlerTests
- {
- private IRepository<ExternalAuthentication> _repository;
- private CustomerDeletedEventHandler _handler;
+ private CustomerDeletedEventHandler _handler;
+ private IRepository<ExternalAuthentication> _repository;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<ExternalAuthentication>();
- _handler = new CustomerDeletedEventHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<ExternalAuthentication>();
+ _handler = new CustomerDeletedEventHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- await _repository.InsertAsync(new ExternalAuthentication { CustomerId = "1" });
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Customer>(new Customer { Id = "1" }), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Count());
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new ExternalAuthentication { CustomerId = "1" });
+ //Act
+ await _handler.Handle(new EntityDeleted<Customer>(new Customer { Id = "1" }), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/ExternalAuthenticationProviderTest.cs b/src/Tests/Grand.Business.Authentication.Tests/ExternalAuthenticationProviderTest.cs
index c89e677e4..fefe3e0b2 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/ExternalAuthenticationProviderTest.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/ExternalAuthenticationProviderTest.cs
@@ -1,24 +1,23 @@
using Grand.Business.Core.Interfaces.Authentication;
-namespace Grand.Business.Authentication.Tests
+namespace Grand.Business.Authentication.Tests;
+
+public class ExternalAuthenticationProviderTest : IExternalAuthenticationProvider
{
- public class ExternalAuthenticationProviderTest : IExternalAuthenticationProvider
- {
- public string ConfigurationUrl => "";
+ public string ConfigurationUrl => "";
- public string SystemName => nameof(ExternalAuthenticationProviderTest);
+ public string SystemName => nameof(ExternalAuthenticationProviderTest);
- public string FriendlyName => nameof(ExternalAuthenticationProviderTest);
+ public string FriendlyName => nameof(ExternalAuthenticationProviderTest);
- public int Priority => 0;
+ public int Priority => 0;
- public IList<string> LimitedToStores => new List<string>();
+ public IList<string> LimitedToStores => new List<string>();
- public IList<string> LimitedToGroups => new List<string>();
+ public IList<string> LimitedToGroups => new List<string>();
- public Task<string> GetPublicViewComponentName()
- {
- throw new NotImplementedException();
- }
+ public Task<string> GetPublicViewComponentName()
+ {
+ throw new NotImplementedException();
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs
index b1fcf79c5..32ca6ab19 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/ApiAuthenticationServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Authentication.Services;
+using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Customers;
@@ -10,160 +10,174 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Security.Claims;
-namespace Grand.Business.Authentication.Tests.Services
+namespace Grand.Business.Authentication.Tests.Services;
+
+[TestClass]
+public class ApiAuthenticationServiceTests
{
- [TestClass()]
- public class ApiAuthenticationServiceTests
- {
- private Mock<IHttpContextAccessor> _httpContextAccessorMoc;
- private Mock<ICustomerService> _customerService;
- private Mock<IUserApiService> _userApiServiceMock;
- private Mock<IGroupService> _groupService;
- private IApiAuthenticationService _authService;
- private IJwtBearerAuthenticationService _jwtBearerAuthenticationService;
+ private IApiAuthenticationService _authService;
+ private Mock<ICustomerService> _customerService;
+ private Mock<IGroupService> _groupService;
+ private Mock<IHttpContextAccessor> _httpContextAccessorMoc;
+ private IJwtBearerAuthenticationService _jwtBearerAuthenticationService;
+ private Mock<IUserApiService> _userApiServiceMock;
- [TestInitialize()]
- public void Init()
- {
- _httpContextAccessorMoc = new Mock<IHttpContextAccessor>();
- _customerService = new Mock<ICustomerService>();
- _userApiServiceMock = new Mock<IUserApiService>();
- _groupService = new Mock<IGroupService>();
- _authService = new ApiAuthenticationService(_customerService.Object, _groupService.Object, _httpContextAccessorMoc.Object);
- _jwtBearerAuthenticationService = new JwtBearerAuthenticationService(_customerService.Object, _userApiServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _httpContextAccessorMoc = new Mock<IHttpContextAccessor>();
+ _customerService = new Mock<ICustomerService>();
+ _userApiServiceMock = new Mock<IUserApiService>();
+ _groupService = new Mock<IGroupService>();
+ _authService = new ApiAuthenticationService(_customerService.Object, _groupService.Object,
+ _httpContextAccessorMoc.Object);
+ _jwtBearerAuthenticationService =
+ new JwtBearerAuthenticationService(_customerService.Object, _userApiServiceMock.Object);
+ }
- [TestMethod()]
- public async Task Valid_NullEmail_ReturnFalse()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Token", "123")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- var result = await _jwtBearerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(), "Email not exists in the context");
- }
+ [TestMethod]
+ public async Task Valid_NullEmail_ReturnFalse()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Token", "123")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ var result = await _jwtBearerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(), "Email not exists in the context");
+ }
- [TestMethod()]
- public async Task Valid_NullToken_ReturnFalse()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- var result = await _jwtBearerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(), "Wrong token, change password on the customer and create token again");
- }
+ [TestMethod]
+ public async Task Valid_NullToken_ReturnFalse()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ var result = await _jwtBearerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(),
+ "Wrong token, change password on the customer and create token again");
+ }
- [TestMethod()]
- public async Task Valid_NotFoundCoustomer_ReturnFalse()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(null));
- var result = await _jwtBearerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(), "Email not exists/or not active in the customer table");
- }
+ [TestMethod]
+ public async Task Valid_NotFoundCoustomer_ReturnFalse()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult<Customer>(null));
+ var result = await _jwtBearerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(),
+ "Email not exists/or not active in the customer table");
+ }
- [TestMethod()]
- public async Task Valid_NotActiveCustomer_ReturnFalse()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new Customer { Active = false }));
- var result = await _jwtBearerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(), "Email not exists/or not active in the customer table");
- }
+ [TestMethod]
+ public async Task Valid_NotActiveCustomer_ReturnFalse()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Customer { Active = false }));
+ var result = await _jwtBearerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerAuthenticationService.ErrorMessage(),
+ "Email not exists/or not active in the customer table");
+ }
- [TestMethod()]
- public async Task Valid_NotActiveUserApi_ReturnFalse()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new Customer { Active = true }));
- _userApiServiceMock.Setup(c => c.GetUserByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new UserApi { IsActive = false, Token = "123" }));
- var result = await _jwtBearerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual("User api not exists/or not active in the user api table", await _jwtBearerAuthenticationService.ErrorMessage());
- }
- [TestMethod()]
- public async Task Valid_WrongTokenUserApi_ReturnFalse()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new Customer { Active = true }));
- _userApiServiceMock.Setup(c => c.GetUserByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new UserApi { IsActive = true, Token = "321" }));
- var result = await _jwtBearerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual("Wrong token, generate again", await _jwtBearerAuthenticationService.ErrorMessage());
- }
- [TestMethod()]
- public async Task Valid_ActiveUserApi_ReturnTrue()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new Customer { Active = true }));
- _userApiServiceMock.Setup(c => c.GetUserByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new UserApi { IsActive = true, Token = "123" }));
- var result = await _jwtBearerAuthenticationService.Valid(context);
- Assert.IsTrue(result);
- }
+ [TestMethod]
+ public async Task Valid_NotActiveUserApi_ReturnFalse()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Customer { Active = true }));
+ _userApiServiceMock.Setup(c => c.GetUserByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new UserApi { IsActive = false, Token = "123" }));
+ var result = await _jwtBearerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual("User api not exists/or not active in the user api table",
+ await _jwtBearerAuthenticationService.ErrorMessage());
+ }
+ [TestMethod]
+ public async Task Valid_WrongTokenUserApi_ReturnFalse()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Customer { Active = true }));
+ _userApiServiceMock.Setup(c => c.GetUserByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new UserApi { IsActive = true, Token = "321" }));
+ var result = await _jwtBearerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual("Wrong token, generate again", await _jwtBearerAuthenticationService.ErrorMessage());
+ }
+ [TestMethod]
+ public async Task Valid_ActiveUserApi_ReturnTrue()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ _customerService.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Customer { Active = true }));
+ _userApiServiceMock.Setup(c => c.GetUserByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new UserApi { IsActive = true, Token = "123" }));
+ var result = await _jwtBearerAuthenticationService.Valid(context);
+ Assert.IsTrue(result);
+ }
- [TestMethod()]
- public async Task GetAuthenticatedCustomer_NullAuthHeader_GetNull()
- {
- var customer = new Customer { Email = "[email protected]" };
- var httpContext = new Mock<HttpContext>();
- var req = new Mock<HttpRequest>();
- req.Setup(c => c.Path).Returns(new PathString("/api/..."));
- req.Setup(c => c.Headers).Returns(new HeaderDictionary());
- httpContext.Setup(c => c.Request).Returns(req.Object);
- _httpContextAccessorMoc.Setup(c => c.HttpContext).Returns(httpContext.Object);
- _customerService.Setup(c => c.GetCustomerBySystemName(It.IsAny<string>())).Returns(() => Task.FromResult(customer));
- var result = await _authService.GetAuthenticatedCustomer();
- Assert.IsNull(result);
- }
+ [TestMethod]
+ public async Task GetAuthenticatedCustomer_NullAuthHeader_GetNull()
+ {
+ var customer = new Customer { Email = "[email protected]" };
+ var httpContext = new Mock<HttpContext>();
+ var req = new Mock<HttpRequest>();
+ req.Setup(c => c.Path).Returns(new PathString("/api/..."));
+ req.Setup(c => c.Headers).Returns(new HeaderDictionary());
+ httpContext.Setup(c => c.Request).Returns(req.Object);
+ _httpContextAccessorMoc.Setup(c => c.HttpContext).Returns(httpContext.Object);
+ _customerService.Setup(c => c.GetCustomerBySystemName(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(customer));
+ var result = await _authService.GetAuthenticatedCustomer();
+ Assert.IsNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs
index 17a28aed9..bc37aee23 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/CookieAuthenticationServiceTests.cs
@@ -10,123 +10,128 @@ using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Security.Claims;
-namespace Grand.Business.Authentication.Tests.Services
-{
- [TestClass()]
- public class CookieAuthenticationServiceTests
- {
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<IHttpContextAccessor> _httpAccessorMock;
- private CustomerSettings _customerSettings;
- private CookieAuthenticationService _cookieAuthService;
- private Mock<IAuthenticationService> _authServiceMock;
- private Mock<IServiceProvider> serviceProviderMock;
- private Mock<IGroupService> _groupServiceMock;
- private Mock<IUserFieldService> _userFieldServiceMock;
- private DefaultHttpContext _httpContext;
- private SecurityConfig _config;
-
- [TestInitialize()]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
+namespace Grand.Business.Authentication.Tests.Services;
- _httpAccessorMock = new Mock<IHttpContextAccessor>();
- _customerSettings = new CustomerSettings();
- _groupServiceMock = new Mock<IGroupService>();
- _userFieldServiceMock = new Mock<IUserFieldService>();
- _config = new SecurityConfig {
- CookieClaimsIssuer = "grandnode",
- CookiePrefix = ".Grand."
- };
- _cookieAuthService = new CookieAuthenticationService(_customerSettings, _customerServiceMock.Object, _groupServiceMock.Object, _userFieldServiceMock.Object, _httpAccessorMock.Object, _config);
- //For mock HttpContext extension methods like SignOutAsync ,SignInAsync etc..
- _authServiceMock = new Mock<IAuthenticationService>();
- serviceProviderMock = new Mock<IServiceProvider>();
- serviceProviderMock
- .Setup(_ => _.GetService(typeof(IAuthenticationService)))
- .Returns(_authServiceMock.Object);
- _httpContext = new DefaultHttpContext { RequestServices = serviceProviderMock.Object };
- _httpAccessorMock.Setup(c => c.HttpContext).Returns(_httpContext);
- }
+[TestClass]
+public class CookieAuthenticationServiceTests
+{
+ private Mock<IAuthenticationService> _authServiceMock;
+ private SecurityConfig _config;
+ private CookieAuthenticationService _cookieAuthService;
+ private Mock<ICustomerService> _customerServiceMock;
+ private CustomerSettings _customerSettings;
+ private Mock<IGroupService> _groupServiceMock;
+ private Mock<IHttpContextAccessor> _httpAccessorMock;
+ private DefaultHttpContext _httpContext;
+ private Mock<IUserFieldService> _userFieldServiceMock;
+ private Mock<IServiceProvider> serviceProviderMock;
- [TestMethod()]
- public async Task SignOut()
- {
- _authServiceMock.Setup(c => c.SignOutAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()));
- await _cookieAuthService.SignOut();
- _authServiceMock.Verify(c => c.SignOutAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()), Times.AtLeastOnce);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _customerServiceMock = new Mock<ICustomerService>();
+ _httpAccessorMock = new Mock<IHttpContextAccessor>();
+ _customerSettings = new CustomerSettings();
+ _groupServiceMock = new Mock<IGroupService>();
+ _userFieldServiceMock = new Mock<IUserFieldService>();
+ _config = new SecurityConfig {
+ CookieClaimsIssuer = "grandnode",
+ CookiePrefix = ".Grand."
+ };
+ _cookieAuthService = new CookieAuthenticationService(_customerSettings, _customerServiceMock.Object,
+ _groupServiceMock.Object, _userFieldServiceMock.Object, _httpAccessorMock.Object, _config);
+ //For mock HttpContext extension methods like SignOutAsync ,SignInAsync etc..
+ _authServiceMock = new Mock<IAuthenticationService>();
+ serviceProviderMock = new Mock<IServiceProvider>();
+ serviceProviderMock
+ .Setup(_ => _.GetService(typeof(IAuthenticationService)))
+ .Returns(_authServiceMock.Object);
+ _httpContext = new DefaultHttpContext { RequestServices = serviceProviderMock.Object };
+ _httpAccessorMock.Setup(c => c.HttpContext).Returns(_httpContext);
+ }
+ [TestMethod]
+ public async Task SignOut()
+ {
+ _authServiceMock.Setup(c =>
+ c.SignOutAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()));
+ await _cookieAuthService.SignOut();
+ _authServiceMock.Verify(
+ c => c.SignOutAsync(It.IsAny<HttpContext>(), It.IsAny<string>(), It.IsAny<AuthenticationProperties>()),
+ Times.AtLeastOnce);
+ }
- [TestMethod()]
- public async Task SignIn_NullCustomer_ThrowException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _cookieAuthService.SignIn(null, false));
- }
+ [TestMethod]
+ public async Task SignIn_NullCustomer_ThrowException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
+ await _cookieAuthService.SignIn(null, false));
+ }
- [TestMethod()]
- public async Task SignIn_ValidCustomer()
- {
- _authServiceMock.Setup(c => c.SignInAsync(It.IsAny<HttpContext>(),
- It.IsAny<string>(), It.IsAny<ClaimsPrincipal>(), It.IsAny<AuthenticationProperties>())).Returns(() => Task.CompletedTask);
- await _cookieAuthService.SignIn(new Customer(), false);
- _authServiceMock.Verify(c => c.SignInAsync(It.IsAny<HttpContext>(),
- It.IsAny<string>(), It.IsAny<ClaimsPrincipal>(), It.IsAny<AuthenticationProperties>()), Times.Once);
- }
- [TestMethod()]
- public async Task GetAuthenticatedCustomer_AuthenticatedFaild_ReturnNull()
- {
- _authServiceMock.Setup(c => c.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult(AuthenticateResult.Fail(new Exception())));
- var customer = await _cookieAuthService.GetAuthenticatedCustomer();
- Assert.IsNull(customer);
- }
+ [TestMethod]
+ public async Task SignIn_ValidCustomer()
+ {
+ _authServiceMock.Setup(c => c.SignInAsync(It.IsAny<HttpContext>(),
+ It.IsAny<string>(), It.IsAny<ClaimsPrincipal>(), It.IsAny<AuthenticationProperties>()))
+ .Returns(() => Task.CompletedTask);
+ await _cookieAuthService.SignIn(new Customer(), false);
+ _authServiceMock.Verify(c => c.SignInAsync(It.IsAny<HttpContext>(),
+ It.IsAny<string>(), It.IsAny<ClaimsPrincipal>(), It.IsAny<AuthenticationProperties>()), Times.Once);
+ }
- [TestMethod()]
- public async Task GetAuthenticatedCustomer_UsernameEnableRegisterd_ReturnCustomer()
- {
- var expectedCustomer = new Customer { Username = "John", Active = true };
+ [TestMethod]
+ public async Task GetAuthenticatedCustomer_AuthenticatedFaild_ReturnNull()
+ {
+ _authServiceMock.Setup(c => c.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult(AuthenticateResult.Fail(new Exception())));
+ var customer = await _cookieAuthService.GetAuthenticatedCustomer();
+ Assert.IsNull(customer);
+ }
- _customerSettings.UsernamesEnabled = true;
- var cliaim = new Claim(ClaimTypes.Name, "Johny", "", "grandnode");
- IList<Claim> claims = new List<Claim>
- {
- new Claim(ClaimTypes.Name,ClaimTypes.Name,"", "grandnode")
- };
- var principals = new ClaimsPrincipal(new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme));
- _authServiceMock.Setup(c => c.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principals, ""))));
- _customerServiceMock.Setup(c => c.GetCustomerByUsername(It.IsAny<string>())).Returns(() => Task.FromResult(expectedCustomer));
- _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
+ [TestMethod]
+ public async Task GetAuthenticatedCustomer_UsernameEnableRegisterd_ReturnCustomer()
+ {
+ var expectedCustomer = new Customer { Username = "John", Active = true };
- var customer = await _cookieAuthService.GetAuthenticatedCustomer();
- Assert.AreEqual(customer.Username, expectedCustomer.Username);
- }
+ _customerSettings.UsernamesEnabled = true;
+ var cliaim = new Claim(ClaimTypes.Name, "Johny", "", "grandnode");
+ IList<Claim> claims = new List<Claim> {
+ new(ClaimTypes.Name, ClaimTypes.Name, "", "grandnode")
+ };
+ var principals =
+ new ClaimsPrincipal(new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme));
+ _authServiceMock.Setup(c => c.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principals, ""))));
+ _customerServiceMock.Setup(c => c.GetCustomerByUsername(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(expectedCustomer));
+ _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
- [TestMethod()]
- public async Task GetAuthenticatedCustomer_UsernameEnableGuests_ReturnNull()
- {
- var expectedCustomer = new Customer { Username = "John", Active = true };
- _customerSettings.UsernamesEnabled = true;
- var cliaim = new Claim(ClaimTypes.Name, "Johny", "", "grandnode");
- IList<Claim> claims = new List<Claim>
- {
- new Claim(ClaimTypes.Name,ClaimTypes.Name,"", "grandnode")
- };
- var principals = new ClaimsPrincipal(new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme));
- _authServiceMock.Setup(c => c.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principals, ""))));
- _customerServiceMock.Setup(c => c.GetCustomerByUsername(It.IsAny<string>())).Returns(() => Task.FromResult(expectedCustomer));
- //guest
- _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(false));
- var customer = await _cookieAuthService.GetAuthenticatedCustomer();
- Assert.IsNull(customer);
- //_customerServiceMock.Verify(c => c.GetCustomerByUsername(It.IsAny<string>()), Times.Once);
- }
+ var customer = await _cookieAuthService.GetAuthenticatedCustomer();
+ Assert.AreEqual(customer.Username, expectedCustomer.Username);
+ }
+ [TestMethod]
+ public async Task GetAuthenticatedCustomer_UsernameEnableGuests_ReturnNull()
+ {
+ var expectedCustomer = new Customer { Username = "John", Active = true };
+ _customerSettings.UsernamesEnabled = true;
+ var cliaim = new Claim(ClaimTypes.Name, "Johny", "", "grandnode");
+ IList<Claim> claims = new List<Claim> {
+ new(ClaimTypes.Name, ClaimTypes.Name, "", "grandnode")
+ };
+ var principals =
+ new ClaimsPrincipal(new ClaimsIdentity(claims, GrandCookieAuthenticationDefaults.AuthenticationScheme));
+ _authServiceMock.Setup(c => c.AuthenticateAsync(It.IsAny<HttpContext>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principals, ""))));
+ _customerServiceMock.Setup(c => c.GetCustomerByUsername(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(expectedCustomer));
+ //guest
+ _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(false));
+ var customer = await _cookieAuthService.GetAuthenticatedCustomer();
+ Assert.IsNull(customer);
+ //_customerServiceMock.Verify(c => c.GetCustomerByUsername(It.IsAny<string>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs
index f9f21446c..59bb38ee5 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs
@@ -2,146 +2,158 @@
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Utilities.Authentication;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Authentication.Tests.Services
+namespace Grand.Business.Authentication.Tests.Services;
+
+[TestClass]
+public class ExternalAuthenticationServiceTests
{
- [TestClass()]
- public class ExternalAuthenticationServiceTests
+ private Mock<IGrandAuthenticationService> _authenticationServiceMock;
+ private Mock<ICustomerManagerService> _customerManagerServiceMock;
+ private Mock<ICustomerService> _customerServiceMock;
+ private IEnumerable<IExternalAuthenticationProvider> _externalAuthenticationProviders;
+ private IRepository<ExternalAuthentication> _externalAuthenticationRecordRepository;
+
+ private ExternalAuthenticationService _externalAuthenticationService;
+ private Mock<IGroupService> _groupServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _customerServiceMock = new Mock<ICustomerService>();
+ _groupServiceMock = new Mock<IGroupService>();
+ _authenticationServiceMock = new Mock<IGrandAuthenticationService>();
+ _customerManagerServiceMock = new Mock<ICustomerManagerService>();
+ _mediatorMock = new Mock<IMediator>();
+ _externalAuthenticationRecordRepository = new MongoDBRepositoryTest<ExternalAuthentication>();
+ _workContextMock = new Mock<IWorkContext>();
+ _externalAuthenticationProviders = new List<IExternalAuthenticationProvider>
+ { new ExternalAuthenticationProviderTest() };
+
+ var externalAuthenticationSetting = new ExternalAuthenticationSettings {
+ ActiveAuthenticationMethodSystemNames = [
+ "ExternalAuthenticationProviderTest"
+ ]
+ };
+
+ _externalAuthenticationService = new ExternalAuthenticationService(_authenticationServiceMock.Object,
+ _customerManagerServiceMock.Object, _customerServiceMock.Object,
+ _groupServiceMock.Object, _mediatorMock.Object, _externalAuthenticationRecordRepository,
+ _workContextMock.Object, _externalAuthenticationProviders,
+ new CustomerSettings(), externalAuthenticationSetting);
+ }
+
+
+ [TestMethod]
+ public void LoadActiveAuthenticationProvidersTest()
+ {
+ //Act
+ var result = _externalAuthenticationService.LoadActiveAuthenticationProviders();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public void LoadAuthenticationProviderBySystemNameTest()
+ {
+ //Act
+ var result =
+ _externalAuthenticationService.LoadAuthenticationProviderBySystemName("ExternalAuthenticationProviderTest");
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public void LoadAllAuthenticationProvidersTest()
+ {
+ //Act
+ var result = _externalAuthenticationService.LoadAllAuthenticationProviders();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public void AuthenticationProviderIsAvailableTest_Available()
+ {
+ //Act
+ var result =
+ _externalAuthenticationService.AuthenticationProviderIsAvailable("ExternalAuthenticationProviderTest");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public void AuthenticationProviderIsAvailableTest_NotAvailable()
+ {
+ //Act
+ var result = _externalAuthenticationService.AuthenticationProviderIsAvailable("123");
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task AssociateCustomerTest()
+ {
+ //Act
+ await _externalAuthenticationService.AssociateCustomer(new Customer(),
+ new ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest" });
+ //Assert
+ Assert.IsTrue(_externalAuthenticationRecordRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task GetCustomerTest()
+ {
+ //Arrange
+ var expectedCustomer = new Customer { Username = "John", Active = true };
+ _customerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(expectedCustomer));
+ await _externalAuthenticationService.AssociateCustomer(expectedCustomer,
+ new ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" });
+ //Act
+ var customer = await _externalAuthenticationService.GetCustomer(new ExternalAuthParam
+ { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" });
+ //Assert
+ Assert.IsNotNull(customer);
+ Assert.AreEqual(customer.Username, expectedCustomer.Username);
+ }
+
+ [TestMethod]
+ public async Task GetExternalIdentifiersTest()
+ {
+ //Arrange
+ var customer = new Customer { Username = "John", Active = true };
+ await _externalAuthenticationService.AssociateCustomer(customer,
+ new ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" });
+ //Act
+ var result = await _externalAuthenticationService.GetExternalIdentifiers(customer);
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task DeleteExternalAuthenticationTest()
{
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<IGroupService> _groupServiceMock;
-
- private Mock<IGrandAuthenticationService> _authenticationServiceMock;
- private Mock<ICustomerManagerService> _customerManagerServiceMock;
- private Mock<IMediator> _mediatorMock;
- private IRepository<ExternalAuthentication> _externalAuthenticationRecordRepository;
- private Mock<IWorkContext> _workContextMock;
- private IEnumerable<IExternalAuthenticationProvider> _externalAuthenticationProviders;
-
- ExternalAuthenticationService _externalAuthenticationService;
-
- [TestInitialize()]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
- _groupServiceMock = new Mock<IGroupService>();
- _authenticationServiceMock = new Mock<IGrandAuthenticationService>();
- _customerManagerServiceMock = new Mock<ICustomerManagerService>();
- _mediatorMock = new Mock<IMediator>();
- _externalAuthenticationRecordRepository = new MongoDBRepositoryTest<ExternalAuthentication>();
- _workContextMock = new Mock<IWorkContext>();
- _externalAuthenticationProviders = new List<IExternalAuthenticationProvider> { new ExternalAuthenticationProviderTest() };
-
- var externalAuthenticationSetting = new ExternalAuthenticationSettings
- {
- ActiveAuthenticationMethodSystemNames = [
- "ExternalAuthenticationProviderTest"
- ]
- };
-
- _externalAuthenticationService = new ExternalAuthenticationService(_authenticationServiceMock.Object, _customerManagerServiceMock.Object, _customerServiceMock.Object,
- _groupServiceMock.Object, _mediatorMock.Object, _externalAuthenticationRecordRepository, _workContextMock.Object, _externalAuthenticationProviders,
- new CustomerSettings(), externalAuthenticationSetting);
- }
-
-
- [TestMethod()]
- public void LoadActiveAuthenticationProvidersTest()
- {
- //Act
- var result = _externalAuthenticationService.LoadActiveAuthenticationProviders();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public void LoadAuthenticationProviderBySystemNameTest()
- {
- //Act
- var result = _externalAuthenticationService.LoadAuthenticationProviderBySystemName("ExternalAuthenticationProviderTest");
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public void LoadAllAuthenticationProvidersTest()
- {
- //Act
- var result = _externalAuthenticationService.LoadAllAuthenticationProviders();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public void AuthenticationProviderIsAvailableTest_Available()
- {
- //Act
- var result = _externalAuthenticationService.AuthenticationProviderIsAvailable("ExternalAuthenticationProviderTest");
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public void AuthenticationProviderIsAvailableTest_NotAvailable()
- {
- //Act
- var result = _externalAuthenticationService.AuthenticationProviderIsAvailable("123");
- //Assert
- Assert.IsFalse(result);
- }
-
- [TestMethod()]
- public async Task AssociateCustomerTest()
- {
- //Act
- await _externalAuthenticationService.AssociateCustomer(new Customer(), new Core.Utilities.Authentication.ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest" });
- //Assert
- Assert.IsTrue(_externalAuthenticationRecordRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetCustomerTest()
- {
- //Arrange
- var expectedCustomer = new Customer { Username = "John", Active = true };
- _customerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>())).Returns(() => Task.FromResult(expectedCustomer));
- await _externalAuthenticationService.AssociateCustomer(expectedCustomer, new Core.Utilities.Authentication.ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" });
- //Act
- var customer = await _externalAuthenticationService.GetCustomer(new Core.Utilities.Authentication.ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" });
- //Assert
- Assert.IsNotNull(customer);
- Assert.AreEqual(customer.Username, expectedCustomer.Username);
- }
-
- [TestMethod()]
- public async Task GetExternalIdentifiersTest()
- {
- //Arrange
- var customer = new Customer { Username = "John", Active = true };
- await _externalAuthenticationService.AssociateCustomer(customer, new Core.Utilities.Authentication.ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" });
- //Act
- var result = await _externalAuthenticationService.GetExternalIdentifiers(customer);
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task DeleteExternalAuthenticationTest()
- {
- //Arrange
- var customer = new Customer { Username = "John", Active = true };
- var externalAuthParam = new Core.Utilities.Authentication.ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" };
- await _externalAuthenticationService.AssociateCustomer(customer, externalAuthParam);
- //Act
- await _externalAuthenticationService.DeleteExternalAuthentication(_externalAuthenticationRecordRepository.Table.FirstOrDefault(x=>x.ExternalIdentifier == externalAuthParam.Identifier));
- //Assert
- Assert.IsFalse(_externalAuthenticationRecordRepository.Table.Any());
- }
+ //Arrange
+ var customer = new Customer { Username = "John", Active = true };
+ var externalAuthParam = new ExternalAuthParam
+ { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" };
+ await _externalAuthenticationService.AssociateCustomer(customer, externalAuthParam);
+ //Act
+ await _externalAuthenticationService.DeleteExternalAuthentication(
+ _externalAuthenticationRecordRepository.Table.FirstOrDefault(x =>
+ x.ExternalIdentifier == externalAuthParam.Identifier));
+ //Assert
+ Assert.IsFalse(_externalAuthenticationRecordRepository.Table.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.cs
index bc0d53097..362f60118 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/JwtBearerCustomerAuthenticationServiceTests.cs
@@ -1,139 +1,155 @@
-using Grand.Business.Core.Interfaces.Authentication;
-using Grand.Business.Authentication.Services;
+using Grand.Business.Authentication.Services;
+using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Utilities.Common.Security;
+using Grand.Domain.Common;
using Grand.Domain.Customers;
+using Grand.Domain.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Security.Claims;
-using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Business.Core.Utilities.Common.Security;
-using Grand.Domain.Security;
-namespace Grand.Business.Authentication.Tests.Services
+namespace Grand.Business.Authentication.Tests.Services;
+
+[TestClass]
+public class JwtBearerCustomerAuthenticationServiceTests
{
- [TestClass()]
- public class JwtBearerCustomerAuthenticationServiceTests
+ private Mock<ICustomerService> _customerServiceMock;
+ private Mock<IGroupService> _groupService;
+ private Mock<HttpContext> _httpContextMock;
+
+ private IJwtBearerCustomerAuthenticationService _jwtBearerCustomerAuthenticationService;
+ private Mock<IPermissionService> _permissionServiceMock;
+ private Mock<IRefreshTokenService> _refreshTokenServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<IPermissionService> _permissionServiceMock;
- private Mock<HttpContext> _httpContextMock;
- private Mock<IGroupService> _groupService;
- private Mock<IRefreshTokenService> _refreshTokenServiceMock;
+ _customerServiceMock = new Mock<ICustomerService>();
+ _groupService = new Mock<IGroupService>();
+ _permissionServiceMock = new Mock<IPermissionService>();
+ _httpContextMock = new Mock<HttpContext>();
+ _refreshTokenServiceMock = new Mock<IRefreshTokenService>();
+ _jwtBearerCustomerAuthenticationService = new JwtBearerCustomerAuthenticationService(
+ _customerServiceMock.Object, _permissionServiceMock.Object, _groupService.Object,
+ _refreshTokenServiceMock.Object);
+ }
- private IJwtBearerCustomerAuthenticationService _jwtBearerCustomerAuthenticationService;
+ [TestMethod]
+ public async Task Valid_NullEmail_ReturnFalse()
+ {
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Token", "123"),
+ new("Email", "[email protected]"),
+ new("RefreshId", "567")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(), "Not found customer");
+ }
- [TestInitialize()]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
- _groupService = new Mock<IGroupService>();
- _permissionServiceMock = new Mock<IPermissionService>();
- _httpContextMock = new Mock<HttpContext>();
- _refreshTokenServiceMock = new Mock<IRefreshTokenService>();
- _jwtBearerCustomerAuthenticationService = new JwtBearerCustomerAuthenticationService(_customerServiceMock.Object, _permissionServiceMock.Object, _groupService.Object, _refreshTokenServiceMock.Object);
- }
+ [TestMethod]
+ public async Task Valid_NullToken_ReturnFalse()
+ {
+ var expectedCustomer = new Customer { Username = "John", Active = true };
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(expectedCustomer));
- [TestMethod()]
- public async Task Valid_NullEmail_ReturnFalse()
- {
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Token", "123"),
- new Claim("Email", "[email protected]"),
- new Claim("RefreshId", "567")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(), "Not found customer");
- }
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(),
+ "Invalid token or cancel by refresh token");
+ }
- [TestMethod()]
- public async Task Valid_NullToken_ReturnFalse()
- {
- var expectedCustomer = new Customer { Username = "John", Active = true };
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(expectedCustomer));
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(), "Invalid token or cancel by refresh token");
- }
+ [TestMethod]
+ public async Task Valid_NotActiveCustomer_ReturnFalse()
+ {
+ var expectedCustomer = new Customer { Username = "John", Active = true };
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(expectedCustomer));
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Customer { Active = false }));
+ var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(),
+ "Customer not exists/or not active in the customer table");
+ }
- [TestMethod()]
- public async Task Valid_NotActiveCustomer_ReturnFalse()
- {
- var expectedCustomer = new Customer { Username = "John", Active = true };
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(expectedCustomer));
+ [TestMethod]
+ public async Task Valid_NoPermissions_Customer_ReturnFalse()
+ {
+ var customer = new Customer { Username = "John", Active = true };
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(customer));
+ _refreshTokenServiceMock.Setup(c => c.GetCustomerRefreshToken(customer)).Returns(() =>
+ Task.FromResult(new RefreshToken { IsActive = true, RefreshId = "567", Token = "123" }));
+ _permissionServiceMock.Setup(c => c.Authorize(StandardPermission.AllowUseApi, customer))
+ .Returns(() => Task.FromResult(false));
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123"),
+ new("RefreshId", "567")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(new Customer { Active = false }));
- var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(), "Customer not exists/or not active in the customer table");
- }
+ var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
+ Assert.IsFalse(result);
+ Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(),
+ "You do not have permission to use API operation (Customer group)");
+ }
- [TestMethod()]
- public async Task Valid_NoPermissions_Customer_ReturnFalse()
- {
- var customer = new Customer { Username = "John", Active = true };
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(customer));
- _refreshTokenServiceMock.Setup(c => c.GetCustomerRefreshToken(customer)).Returns(() => Task.FromResult(new RefreshToken { IsActive = true, RefreshId = "567", Token = "123" }));
- _permissionServiceMock.Setup(c => c.Authorize(StandardPermission.AllowUseApi, customer)).Returns(() => Task.FromResult(false));
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123"),
- new Claim("RefreshId", "567")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
-
- var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
- Assert.IsFalse(result);
- Assert.AreEqual(await _jwtBearerCustomerAuthenticationService.ErrorMessage(), "You do not have permission to use API operation (Customer group)");
- }
- [TestMethod()]
- public async Task Valid_Customer_ReturnTrue()
- {
- var customer = new Customer { Username = "John", Active = true };
- customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.PasswordToken, Value = "123", StoreId = "" });
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult(customer));
- _refreshTokenServiceMock.Setup(c => c.GetCustomerRefreshToken(customer)).Returns(() => Task.FromResult(new RefreshToken { IsActive = true, RefreshId = "567", Token = "123" }));
- _permissionServiceMock.Setup(c => c.Authorize(StandardPermission.AllowUseApi, customer)).Returns(() => Task.FromResult(true));
- var httpContext = new Mock<HttpContext>();
- var context = new TokenValidatedContext(httpContext.Object, new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
- IList<Claim> claims = new List<Claim>
- {
- new Claim("Email", "[email protected]"),
- new Claim("Token", "123"),
- new Claim("RefreshId", "567")
- };
- context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
+ [TestMethod]
+ public async Task Valid_Customer_ReturnTrue()
+ {
+ var customer = new Customer { Username = "John", Active = true };
+ customer.UserFields.Add(new UserField
+ { Key = SystemCustomerFieldNames.PasswordToken, Value = "123", StoreId = "" });
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(customer));
+ _refreshTokenServiceMock.Setup(c => c.GetCustomerRefreshToken(customer)).Returns(() =>
+ Task.FromResult(new RefreshToken { IsActive = true, RefreshId = "567", Token = "123" }));
+ _permissionServiceMock.Setup(c => c.Authorize(StandardPermission.AllowUseApi, customer))
+ .Returns(() => Task.FromResult(true));
+ var httpContext = new Mock<HttpContext>();
+ var context = new TokenValidatedContext(httpContext.Object,
+ new AuthenticationScheme("", "", typeof(AuthSchemaMock)), new JwtBearerOptions());
+ IList<Claim> claims = new List<Claim> {
+ new("Email", "[email protected]"),
+ new("Token", "123"),
+ new("RefreshId", "567")
+ };
+ context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, ""));
- var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
- Assert.IsTrue(result);
- }
+ var result = await _jwtBearerCustomerAuthenticationService.Valid(context);
+ Assert.IsTrue(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/RefreshTokenServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/RefreshTokenServiceTests.cs
index 2bdf7b6bd..56f72645d 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/RefreshTokenServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/RefreshTokenServiceTests.cs
@@ -1,71 +1,72 @@
using Grand.Business.Authentication.Services;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Domain;
+using Grand.Domain.Customers;
using Grand.Domain.Security;
+using Grand.Infrastructure.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Authentication.Tests.Services
-{
- [TestClass()]
- public class RefreshTokenServiceTests
- {
- private Mock<IUserFieldService> _userFieldServiceMock;
- private RefreshTokenService _service;
-
- [TestInitialize()]
- public void Init()
- {
- _userFieldServiceMock = new Mock<IUserFieldService>();
- _service = new RefreshTokenService(_userFieldServiceMock.Object, new Infrastructure.Configuration.FrontendAPIConfig {
- SecretKey = "JWTRefreshTokenHIGHsecuredPasswordVVVp1OH7Xzyr",
- ValidIssuer = "http://localhost:4200",
- ValidAudience = "http://localhost:4200",
- ValidateLifetime = false,
- ValidateAudience = false,
- ValidateIssuerSigningKey = false,
- ExpiryInMinutes = 1440,
- RefreshTokenExpiryInMinutes = 1440,
- Enabled = true,
- ValidateIssuer = false
- });
- }
+namespace Grand.Business.Authentication.Tests.Services;
- [TestMethod()]
- public void GenerateRefreshTokenTest()
- {
- //Act
- var result = _service.GenerateRefreshToken();
- //Assert
- Assert.IsNotNull(result);
- }
+[TestClass]
+public class RefreshTokenServiceTests
+{
+ private RefreshTokenService _service;
+ private Mock<IUserFieldService> _userFieldServiceMock;
- [TestMethod()]
- public async Task SaveRefreshTokenToCustomerTest()
- {
- //Arrange
- _userFieldServiceMock.Setup(c => c.SaveField<string>(It.IsAny<BaseEntity>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()));
- var token = Guid.NewGuid().ToString();
- //Act
- var result = await _service.SaveRefreshTokenToCustomer(new Domain.Customers.Customer(), token);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(token, result.Token);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _userFieldServiceMock = new Mock<IUserFieldService>();
+ _service = new RefreshTokenService(_userFieldServiceMock.Object, new FrontendAPIConfig {
+ SecretKey = "JWTRefreshTokenHIGHsecuredPasswordVVVp1OH7Xzyr",
+ ValidIssuer = "http://localhost:4200",
+ ValidAudience = "http://localhost:4200",
+ ValidateLifetime = false,
+ ValidateAudience = false,
+ ValidateIssuerSigningKey = false,
+ ExpiryInMinutes = 1440,
+ RefreshTokenExpiryInMinutes = 1440,
+ Enabled = true,
+ ValidateIssuer = false
+ });
+ }
- [TestMethod()]
- public async Task GetCustomerRefreshTokenTest()
- {
- //Arrange
- _userFieldServiceMock.Setup(c => c.GetFieldsForEntity<RefreshToken>(It.IsAny<BaseEntity>(), It.IsAny<string>(), It.IsAny<string>()))
- .Returns(Task.FromResult(new RefreshToken { Token = "123" }));
- //Act
- var result = await _service.GetCustomerRefreshToken(new Domain.Customers.Customer());
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("123", result.Token);
- }
+ [TestMethod]
+ public void GenerateRefreshTokenTest()
+ {
+ //Act
+ var result = _service.GenerateRefreshToken();
+ //Assert
+ Assert.IsNotNull(result);
+ }
+ [TestMethod]
+ public async Task SaveRefreshTokenToCustomerTest()
+ {
+ //Arrange
+ _userFieldServiceMock.Setup(c =>
+ c.SaveField(It.IsAny<BaseEntity>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()));
+ var token = Guid.NewGuid().ToString();
+ //Act
+ var result = await _service.SaveRefreshTokenToCustomer(new Customer(), token);
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(token, result.Token);
+ }
+ [TestMethod]
+ public async Task GetCustomerRefreshTokenTest()
+ {
+ //Arrange
+ _userFieldServiceMock.Setup(c =>
+ c.GetFieldsForEntity<RefreshToken>(It.IsAny<BaseEntity>(), It.IsAny<string>(), It.IsAny<string>()))
+ .Returns(Task.FromResult(new RefreshToken { Token = "123" }));
+ //Act
+ var result = await _service.GetCustomerRefreshToken(new Customer());
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("123", result.Token);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs
index f754c9e1f..ef7e1293a 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Services/TwoFactorAuthenticationServiceTests.cs
@@ -2,57 +2,58 @@
using Grand.Business.Core.Interfaces.Authentication;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Domain.Customers;
+using Grand.Domain.Localization;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Authentication.Tests.Services
+namespace Grand.Business.Authentication.Tests.Services;
+
+[TestClass]
+public class TwoFactorAuthenticationServiceTests
{
- [TestClass()]
- public class TwoFactorAuthenticationServiceTests
+ private Mock<IEnumerable<ISMSVerificationService>> _sMsVerificationService;
+ private TwoFactorAuthenticationService _twoFactorAuthenticationService;
+ private Mock<IUserFieldService> _userFieldServiceMock;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<IWorkContext> _workContextMock;
- private Mock<IUserFieldService> _userFieldServiceMock;
- private Mock<IEnumerable<ISMSVerificationService>> _sMsVerificationService;
- private TwoFactorAuthenticationService _twoFactorAuthenticationService;
- [TestInitialize()]
- public void Init()
- {
- _workContextMock = new Mock<IWorkContext>();
- _userFieldServiceMock = new Mock<IUserFieldService>();
- _sMsVerificationService = new Mock<IEnumerable<ISMSVerificationService>>();
- _twoFactorAuthenticationService = new TwoFactorAuthenticationService(_workContextMock.Object,
- _userFieldServiceMock.Object, _sMsVerificationService.Object);
- }
+ _workContextMock = new Mock<IWorkContext>();
+ _userFieldServiceMock = new Mock<IUserFieldService>();
+ _sMsVerificationService = new Mock<IEnumerable<ISMSVerificationService>>();
+ _twoFactorAuthenticationService = new TwoFactorAuthenticationService(_workContextMock.Object,
+ _userFieldServiceMock.Object, _sMsVerificationService.Object);
+ }
- [TestMethod()]
- public async Task GenerateCodeSetupTest_AppVerification()
- {
- //Arrange
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- //Act
- var result = await _twoFactorAuthenticationService.GenerateCodeSetup(Guid.NewGuid().ToString(),
- new Customer { Email = "[email protected]" },
- new Domain.Localization.Language { LanguageCulture = "en" }, TwoFactorAuthenticationType.AppVerification);
- //Assert
- Assert.IsTrue(result.CustomValues.ContainsKey("QrCodeImageUrl"));
- Assert.IsTrue(result.CustomValues.ContainsKey("ManualEntryQrCode"));
- }
- [TestMethod()]
- public async Task GenerateCodeSetupTest_Email()
- {
- //Arrange
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- //Act
- var result = await _twoFactorAuthenticationService.GenerateCodeSetup(Guid.NewGuid().ToString(),
- new Customer { Email = "[email protected]" },
- new Domain.Localization.Language { LanguageCulture = "en" }, TwoFactorAuthenticationType.EmailVerification);
- //Assert
- Assert.IsTrue(result.CustomValues.ContainsKey("Token"));
- }
-
+ [TestMethod]
+ public async Task GenerateCodeSetupTest_AppVerification()
+ {
+ //Arrange
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ //Act
+ var result = await _twoFactorAuthenticationService.GenerateCodeSetup(Guid.NewGuid().ToString(),
+ new Customer { Email = "[email protected]" },
+ new Language { LanguageCulture = "en" }, TwoFactorAuthenticationType.AppVerification);
+ //Assert
+ Assert.IsTrue(result.CustomValues.ContainsKey("QrCodeImageUrl"));
+ Assert.IsTrue(result.CustomValues.ContainsKey("ManualEntryQrCode"));
+ }
+ [TestMethod]
+ public async Task GenerateCodeSetupTest_Email()
+ {
+ //Arrange
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ //Act
+ var result = await _twoFactorAuthenticationService.GenerateCodeSetup(Guid.NewGuid().ToString(),
+ new Customer { Email = "[email protected]" },
+ new Language { LanguageCulture = "en" }, TwoFactorAuthenticationType.EmailVerification);
+ //Assert
+ Assert.IsTrue(result.CustomValues.ContainsKey("Token"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Authentication.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Startup/StartupApplicationTests.cs
index 52f44ed1c..c9c6e788f 100644
--- a/src/Tests/Grand.Business.Authentication.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Authentication.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Authentication.Tests.Startup
+namespace Grand.Business.Authentication.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/BrandDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/BrandDeletedEventHandlerTests.cs
index 765107892..add509ece 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/BrandDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/BrandDeletedEventHandlerTests.cs
@@ -1,47 +1,47 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class BrandDeletedEventHandlerTests
{
- [TestClass()]
- public class BrandDeletedEventHandlerTests
- {
- private IRepository<Product> _repository;
- private BrandDeletedEventHandler _handler;
+ private BrandDeletedEventHandler _handler;
+ private IRepository<Product> _repository;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- _handler = new BrandDeletedEventHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Product>();
+ _handler = new BrandDeletedEventHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var brand = new Brand();
- var product = new Product {
- BrandId = brand.Id
- };
- await _repository.InsertAsync(product);
- var product2 = new Product {
- BrandId = brand.Id
- };
- await _repository.InsertAsync(product2);
- var product3 = new Product {
- BrandId = "1"
- };
- await _repository.InsertAsync(product3);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var brand = new Brand();
+ var product = new Product {
+ BrandId = brand.Id
+ };
+ await _repository.InsertAsync(product);
+ var product2 = new Product {
+ BrandId = brand.Id
+ };
+ await _repository.InsertAsync(product2);
+ var product3 = new Product {
+ BrandId = "1"
+ };
+ await _repository.InsertAsync(product3);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Brand>(brand), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.BrandId == brand.Id).Count());
- Assert.AreEqual(1, _repository.Table.Where(x => x.BrandId == "1").Count());
- }
+ //Act
+ await _handler.Handle(new EntityDeleted<Brand>(brand), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Where(x => x.BrandId == brand.Id).Count());
+ Assert.AreEqual(1, _repository.Table.Where(x => x.BrandId == "1").Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CategoryDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CategoryDeletedEventHandlerTests.cs
index f9e463e24..7dfdf5235 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CategoryDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CategoryDeletedEventHandlerTests.cs
@@ -1,59 +1,61 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Seo;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.Events;
using Grand.Infrastructure.Tests.Caching;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class CategoryDeletedEventHandlerTests
{
- [TestClass()]
- public class CategoryDeletedEventHandlerTests
+ private MemoryCacheBase _cacheBase;
+ private IRepository<EntityUrl> _entityUrlRepository;
+
+ private CategoryDeletedEventHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Product> _repository;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<Product> _repository;
- private IRepository<EntityUrl> _entityUrlRepository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
-
- private CategoryDeletedEventHandler _handler;
-
- [TestInitialize()]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _repository = new MongoDBRepositoryTest<Product>();
- _entityUrlRepository = new MongoDBRepositoryTest<EntityUrl>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _handler = new CategoryDeletedEventHandler(_entityUrlRepository, _repository, _cacheBase);
- }
-
-
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var category = new Category();
- var product = new Product();
- product.ProductCategories.Add(new ProductCategory { CategoryId = category.Id });
- await _repository.InsertAsync(product);
- var product2 = new Product();
- product2.ProductCategories.Add(new ProductCategory { CategoryId = category.Id });
- await _repository.InsertAsync(product2);
- var product3 = new Product();
- product3.ProductCategories.Add(new ProductCategory { CategoryId = "1" });
- await _repository.InsertAsync(product3);
-
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Category>(category), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == category.Id)).Count());
- Assert.AreEqual(1, _repository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == "1")).Count());
- }
+ _mediatorMock = new Mock<IMediator>();
+ _repository = new MongoDBRepositoryTest<Product>();
+ _entityUrlRepository = new MongoDBRepositoryTest<EntityUrl>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _handler = new CategoryDeletedEventHandler(_entityUrlRepository, _repository, _cacheBase);
+ }
+
+
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var category = new Category();
+ var product = new Product();
+ product.ProductCategories.Add(new ProductCategory { CategoryId = category.Id });
+ await _repository.InsertAsync(product);
+ var product2 = new Product();
+ product2.ProductCategories.Add(new ProductCategory { CategoryId = category.Id });
+ await _repository.InsertAsync(product2);
+ var product3 = new Product();
+ product3.ProductCategories.Add(new ProductCategory { CategoryId = "1" });
+ await _repository.InsertAsync(product3);
+
+ //Act
+ await _handler.Handle(new EntityDeleted<Category>(category), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0,
+ _repository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == category.Id)).Count());
+ Assert.AreEqual(1, _repository.Table.Where(x => x.ProductCategories.Any(y => y.CategoryId == "1")).Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CollectionDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CollectionDeletedEventHandlerTests.cs
index 02f4e92d9..1f286aff2 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CollectionDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/CollectionDeletedEventHandlerTests.cs
@@ -1,59 +1,61 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Seo;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.Events;
using Grand.Infrastructure.Tests.Caching;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class CollectionDeletedEventHandlerTests
{
- [TestClass()]
- public class CollectionDeletedEventHandlerTests
+ private MemoryCacheBase _cacheBase;
+ private IRepository<EntityUrl> _entityUrlRepository;
+
+ private CollectionDeletedEventHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Product> _repository;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<Product> _repository;
- private IRepository<EntityUrl> _entityUrlRepository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
-
- private CollectionDeletedEventHandler _handler;
-
- [TestInitialize()]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _repository = new MongoDBRepositoryTest<Product>();
- _entityUrlRepository = new MongoDBRepositoryTest<EntityUrl>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _handler = new CollectionDeletedEventHandler(_entityUrlRepository, _repository, _cacheBase);
- }
-
-
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var collection = new Collection();
- var product = new Product();
- product.ProductCollections.Add(new ProductCollection { CollectionId = collection.Id });
- await _repository.InsertAsync(product);
- var product2 = new Product();
- product2.ProductCollections.Add(new ProductCollection { CollectionId = collection.Id });
- await _repository.InsertAsync(product2);
- var product3 = new Product();
- product3.ProductCollections.Add(new ProductCollection { CollectionId = "1" });
- await _repository.InsertAsync(product3);
-
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Collection>(collection), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.ProductCollections.Any(y => y.CollectionId == collection.Id)).Count());
- Assert.AreEqual(1, _repository.Table.Where(x => x.ProductCollections.Any(y => y.CollectionId == "1")).Count());
- }
+ _mediatorMock = new Mock<IMediator>();
+ _repository = new MongoDBRepositoryTest<Product>();
+ _entityUrlRepository = new MongoDBRepositoryTest<EntityUrl>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _handler = new CollectionDeletedEventHandler(_entityUrlRepository, _repository, _cacheBase);
+ }
+
+
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var collection = new Collection();
+ var product = new Product();
+ product.ProductCollections.Add(new ProductCollection { CollectionId = collection.Id });
+ await _repository.InsertAsync(product);
+ var product2 = new Product();
+ product2.ProductCollections.Add(new ProductCollection { CollectionId = collection.Id });
+ await _repository.InsertAsync(product2);
+ var product3 = new Product();
+ product3.ProductCollections.Add(new ProductCollection { CollectionId = "1" });
+ await _repository.InsertAsync(product3);
+
+ //Act
+ await _handler.Handle(new EntityDeleted<Collection>(collection), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0,
+ _repository.Table.Where(x => x.ProductCollections.Any(y => y.CollectionId == collection.Id)).Count());
+ Assert.AreEqual(1, _repository.Table.Where(x => x.ProductCollections.Any(y => y.CollectionId == "1")).Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeleteMeasureUnitOnProductEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeleteMeasureUnitOnProductEventHandlerTests.cs
index 0d672dbca..09facba6a 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeleteMeasureUnitOnProductEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeleteMeasureUnitOnProductEventHandlerTests.cs
@@ -1,48 +1,48 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Directory;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class DeleteMeasureUnitOnProductEventHandlerTests
{
- [TestClass()]
- public class DeleteMeasureUnitOnProductEventHandlerTests
- {
- private IRepository<Product> _repository;
- private DeleteMeasureUnitOnProductEventHandler _handler;
+ private DeleteMeasureUnitOnProductEventHandler _handler;
+ private IRepository<Product> _repository;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- _handler = new DeleteMeasureUnitOnProductEventHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Product>();
+ _handler = new DeleteMeasureUnitOnProductEventHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var measureUnit = new MeasureUnit();
- var product = new Product {
- UnitId = measureUnit.Id
- };
- await _repository.InsertAsync(product);
- var product2 = new Product {
- UnitId = measureUnit.Id
- };
- await _repository.InsertAsync(product2);
- var product3 = new Product {
- UnitId = "1"
- };
- await _repository.InsertAsync(product3);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var measureUnit = new MeasureUnit();
+ var product = new Product {
+ UnitId = measureUnit.Id
+ };
+ await _repository.InsertAsync(product);
+ var product2 = new Product {
+ UnitId = measureUnit.Id
+ };
+ await _repository.InsertAsync(product2);
+ var product3 = new Product {
+ UnitId = "1"
+ };
+ await _repository.InsertAsync(product3);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<MeasureUnit>(measureUnit), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.UnitId == measureUnit.Id).Count());
- Assert.AreEqual(1, _repository.Table.Where(x => x.UnitId == "1").Count());
- }
+ //Act
+ await _handler.Handle(new EntityDeleted<MeasureUnit>(measureUnit), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Where(x => x.UnitId == measureUnit.Id).Count());
+ Assert.AreEqual(1, _repository.Table.Where(x => x.UnitId == "1").Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeliveryDateDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeliveryDateDeletedEventHandlerTests.cs
index 31234afc7..5d1029bd9 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeliveryDateDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DeliveryDateDeletedEventHandlerTests.cs
@@ -1,48 +1,48 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Shipping;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class DeliveryDateDeletedEventHandlerTests
{
- [TestClass()]
- public class DeliveryDateDeletedEventHandlerTests
- {
- private IRepository<Product> _repository;
- private DeliveryDateDeletedEventHandler _handler;
+ private DeliveryDateDeletedEventHandler _handler;
+ private IRepository<Product> _repository;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- _handler = new DeliveryDateDeletedEventHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Product>();
+ _handler = new DeliveryDateDeletedEventHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var deliveryDate = new DeliveryDate();
- var product = new Product {
- DeliveryDateId = deliveryDate.Id
- };
- await _repository.InsertAsync(product);
- var product2 = new Product {
- DeliveryDateId = deliveryDate.Id
- };
- await _repository.InsertAsync(product2);
- var product3 = new Product {
- DeliveryDateId = "1"
- };
- await _repository.InsertAsync(product3);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var deliveryDate = new DeliveryDate();
+ var product = new Product {
+ DeliveryDateId = deliveryDate.Id
+ };
+ await _repository.InsertAsync(product);
+ var product2 = new Product {
+ DeliveryDateId = deliveryDate.Id
+ };
+ await _repository.InsertAsync(product2);
+ var product3 = new Product {
+ DeliveryDateId = "1"
+ };
+ await _repository.InsertAsync(product3);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<DeliveryDate>(deliveryDate), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.DeliveryDateId == deliveryDate.Id).Count());
- Assert.AreEqual(1, _repository.Table.Where(x => x.DeliveryDateId == "1").Count());
- }
+ //Act
+ await _handler.Handle(new EntityDeleted<DeliveryDate>(deliveryDate), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Where(x => x.DeliveryDateId == deliveryDate.Id).Count());
+ Assert.AreEqual(1, _repository.Table.Where(x => x.DeliveryDateId == "1").Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DiscountDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DiscountDeletedEventHandlerTests.cs
index 4b0d749ae..147bb622b 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DiscountDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/DiscountDeletedEventHandlerTests.cs
@@ -1,120 +1,123 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Discounts;
using Grand.Domain.Vendors;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.Events;
using Grand.Infrastructure.Tests.Caching;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class DiscountDeletedEventHandlerTests
{
- [TestClass()]
- public class DiscountDeletedEventHandlerTests
+ private IRepository<Brand> _brandRepository;
+ private MemoryCacheBase _cacheBase;
+ private IRepository<Category> _categoryRepository;
+ private IRepository<Collection> _collectionRepository;
+ private IRepository<DiscountCoupon> _discountCouponRepository;
+
+ private DiscountDeletedEventHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Product> _productRepository;
+ private IRepository<Vendor> _vendorRepository;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<Product> _productRepository;
- private IRepository<Category> _categoryRepository;
- private IRepository<Brand> _brandRepository;
- private IRepository<Collection> _collectionRepository;
- private IRepository<Vendor> _vendorRepository;
- private IRepository<DiscountCoupon> _discountCouponRepository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
+ _mediatorMock = new Mock<IMediator>();
+ _productRepository = new MongoDBRepositoryTest<Product>();
+ _categoryRepository = new MongoDBRepositoryTest<Category>();
+ _brandRepository = new MongoDBRepositoryTest<Brand>();
+ _collectionRepository = new MongoDBRepositoryTest<Collection>();
+ _vendorRepository = new MongoDBRepositoryTest<Vendor>();
+ _discountCouponRepository = new MongoDBRepositoryTest<DiscountCoupon>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
- private DiscountDeletedEventHandler _handler;
+ _handler = new DiscountDeletedEventHandler(_productRepository, _categoryRepository,
+ _brandRepository, _collectionRepository, _vendorRepository, _discountCouponRepository, _cacheBase);
+ }
- [TestInitialize()]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _productRepository = new MongoDBRepositoryTest<Product>();
- _categoryRepository = new MongoDBRepositoryTest<Category>();
- _brandRepository = new MongoDBRepositoryTest<Brand>();
- _collectionRepository = new MongoDBRepositoryTest<Collection>();
- _vendorRepository = new MongoDBRepositoryTest<Vendor>();
- _discountCouponRepository = new MongoDBRepositoryTest<DiscountCoupon>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
+ [TestMethod]
+ public async Task Handle_Product_Test()
+ {
+ //Arrange
+ var discount = new Discount { DiscountTypeId = DiscountType.AssignedToSkus };
+ var product = new Product();
+ product.AppliedDiscounts.Add(discount.Id);
+ await _productRepository.InsertAsync(product);
+ var product3 = new Product();
+ product3.AppliedDiscounts.Add("1");
+ await _productRepository.InsertAsync(product3);
- _handler = new DiscountDeletedEventHandler(_productRepository, _categoryRepository,
- _brandRepository, _collectionRepository, _vendorRepository, _discountCouponRepository, _cacheBase);
- }
+ //Act
+ await _handler.Handle(new EntityDeleted<Discount>(discount), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _productRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
+ Assert.AreEqual(1, _productRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
+ }
- [TestMethod()]
- public async Task Handle_Product_Test()
- {
- //Arrange
- var discount = new Discount { DiscountTypeId = DiscountType.AssignedToSkus };
- var product = new Product();
- product.AppliedDiscounts.Add(discount.Id);
- await _productRepository.InsertAsync(product);
- var product3 = new Product();
- product3.AppliedDiscounts.Add("1");
- await _productRepository.InsertAsync(product3);
+ [TestMethod]
+ public async Task Handle_Category_Test()
+ {
+ //Arrange
+ var discount = new Discount { DiscountTypeId = DiscountType.AssignedToCategories };
+ var category = new Category();
+ category.AppliedDiscounts.Add(discount.Id);
+ await _categoryRepository.InsertAsync(category);
+ var category3 = new Category();
+ category3.AppliedDiscounts.Add("1");
+ await _categoryRepository.InsertAsync(category3);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Discount>(discount), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _productRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
- Assert.AreEqual(1, _productRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
- }
- [TestMethod()]
- public async Task Handle_Category_Test()
- {
- //Arrange
- var discount = new Discount { DiscountTypeId = DiscountType.AssignedToCategories };
- var category = new Category();
- category.AppliedDiscounts.Add(discount.Id);
- await _categoryRepository.InsertAsync(category);
- var category3 = new Category();
- category3.AppliedDiscounts.Add("1");
- await _categoryRepository.InsertAsync(category3);
+ //Act
+ await _handler.Handle(new EntityDeleted<Discount>(discount), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _categoryRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
+ Assert.AreEqual(1, _categoryRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
+ }
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Discount>(discount), CancellationToken.None);
- //Assert
- Assert.AreEqual(0,_categoryRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
- Assert.AreEqual(1, _categoryRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
- }
+ [TestMethod]
+ public async Task Handle_Collection_Test()
+ {
+ //Arrange
+ var discount = new Discount { DiscountTypeId = DiscountType.AssignedToCollections };
+ var collection = new Collection();
+ collection.AppliedDiscounts.Add(discount.Id);
+ await _collectionRepository.InsertAsync(collection);
+ var collection3 = new Collection();
+ collection3.AppliedDiscounts.Add("1");
+ await _collectionRepository.InsertAsync(collection3);
- [TestMethod()]
- public async Task Handle_Collection_Test()
- {
- //Arrange
- var discount = new Discount { DiscountTypeId = DiscountType.AssignedToCollections };
- var collection = new Collection();
- collection.AppliedDiscounts.Add(discount.Id);
- await _collectionRepository.InsertAsync(collection);
- var collection3 = new Collection();
- collection3.AppliedDiscounts.Add("1");
- await _collectionRepository.InsertAsync(collection3);
+ //Act
+ await _handler.Handle(new EntityDeleted<Discount>(discount), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _collectionRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
+ Assert.AreEqual(1, _collectionRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
+ }
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Discount>(discount), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _collectionRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
- Assert.AreEqual(1, _collectionRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
- }
- [TestMethod()]
- public async Task Handle_Vendor_Test()
- {
- //Arrange
- var discount = new Discount { DiscountTypeId = DiscountType.AssignedToVendors };
- var vendor = new Vendor();
- vendor.AppliedDiscounts.Add(discount.Id);
- await _vendorRepository.InsertAsync(vendor);
- var vendor3 = new Vendor();
- vendor3.AppliedDiscounts.Add("1");
- await _vendorRepository.InsertAsync(vendor3);
+ [TestMethod]
+ public async Task Handle_Vendor_Test()
+ {
+ //Arrange
+ var discount = new Discount { DiscountTypeId = DiscountType.AssignedToVendors };
+ var vendor = new Vendor();
+ vendor.AppliedDiscounts.Add(discount.Id);
+ await _vendorRepository.InsertAsync(vendor);
+ var vendor3 = new Vendor();
+ vendor3.AppliedDiscounts.Add("1");
+ await _vendorRepository.InsertAsync(vendor3);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Discount>(discount), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _vendorRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
- Assert.AreEqual(1, _vendorRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
- }
+ //Act
+ await _handler.Handle(new EntityDeleted<Discount>(discount), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _vendorRepository.Table.Where(x => x.AppliedDiscounts.Contains(discount.Id)).Count());
+ Assert.AreEqual(1, _vendorRepository.Table.Where(x => x.AppliedDiscounts.Contains("1")).Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.cs
index 258be0e82..057ee6d33 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductDeletedEventHandlerTests.cs
@@ -1,65 +1,65 @@
using Grand.Business.Catalog.Events.Handlers;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Seo;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class ProductDeletedEventHandlerTests
{
- [TestClass()]
- public class ProductDeletedEventHandlerTests
- {
- private IRepository<Product> _repository;
- private IRepository<CustomerGroupProduct> _customerGroupProductRepository;
- private IRepository<Customer> _customerRepository;
- private IRepository<EntityUrl> _entityUrlRepository;
- private IRepository<ProductTag> _productTagRepository;
- private IRepository<ProductReview> _productReviewRepository;
- private IRepository<ProductDeleted> _productDeletedRepository;
- private Mock<IProductTagService> _productTagService;
- private ProductDeletedEventHandler _handler;
+ private IRepository<CustomerGroupProduct> _customerGroupProductRepository;
+ private IRepository<Customer> _customerRepository;
+ private IRepository<EntityUrl> _entityUrlRepository;
+ private ProductDeletedEventHandler _handler;
+ private IRepository<ProductDeleted> _productDeletedRepository;
+ private IRepository<ProductReview> _productReviewRepository;
+ private IRepository<ProductTag> _productTagRepository;
+ private Mock<IProductTagService> _productTagService;
+ private IRepository<Product> _repository;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- _customerGroupProductRepository = new MongoDBRepositoryTest<CustomerGroupProduct>();
- _customerRepository = new MongoDBRepositoryTest<Customer>();
- _entityUrlRepository = new MongoDBRepositoryTest<EntityUrl>();
- _productTagRepository = new MongoDBRepositoryTest<ProductTag>();
- _productReviewRepository = new MongoDBRepositoryTest<ProductReview>();
- _productDeletedRepository = new MongoDBRepositoryTest<ProductDeleted>();
- _productTagService = new Mock<IProductTagService>();
- _handler = new ProductDeletedEventHandler(_repository, _customerGroupProductRepository,
- _customerRepository, _entityUrlRepository, _productTagRepository, _productReviewRepository,
- _productDeletedRepository, _productTagService.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Product>();
+ _customerGroupProductRepository = new MongoDBRepositoryTest<CustomerGroupProduct>();
+ _customerRepository = new MongoDBRepositoryTest<Customer>();
+ _entityUrlRepository = new MongoDBRepositoryTest<EntityUrl>();
+ _productTagRepository = new MongoDBRepositoryTest<ProductTag>();
+ _productReviewRepository = new MongoDBRepositoryTest<ProductReview>();
+ _productDeletedRepository = new MongoDBRepositoryTest<ProductDeleted>();
+ _productTagService = new Mock<IProductTagService>();
+ _handler = new ProductDeletedEventHandler(_repository, _customerGroupProductRepository,
+ _customerRepository, _entityUrlRepository, _productTagRepository, _productReviewRepository,
+ _productDeletedRepository, _productTagService.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var product = new Product();
- product.RecommendedProduct.Add("1");
- product.RelatedProducts.Add(new RelatedProduct { ProductId2 = "1" });
- product.CrossSellProduct.Add("1");
- product.SimilarProducts.Add(new SimilarProduct { ProductId2 = "1" });
- await _repository.InsertAsync(product);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Product>(new Product { Id = "1" }), CancellationToken.None);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var product = new Product();
+ product.RecommendedProduct.Add("1");
+ product.RelatedProducts.Add(new RelatedProduct { ProductId2 = "1" });
+ product.CrossSellProduct.Add("1");
+ product.SimilarProducts.Add(new SimilarProduct { ProductId2 = "1" });
+ await _repository.InsertAsync(product);
+ //Act
+ await _handler.Handle(new EntityDeleted<Product>(new Product { Id = "1" }), CancellationToken.None);
- //Assert
- var result = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
- Assert.IsNotNull(result);
- Assert.IsTrue(result.RelatedProducts.Count == 0);
- Assert.IsTrue(result.RecommendedProduct.Count == 0);
- Assert.IsTrue(result.CrossSellProduct.Count == 0);
- Assert.IsTrue(result.SimilarProducts.Count == 0);
- }
+ //Assert
+ var result = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
+ Assert.IsNotNull(result);
+ Assert.IsTrue(result.RelatedProducts.Count == 0);
+ Assert.IsTrue(result.RecommendedProduct.Count == 0);
+ Assert.IsTrue(result.CrossSellProduct.Count == 0);
+ Assert.IsTrue(result.SimilarProducts.Count == 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductPublishEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductPublishEventHandlerTests.cs
index 656764b3d..1faa2ed2c 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductPublishEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/ProductPublishEventHandlerTests.cs
@@ -1,40 +1,43 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Business.Core.Events.Catalog;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class ProductPublishEventHandlerTests
{
- [TestClass()]
- public class ProductPublishEventHandlerTests
- {
+ private Mock<ICacheBase> _casheManagerMock;
- ProductPublishEventHandler handlerPublish;
- ProductUnPublishEventHandler handlerUnPublish;
- private Mock<ICacheBase> _casheManagerMock;
+ private ProductPublishEventHandler handlerPublish;
+ private ProductUnPublishEventHandler handlerUnPublish;
- [TestInitialize()]
- public void Init()
- {
- _casheManagerMock = new Mock<ICacheBase>();
- handlerPublish = new ProductPublishEventHandler(_casheManagerMock.Object);
- handlerUnPublish = new ProductUnPublishEventHandler(_casheManagerMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _casheManagerMock = new Mock<ICacheBase>();
+ handlerPublish = new ProductPublishEventHandler(_casheManagerMock.Object);
+ handlerUnPublish = new ProductUnPublishEventHandler(_casheManagerMock.Object);
+ }
- [TestMethod()]
- public async Task Handle_Publish()
- {
- //Act
- await handlerPublish.Handle(new Core.Events.Catalog.ProductPublishEvent(new Domain.Catalog.Product { ShowOnHomePage = true }), CancellationToken.None);
- _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
+ [TestMethod]
+ public async Task Handle_Publish()
+ {
+ //Act
+ await handlerPublish.Handle(new ProductPublishEvent(new Product { ShowOnHomePage = true }),
+ CancellationToken.None);
+ _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
+ }
- }
- [TestMethod()]
- public async Task Handle_UnPublish()
- {
- //Act
- await handlerUnPublish.Handle(new Core.Events.Catalog.ProductUnPublishEvent(new Domain.Catalog.Product { ShowOnHomePage = true }), CancellationToken.None);
- _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
- }
+ [TestMethod]
+ public async Task Handle_UnPublish()
+ {
+ //Act
+ await handlerUnPublish.Handle(new ProductUnPublishEvent(new Product { ShowOnHomePage = true }),
+ CancellationToken.None);
+ _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/TaxCategoryDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/TaxCategoryDeletedEventHandlerTests.cs
index 138c5c0a3..52ca99f7e 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/TaxCategoryDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/TaxCategoryDeletedEventHandlerTests.cs
@@ -1,48 +1,48 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Tax;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class TaxCategoryDeletedEventHandlerTests
{
- [TestClass()]
- public class TaxCategoryDeletedEventHandlerTests
- {
- private IRepository<Product> _repository;
- private TaxCategoryDeletedEventHandler _handler;
+ private TaxCategoryDeletedEventHandler _handler;
+ private IRepository<Product> _repository;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- _handler = new TaxCategoryDeletedEventHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Product>();
+ _handler = new TaxCategoryDeletedEventHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var taxCategory = new TaxCategory();
- var product = new Product {
- TaxCategoryId = taxCategory.Id
- };
- await _repository.InsertAsync(product);
- var product2 = new Product {
- TaxCategoryId = taxCategory.Id
- };
- await _repository.InsertAsync(product2);
- var product3 = new Product {
- TaxCategoryId = "1"
- };
- await _repository.InsertAsync(product3);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var taxCategory = new TaxCategory();
+ var product = new Product {
+ TaxCategoryId = taxCategory.Id
+ };
+ await _repository.InsertAsync(product);
+ var product2 = new Product {
+ TaxCategoryId = taxCategory.Id
+ };
+ await _repository.InsertAsync(product2);
+ var product3 = new Product {
+ TaxCategoryId = "1"
+ };
+ await _repository.InsertAsync(product3);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<TaxCategory>(taxCategory), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.TaxCategoryId == taxCategory.Id).Count());
- Assert.AreEqual(1, _repository.Table.Where(x => x.TaxCategoryId == "1").Count());
- }
+ //Act
+ await _handler.Handle(new EntityDeleted<TaxCategory>(taxCategory), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Where(x => x.TaxCategoryId == taxCategory.Id).Count());
+ Assert.AreEqual(1, _repository.Table.Where(x => x.TaxCategoryId == "1").Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/UpdateProductOnCartEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/UpdateProductOnCartEventHandlerTests.cs
index 0c6dbfb4c..5979383c3 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/UpdateProductOnCartEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/UpdateProductOnCartEventHandlerTests.cs
@@ -1,49 +1,55 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Business.Core.Events.Catalog;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
-{
- [TestClass()]
- public class UpdateProductOnCartEventHandlerTests
- {
- private IRepository<Customer> _repository;
- private UpdateProductOnCartEventHandler _handler;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Customer>();
- _handler = new UpdateProductOnCartEventHandler(_repository);
- }
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+[TestClass]
+public class UpdateProductOnCartEventHandlerTests
+{
+ private UpdateProductOnCartEventHandler _handler;
+ private IRepository<Customer> _repository;
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Customer>();
+ _handler = new UpdateProductOnCartEventHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var product = new Product();
- var customer = new Customer();
- customer.ShoppingCartItems.Add(new Domain.Orders.ShoppingCartItem {
- ProductId = product.Id,
- IsFreeShipping = !product.IsFreeShipping,
- IsShipEnabled = !product.IsShipEnabled,
- IsTaxExempt = !product.IsTaxExempt,
- IsGiftVoucher = !product.IsGiftVoucher
- });
- //Act
- await _handler.Handle(new Core.Events.Catalog.UpdateProductOnCartEvent(product), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsTaxExempt == product.IsTaxExempt)).Count());
- Assert.AreEqual(0, _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsFreeShipping == product.IsFreeShipping)).Count());
- Assert.AreEqual(0, _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsFreeShipping == product.IsFreeShipping)).Count());
- Assert.AreEqual(0, _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsGiftVoucher == product.IsGiftVoucher)).Count());
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var product = new Product();
+ var customer = new Customer();
+ customer.ShoppingCartItems.Add(new ShoppingCartItem {
+ ProductId = product.Id,
+ IsFreeShipping = !product.IsFreeShipping,
+ IsShipEnabled = !product.IsShipEnabled,
+ IsTaxExempt = !product.IsTaxExempt,
+ IsGiftVoucher = !product.IsGiftVoucher
+ });
+ //Act
+ await _handler.Handle(new UpdateProductOnCartEvent(product), CancellationToken.None);
- }
+ //Assert
+ Assert.AreEqual(0,
+ _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsTaxExempt == product.IsTaxExempt)).Count());
+ Assert.AreEqual(0,
+ _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsFreeShipping == product.IsFreeShipping))
+ .Count());
+ Assert.AreEqual(0,
+ _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsFreeShipping == product.IsFreeShipping))
+ .Count());
+ Assert.AreEqual(0,
+ _repository.Table.Where(x => x.ShoppingCartItems.Any(y => y.IsGiftVoucher == product.IsGiftVoucher))
+ .Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/WarehouseDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/WarehouseDeletedEventHandlerTests.cs
index 1637722cc..5bf337b1b 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/WarehouseDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Events/Handlers/WarehouseDeletedEventHandlerTests.cs
@@ -1,48 +1,48 @@
using Grand.Business.Catalog.Events.Handlers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Shipping;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Events.Handlers
+namespace Grand.Business.Catalog.Tests.Events.Handlers;
+
+[TestClass]
+public class WarehouseDeletedEventHandlerTests
{
- [TestClass()]
- public class WarehouseDeletedEventHandlerTests
- {
- private IRepository<Product> _repository;
- private WarehouseDeletedEventHandler _handler;
+ private WarehouseDeletedEventHandler _handler;
+ private IRepository<Product> _repository;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- _handler = new WarehouseDeletedEventHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Product>();
+ _handler = new WarehouseDeletedEventHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var warehouse = new Warehouse();
- var product = new Product {
- WarehouseId = warehouse.Id
- };
- await _repository.InsertAsync(product);
- var product2 = new Product {
- WarehouseId = warehouse.Id
- };
- await _repository.InsertAsync(product2);
- var product3 = new Product {
- WarehouseId = "1"
- };
- await _repository.InsertAsync(product3);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var warehouse = new Warehouse();
+ var product = new Product {
+ WarehouseId = warehouse.Id
+ };
+ await _repository.InsertAsync(product);
+ var product2 = new Product {
+ WarehouseId = warehouse.Id
+ };
+ await _repository.InsertAsync(product2);
+ var product3 = new Product {
+ WarehouseId = "1"
+ };
+ await _repository.InsertAsync(product3);
- //Act
- await _handler.Handle(new Infrastructure.Events.EntityDeleted<Warehouse>(warehouse), CancellationToken.None);
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x => x.WarehouseId == warehouse.Id).Count());
- Assert.AreEqual(1, _repository.Table.Where(x => x.WarehouseId == "1").Count());
- }
+ //Act
+ await _handler.Handle(new EntityDeleted<Warehouse>(warehouse), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Where(x => x.WarehouseId == warehouse.Id).Count());
+ Assert.AreEqual(1, _repository.Table.Where(x => x.WarehouseId == "1").Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductAttributeExtensionsTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductAttributeExtensionsTests.cs
index a83cf30fe..48aebbce6 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductAttributeExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductAttributeExtensionsTests.cs
@@ -1,81 +1,79 @@
using Grand.Domain.Catalog;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Extensions
+namespace Grand.Business.Catalog.Tests.Extensions;
+
+[TestClass]
+public class ProductAttributeExtensionsTests
{
- [TestClass()]
- public class ProductAttributeExtensionsTests
+ [TestMethod]
+ public void ShouldHaveValues_ReturnExpentedResult()
{
-
- [TestMethod()]
- public void ShouldHaveValues_ReturnExpentedResult()
- {
- var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
- var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
- var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
- var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
- var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
- ProductAttributeMapping pam6 = null;
- Assert.AreEqual(false, pam.ShouldHaveValues());
- Assert.AreEqual(false, pam2.ShouldHaveValues());
- Assert.AreEqual(false, pam3.ShouldHaveValues());
- Assert.AreEqual(false, pam4.ShouldHaveValues());
- Assert.AreEqual(false, pam6.ShouldHaveValues());
- Assert.AreEqual(true, pam5.ShouldHaveValues());
- }
+ var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
+ var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
+ var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
+ var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
+ var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
+ ProductAttributeMapping pam6 = null;
+ Assert.AreEqual(false, pam.ShouldHaveValues());
+ Assert.AreEqual(false, pam2.ShouldHaveValues());
+ Assert.AreEqual(false, pam3.ShouldHaveValues());
+ Assert.AreEqual(false, pam4.ShouldHaveValues());
+ Assert.AreEqual(false, pam6.ShouldHaveValues());
+ Assert.AreEqual(true, pam5.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ValidationRulesAllowed_ReturnExpentedResult()
- {
- var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
- var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
- var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
- var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
- var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
- ProductAttributeMapping pam6 = null;
- Assert.AreEqual(true, pam.ValidationRulesAllowed());
- Assert.AreEqual(true, pam2.ValidationRulesAllowed());
- Assert.AreEqual(true, pam4.ValidationRulesAllowed());
- Assert.AreEqual(false, pam3.ValidationRulesAllowed());
- Assert.AreEqual(false, pam6.ValidationRulesAllowed());
- Assert.AreEqual(false, pam5.ValidationRulesAllowed());
- }
+ [TestMethod]
+ public void ValidationRulesAllowed_ReturnExpentedResult()
+ {
+ var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
+ var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
+ var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
+ var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
+ var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
+ ProductAttributeMapping pam6 = null;
+ Assert.AreEqual(true, pam.ValidationRulesAllowed());
+ Assert.AreEqual(true, pam2.ValidationRulesAllowed());
+ Assert.AreEqual(true, pam4.ValidationRulesAllowed());
+ Assert.AreEqual(false, pam3.ValidationRulesAllowed());
+ Assert.AreEqual(false, pam6.ValidationRulesAllowed());
+ Assert.AreEqual(false, pam5.ValidationRulesAllowed());
+ }
- [TestMethod()]
- public void CanBeUsedAsCondition_ReturnExpentedResult()
- {
- var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
- var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
- var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
- var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
- var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
- ProductAttributeMapping pam6 = null;
- Assert.AreEqual(false, pam.CanBeUsedAsCondition());
- Assert.AreEqual(false, pam2.CanBeUsedAsCondition());
- Assert.AreEqual(false, pam4.CanBeUsedAsCondition());
- Assert.AreEqual(false, pam3.CanBeUsedAsCondition());
- Assert.AreEqual(false, pam6.CanBeUsedAsCondition());
- Assert.AreEqual(true, pam5.CanBeUsedAsCondition());
- }
+ [TestMethod]
+ public void CanBeUsedAsCondition_ReturnExpentedResult()
+ {
+ var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
+ var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
+ var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
+ var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
+ var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
+ ProductAttributeMapping pam6 = null;
+ Assert.AreEqual(false, pam.CanBeUsedAsCondition());
+ Assert.AreEqual(false, pam2.CanBeUsedAsCondition());
+ Assert.AreEqual(false, pam4.CanBeUsedAsCondition());
+ Assert.AreEqual(false, pam3.CanBeUsedAsCondition());
+ Assert.AreEqual(false, pam6.CanBeUsedAsCondition());
+ Assert.AreEqual(true, pam5.CanBeUsedAsCondition());
+ }
- [TestMethod()]
- public void IsNonCombinable_ReturnExpentedResult()
- {
- var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
- var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
- var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
- var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
- var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
- ProductAttributeMapping pam6 = null;
- var pam7 = new ProductAttributeMapping { Combination = true };
- Assert.AreEqual(true, pam.IsNonCombinable());
- Assert.AreEqual(true, pam2.IsNonCombinable());
- Assert.AreEqual(true, pam4.IsNonCombinable());
- Assert.AreEqual(true, pam3.IsNonCombinable());
- Assert.AreEqual(false, pam6.IsNonCombinable());
- Assert.AreEqual(true, pam5.IsNonCombinable());
- Assert.AreEqual(false, pam7.IsNonCombinable());
- }
+ [TestMethod]
+ public void IsNonCombinable_ReturnExpentedResult()
+ {
+ var pam = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.TextBox };
+ var pam2 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
+ var pam3 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.Datepicker };
+ var pam4 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.FileUpload };
+ var pam5 = new ProductAttributeMapping { AttributeControlTypeId = AttributeControlType.DropdownList };
+ ProductAttributeMapping pam6 = null;
+ var pam7 = new ProductAttributeMapping { Combination = true };
+ Assert.AreEqual(true, pam.IsNonCombinable());
+ Assert.AreEqual(true, pam2.IsNonCombinable());
+ Assert.AreEqual(true, pam4.IsNonCombinable());
+ Assert.AreEqual(true, pam3.IsNonCombinable());
+ Assert.AreEqual(false, pam6.IsNonCombinable());
+ Assert.AreEqual(true, pam5.IsNonCombinable());
+ Assert.AreEqual(false, pam7.IsNonCombinable());
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductExtensionsTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductExtensionsTests.cs
index 5b90caf76..5f90a94ef 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Extensions/ProductExtensionsTests.cs
@@ -1,26 +1,24 @@
using Grand.Domain.Catalog;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Extensions
+namespace Grand.Business.Catalog.Tests.Extensions;
+
+[TestClass]
+public class ProductExtensionsTests
{
- [TestClass()]
- public class ProductExtensionsTests
+ [TestMethod]
+ public void Can_parse_allowed_quantities()
{
+ //simple parsing witohut unallowed word-characters
+ var product = new Product { AllowedQuantities = "1,3,42,1,dsad,123,d22,d,122223" };
- [TestMethod()]
- public void Can_parse_allowed_quantities()
- {
- //simple parsing witohut unallowed word-characters
- var product = new Product { AllowedQuantities = "1,3,42,1,dsad,123,d22,d,122223" };
-
- var result = product.ParseAllowedQuantities();
- Assert.AreEqual(6, result.Length);
- Assert.AreEqual(1, result[0]);
- Assert.AreEqual(3, result[1]);
- Assert.AreEqual(42, result[2]);
- Assert.AreEqual(1, result[3]);
- Assert.AreEqual(123, result[4]);
- Assert.AreEqual(122223, result[5]);
- }
+ var result = product.ParseAllowedQuantities();
+ Assert.AreEqual(6, result.Length);
+ Assert.AreEqual(1, result[0]);
+ Assert.AreEqual(3, result[1]);
+ Assert.AreEqual(42, result[2]);
+ Assert.AreEqual(1, result[3]);
+ Assert.AreEqual(123, result[4]);
+ Assert.AreEqual(122223, result[5]);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs b/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs
index a1b0ab69d..d70f33fe7 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs
@@ -1,81 +1,80 @@
using Grand.Business.Catalog.Commands;
using Grand.Business.Core.Commands.Catalog;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Driver;
using Moq;
-namespace Grand.Business.Catalog.Tests.Handlers
-{
- [TestClass()]
- public class UpdateProductReviewTotalsCommandHandlerTest
- {
- private IRepository<Product> _productRepository;
- private Mock<ICacheBase> _cacheBaseMock;
- private UpdateProductReviewTotalsCommandHandler _updateProductReviewTotalsCommandHandler;
- private Mock<IMongoCollection<Product>> _mongoCollectionMock;
- private Mock<IProductReviewService> _productReviewServiceMock;
+namespace Grand.Business.Catalog.Tests.Handlers;
+[TestClass]
+public class UpdateProductReviewTotalsCommandHandlerTest
+{
+ private Mock<ICacheBase> _cacheBaseMock;
+ private Mock<IMongoCollection<Product>> _mongoCollectionMock;
+ private IRepository<Product> _productRepository;
+ private Mock<IProductReviewService> _productReviewServiceMock;
+ private UpdateProductReviewTotalsCommandHandler _updateProductReviewTotalsCommandHandler;
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "";
- var reviews = new List<ProductReview> {
- new ProductReview { Id = "1", ReplyText = "text1"},
- new ProductReview { Id = "2", ReplyText = "text2"}};
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = "";
- _mongoCollectionMock = new Mock<IMongoCollection<Product>>();
- _mongoCollectionMock.SetupAllProperties();
- _mongoCollectionMock.Setup(x => x.UpdateOneAsync(It.IsAny<FilterDefinition<Product>>(),
- It.IsAny<UpdateDefinition<Product>>(),
- It.IsAny<UpdateOptions>(),
- default));
+ var reviews = new List<ProductReview> {
+ new() { Id = "1", ReplyText = "text1" },
+ new() { Id = "2", ReplyText = "text2" }
+ };
- _productRepository = new MongoDBRepositoryTest<Product>();
- _cacheBaseMock = new Mock<ICacheBase>();
+ _mongoCollectionMock = new Mock<IMongoCollection<Product>>();
+ _mongoCollectionMock.SetupAllProperties();
+ _mongoCollectionMock.Setup(x => x.UpdateOneAsync(It.IsAny<FilterDefinition<Product>>(),
+ It.IsAny<UpdateDefinition<Product>>(),
+ It.IsAny<UpdateOptions>(),
+ default));
- _productReviewServiceMock = new Mock<IProductReviewService>();
- IPagedList<ProductReview> pagedListReviews = new PagedList<ProductReview>(reviews, 0, 234567);
- _productReviewServiceMock.Setup(x => x.GetAllProductReviews(null,
- null,
- null,
- null,
- null,
- null,
- It.IsAny<string>(), 0, It.IsAny<int>())).Returns(Task.FromResult(pagedListReviews));
+ _productRepository = new MongoDBRepositoryTest<Product>();
+ _cacheBaseMock = new Mock<ICacheBase>();
- _updateProductReviewTotalsCommandHandler = new UpdateProductReviewTotalsCommandHandler(
- _productRepository,
- _productReviewServiceMock.Object,
- _cacheBaseMock.Object);
- }
+ _productReviewServiceMock = new Mock<IProductReviewService>();
+ IPagedList<ProductReview> pagedListReviews = new PagedList<ProductReview>(reviews, 0, 234567);
+ _productReviewServiceMock.Setup(x => x.GetAllProductReviews(null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ It.IsAny<string>(), 0, It.IsAny<int>())).Returns(Task.FromResult(pagedListReviews));
- [TestMethod()]
- public async Task InsertProduct_NullArgument_ThrowException()
- {
- var request = new UpdateProductReviewTotalsCommand();
+ _updateProductReviewTotalsCommandHandler = new UpdateProductReviewTotalsCommandHandler(
+ _productRepository,
+ _productReviewServiceMock.Object,
+ _cacheBaseMock.Object);
+ }
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(
- async () => await _updateProductReviewTotalsCommandHandler.Handle(request, default));
- }
+ [TestMethod]
+ public async Task InsertProduct_NullArgument_ThrowException()
+ {
+ var request = new UpdateProductReviewTotalsCommand();
- [TestMethod()]
- public async Task UpdateProductReviews_ValidArgument_InvokeRepositoryAndCache()
- {
- var request = new UpdateProductReviewTotalsCommand { Product = new Product() };
- await _updateProductReviewTotalsCommandHandler.Handle(request, default);
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _updateProductReviewTotalsCommandHandler.Handle(request, default));
+ }
- _productReviewServiceMock.Verify(x => x.GetAllProductReviews(null, null, null, null, null,
- null, It.IsAny<string>(), 0, It.IsAny<int>()), Times.Once);
+ [TestMethod]
+ public async Task UpdateProductReviews_ValidArgument_InvokeRepositoryAndCache()
+ {
+ var request = new UpdateProductReviewTotalsCommand { Product = new Product() };
+ await _updateProductReviewTotalsCommandHandler.Handle(request, default);
- }
+ _productReviewServiceMock.Verify(x => x.GetAllProductReviews(null, null, null, null, null,
+ null, It.IsAny<string>(), 0, It.IsAny<int>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs
index 9ae7d3d2a..344352205 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs
@@ -1,37 +1,40 @@
using Grand.Business.Catalog.Queries.Handlers;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Queries.Handlers
+namespace Grand.Business.Catalog.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetPersonalizedProductsQueryHandlerTests
{
- [TestClass()]
- public class GetPersonalizedProductsQueryHandlerTests
- {
- private Mock<ICacheBase> _casheManagerMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IRepository<CustomerProduct>> _customerProductRepositoryMock;
+ private Mock<ICacheBase> _casheManagerMock;
+ private Mock<IRepository<CustomerProduct>> _customerProductRepositoryMock;
+ private Mock<IProductService> _productServiceMock;
- private GetPersonalizedProductsQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _casheManagerMock = new Mock<ICacheBase>();
- _productServiceMock = new Mock<IProductService>();
- _customerProductRepositoryMock = new Mock<IRepository<CustomerProduct>>();
+ private GetPersonalizedProductsQueryHandler handler;
- handler = new GetPersonalizedProductsQueryHandler(_productServiceMock.Object, _casheManagerMock.Object, _customerProductRepositoryMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _casheManagerMock = new Mock<ICacheBase>();
+ _productServiceMock = new Mock<IProductService>();
+ _customerProductRepositoryMock = new Mock<IRepository<CustomerProduct>>();
+
+ handler = new GetPersonalizedProductsQueryHandler(_productServiceMock.Object, _casheManagerMock.Object,
+ _customerProductRepositoryMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- await handler.Handle(new Core.Queries.Catalog.GetPersonalizedProductsQuery(), CancellationToken.None);
- _casheManagerMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Product>>>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ await handler.Handle(new GetPersonalizedProductsQuery(), CancellationToken.None);
+ _casheManagerMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Product>>>>()),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs
index 15d0233c4..dd2c30ced 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs
@@ -1,34 +1,36 @@
using Grand.Business.Catalog.Queries.Handlers;
-using Grand.Domain.Customers;
+using Grand.Business.Core.Queries.Catalog;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Queries.Handlers
+namespace Grand.Business.Catalog.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetPriceByCustomerProductQueryHandlerTests
{
- [TestClass()]
- public class GetPriceByCustomerProductQueryHandlerTests
- {
- private Mock<ICacheBase> _casheManagerMock;
- private Mock<IRepository<CustomerProductPrice>> _customerProductPriceRepositoryMock;
+ private Mock<ICacheBase> _casheManagerMock;
+ private Mock<IRepository<CustomerProductPrice>> _customerProductPriceRepositoryMock;
- private GetPriceByCustomerProductQueryHandler handler;
-
- [TestInitialize()]
- public void Init()
- {
- _casheManagerMock = new Mock<ICacheBase>();
- _customerProductPriceRepositoryMock = new Mock<IRepository<CustomerProductPrice>>();
+ private GetPriceByCustomerProductQueryHandler handler;
- handler = new GetPriceByCustomerProductQueryHandler(_casheManagerMock.Object, _customerProductPriceRepositoryMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _casheManagerMock = new Mock<ICacheBase>();
+ _customerProductPriceRepositoryMock = new Mock<IRepository<CustomerProductPrice>>();
+
+ handler = new GetPriceByCustomerProductQueryHandler(_casheManagerMock.Object,
+ _customerProductPriceRepositoryMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- await handler.Handle(new Core.Queries.Catalog.GetPriceByCustomerProductQuery(), CancellationToken.None);
- _casheManagerMock.Verify(c => c.Get(It.IsAny<string>(), It.IsAny<Func<(CustomerProductPrice, bool)>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ await handler.Handle(new GetPriceByCustomerProductQuery(), CancellationToken.None);
+ _casheManagerMock.Verify(c => c.Get(It.IsAny<string>(), It.IsAny<Func<(CustomerProductPrice, bool)>>()),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs
index 227e6887c..61f8bb725 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs
@@ -1,33 +1,33 @@
using Grand.Business.Catalog.Queries.Handlers;
-using Grand.Domain.Catalog;
+using Grand.Business.Core.Queries.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Queries.Handlers
+namespace Grand.Business.Catalog.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetProductArchByIdQueryHandlerTests
{
- [TestClass()]
- public class GetProductArchByIdQueryHandlerTests
- {
- private Mock<IRepository<ProductDeleted>> _productDeletedRepository;
+ private Mock<IRepository<ProductDeleted>> _productDeletedRepository;
- private GetProductArchByIdQueryHandler handler;
-
- [TestInitialize()]
- public void Init()
- {
- _productDeletedRepository = new Mock<IRepository<ProductDeleted>>();
+ private GetProductArchByIdQueryHandler handler;
- handler = new GetProductArchByIdQueryHandler(_productDeletedRepository.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _productDeletedRepository = new Mock<IRepository<ProductDeleted>>();
+
+ handler = new GetProductArchByIdQueryHandler(_productDeletedRepository.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Act
- var result = await handler.Handle(new Core.Queries.Catalog.GetProductArchByIdQuery(), CancellationToken.None);
- //Assert
- Assert.IsNull(result);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Act
+ var result = await handler.Handle(new GetProductArchByIdQuery(), CancellationToken.None);
+ //Assert
+ Assert.IsNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs
index 1b7d9016e..42d2efc3e 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs
@@ -1,43 +1,44 @@
using Grand.Business.Catalog.Queries.Handlers;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Queries.Handlers
+namespace Grand.Business.Catalog.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetRecommendedProductsQueryHandlerTests
{
- [TestClass()]
- public class GetRecommendedProductsQueryHandlerTests
- {
- private Mock<ICacheBase> _casheManagerMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IRepository<CustomerGroupProduct>> _customerGroupProductRepositoryMock;
+ private Mock<ICacheBase> _casheManagerMock;
+ private Mock<IRepository<CustomerGroupProduct>> _customerGroupProductRepositoryMock;
+ private Mock<IProductService> _productServiceMock;
- private GetRecommendedProductsQueryHandler handler;
+ private GetRecommendedProductsQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _casheManagerMock = new Mock<ICacheBase>();
- _productServiceMock = new Mock<IProductService>();
- _customerGroupProductRepositoryMock = new Mock<IRepository<CustomerGroupProduct>>();
+ [TestInitialize]
+ public void Init()
+ {
+ _casheManagerMock = new Mock<ICacheBase>();
+ _productServiceMock = new Mock<IProductService>();
+ _customerGroupProductRepositoryMock = new Mock<IRepository<CustomerGroupProduct>>();
- handler = new GetRecommendedProductsQueryHandler(_productServiceMock.Object, _casheManagerMock.Object, _customerGroupProductRepositoryMock.Object);
- }
+ handler = new GetRecommendedProductsQueryHandler(_productServiceMock.Object, _casheManagerMock.Object,
+ _customerGroupProductRepositoryMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- var getRecommendedProductsQuery = new Core.Queries.Catalog.GetRecommendedProductsQuery
- {
- CustomerGroupIds = ["1"],
- StoreId = "1"
- };
- await handler.Handle(getRecommendedProductsQuery, CancellationToken.None);
- _casheManagerMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Product>>>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ var getRecommendedProductsQuery = new GetRecommendedProductsQuery {
+ CustomerGroupIds = ["1"],
+ StoreId = "1"
+ };
+ await handler.Handle(getRecommendedProductsQuery, CancellationToken.None);
+ _casheManagerMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Product>>>>()),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs
index 59160ff88..a30d38b03 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs
@@ -1,39 +1,42 @@
using Grand.Business.Catalog.Queries.Handlers;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Queries.Handlers
+namespace Grand.Business.Catalog.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetSearchProductsQueryHandlerTests
{
- [TestClass()]
- public class GetSearchProductsQueryHandlerTests
+ private IRepository<Product> _repository;
+ private GetSearchProductsQueryHandler handler;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<Product> _repository;
- private GetSearchProductsQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- handler = new GetSearchProductsQueryHandler(_repository, new Mock<ISpecificationAttributeService>().Object, new CatalogSettings { IgnoreFilterableSpecAttributeOption = true}, new AccessControlConfig());
- }
+ _repository = new MongoDBRepositoryTest<Product>();
+ handler = new GetSearchProductsQueryHandler(_repository, new Mock<ISpecificationAttributeService>().Object,
+ new CatalogSettings { IgnoreFilterableSpecAttributeOption = true }, new AccessControlConfig());
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- await _repository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
- var searchProductsQuery = new Core.Queries.Catalog.GetSearchProductsQuery {
- Customer = new Domain.Customers.Customer()
- };
- //Act
- var result = await handler.Handle(searchProductsQuery, CancellationToken.None);
- //Arrange
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
+ var searchProductsQuery = new GetSearchProductsQuery {
+ Customer = new Customer()
+ };
+ //Act
+ var result = await handler.Handle(searchProductsQuery, CancellationToken.None);
+ //Arrange
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs
index 1b6086b71..6d76a5202 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs
@@ -1,42 +1,44 @@
using Grand.Business.Catalog.Queries.Handlers;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Queries.Handlers
+namespace Grand.Business.Catalog.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetSuggestedProductsQueryHandlerTests
{
- [TestClass()]
- public class GetSuggestedProductsQueryHandlerTests
- {
- private Mock<ICacheBase> _casheManagerMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IRepository<CustomerTagProduct>> _customerGroupProductRepositoryMock;
+ private Mock<ICacheBase> _casheManagerMock;
+ private Mock<IRepository<CustomerTagProduct>> _customerGroupProductRepositoryMock;
+ private Mock<IProductService> _productServiceMock;
- private GetSuggestedProductsQueryHandler handler;
+ private GetSuggestedProductsQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _casheManagerMock = new Mock<ICacheBase>();
- _productServiceMock = new Mock<IProductService>();
- _customerGroupProductRepositoryMock = new Mock<IRepository<CustomerTagProduct>>();
+ [TestInitialize]
+ public void Init()
+ {
+ _casheManagerMock = new Mock<ICacheBase>();
+ _productServiceMock = new Mock<IProductService>();
+ _customerGroupProductRepositoryMock = new Mock<IRepository<CustomerTagProduct>>();
- handler = new GetSuggestedProductsQueryHandler(_productServiceMock.Object, _casheManagerMock.Object, _customerGroupProductRepositoryMock.Object);
- }
+ handler = new GetSuggestedProductsQueryHandler(_productServiceMock.Object, _casheManagerMock.Object,
+ _customerGroupProductRepositoryMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- var suggestedProductsQuery = new Core.Queries.Catalog.GetSuggestedProductsQuery {
- CustomerTagIds = ["1"],
- ProductsNumber = 10
- };
- await handler.Handle(suggestedProductsQuery, CancellationToken.None);
- _casheManagerMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Product>>>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ var suggestedProductsQuery = new GetSuggestedProductsQuery {
+ CustomerTagIds = ["1"],
+ ProductsNumber = 10
+ };
+ await handler.Handle(suggestedProductsQuery, CancellationToken.None);
+ _casheManagerMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Product>>>>()),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs
index a84f4dbdc..f8a749417 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs
@@ -1,32 +1,33 @@
using Grand.Business.Catalog.Queries.Handlers;
-using Grand.Data.Tests.MongoDb;
+using Grand.Business.Core.Queries.Catalog;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Vendors;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Queries.Handlers
+namespace Grand.Business.Catalog.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetVendorByIdQueryHandlerTests
{
- [TestClass()]
- public class GetVendorByIdQueryHandlerTests
+ private IRepository<Vendor> _repository;
+ private GetVendorByIdQueryHandler handler;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<Vendor> _repository;
- private GetVendorByIdQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Vendor>();
- handler = new GetVendorByIdQueryHandler(_repository);
- }
+ _repository = new MongoDBRepositoryTest<Vendor>();
+ handler = new GetVendorByIdQueryHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- await _repository.InsertAsync(new Vendor { Id = "1" });
- //Act
- var result = await handler.Handle(new Core.Queries.Catalog.GetVendorByIdQuery { Id = "1" }, CancellationToken.None);
- //Arrange
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new Vendor { Id = "1" });
+ //Act
+ var result = await handler.Handle(new GetVendorByIdQuery { Id = "1" }, CancellationToken.None);
+ //Arrange
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandLayoutServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandLayoutServiceTests.cs
index e72e64fe1..7d9b69c9c 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandLayoutServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandLayoutServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Catalog.Services.Brands;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,105 +9,104 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Brands
+namespace Grand.Business.Catalog.Tests.Services.Brands;
+
+[TestClass]
+public class BrandLayoutServiceTests
{
- [TestClass()]
- public class BrandLayoutServiceTests
+ private BrandLayoutService _brandLayoutService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<BrandLayout> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<BrandLayout>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _brandLayoutService = new BrandLayoutService(_repository, _cacheBase, _mediatorMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task GetAllBrandLayoutsTest()
+ {
+ //Arrange
+ await _brandLayoutService.InsertBrandLayout(new BrandLayout());
+ await _brandLayoutService.InsertBrandLayout(new BrandLayout());
+ await _brandLayoutService.InsertBrandLayout(new BrandLayout());
+
+ //Act
+ var layouts = await _brandLayoutService.GetAllBrandLayouts();
+
+ //Assert
+ Assert.AreEqual(3, layouts.Count);
+ }
+
+ [TestMethod]
+ public async Task GetBrandLayoutByIdTest()
+ {
+ //Arrange
+ var brandLayout = new BrandLayout {
+ Name = "test"
+ };
+ await _brandLayoutService.InsertBrandLayout(brandLayout);
+
+ //Act
+ var layout = await _brandLayoutService.GetBrandLayoutById(brandLayout.Id);
+
+ //Assert
+ Assert.IsNotNull(layout);
+ Assert.AreEqual("test", layout.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertBrandLayoutTest()
+ {
+ //Act
+ await _brandLayoutService.InsertBrandLayout(new BrandLayout());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateBrandLayoutTest()
+ {
+ //Arrange
+ var categoryLayout = new BrandLayout {
+ Name = "test"
+ };
+ await _brandLayoutService.InsertBrandLayout(categoryLayout);
+ categoryLayout.Name = "test2";
+
+ //Act
+ await _brandLayoutService.UpdateBrandLayout(categoryLayout);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
+ }
+
+ [TestMethod]
+ public async Task DeleteBrandLayoutTest()
{
- private IRepository<BrandLayout> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private BrandLayoutService _brandLayoutService;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<BrandLayout>();
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _brandLayoutService = new BrandLayoutService(_repository, _cacheBase, _mediatorMock.Object);
- }
-
-
- [TestMethod()]
- public async Task GetAllBrandLayoutsTest()
- {
- //Arrange
- await _brandLayoutService.InsertBrandLayout(new BrandLayout());
- await _brandLayoutService.InsertBrandLayout(new BrandLayout());
- await _brandLayoutService.InsertBrandLayout(new BrandLayout());
-
- //Act
- var layouts = await _brandLayoutService.GetAllBrandLayouts();
-
- //Assert
- Assert.AreEqual(3, layouts.Count);
- }
-
- [TestMethod()]
- public async Task GetBrandLayoutByIdTest()
- {
- //Arrange
- var brandLayout = new BrandLayout {
- Name = "test"
- };
- await _brandLayoutService.InsertBrandLayout(brandLayout);
-
- //Act
- var layout = await _brandLayoutService.GetBrandLayoutById(brandLayout.Id);
-
- //Assert
- Assert.IsNotNull(layout);
- Assert.AreEqual("test", layout.Name);
- }
-
- [TestMethod()]
- public async Task InsertBrandLayoutTest()
- {
- //Act
- await _brandLayoutService.InsertBrandLayout(new BrandLayout());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateBrandLayoutTest()
- {
- //Arrange
- var categoryLayout = new BrandLayout {
- Name = "test"
- };
- await _brandLayoutService.InsertBrandLayout(categoryLayout);
- categoryLayout.Name = "test2";
-
- //Act
- await _brandLayoutService.UpdateBrandLayout(categoryLayout);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
-
- [TestMethod()]
- public async Task DeleteBrandLayoutTest()
- {
-
- //Arrange
- var brandLayout1 = new BrandLayout {
- Name = "test1"
- };
- await _brandLayoutService.InsertBrandLayout(brandLayout1);
- var brandLayout2 = new BrandLayout {
- Name = "test2"
- };
- await _brandLayoutService.InsertBrandLayout(brandLayout2);
-
- //Act
- await _brandLayoutService.DeleteBrandLayout(brandLayout1);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
- Assert.AreEqual(1, _repository.Table.Count());
- }
+ //Arrange
+ var brandLayout1 = new BrandLayout {
+ Name = "test1"
+ };
+ await _brandLayoutService.InsertBrandLayout(brandLayout1);
+ var brandLayout2 = new BrandLayout {
+ Name = "test2"
+ };
+ await _brandLayoutService.InsertBrandLayout(brandLayout2);
+
+ //Act
+ await _brandLayoutService.DeleteBrandLayout(brandLayout1);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
+ Assert.AreEqual(1, _repository.Table.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs
index 4f3b1bb00..24c7605a8 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Brands/BrandServiceTests.cs
@@ -1,8 +1,9 @@
using Grand.Business.Catalog.Services.Brands;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -12,132 +13,133 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Brands
+namespace Grand.Business.Catalog.Tests.Services.Brands;
+
+[TestClass]
+public class BrandServiceTests
{
- [TestClass()]
- public class BrandServiceTests
+ private BrandService _brandService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Brand> _repository;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _repository = new MongoDBRepositoryTest<Brand>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _brandService = new BrandService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object,
+ new AccessControlConfig());
+ }
+
+
+ [TestMethod]
+ public async Task GetAllBrandsTest()
+ {
+ //Arrange
+ await _brandService.InsertBrand(new Brand { Published = true });
+ await _brandService.InsertBrand(new Brand { Published = true });
+ await _brandService.InsertBrand(new Brand { Published = true });
+
+ //Act
+ var brand = await _brandService.GetAllBrands();
+
+ //Assert
+ Assert.AreEqual(3, brand.Count);
+ }
+
+ [TestMethod]
+ public async Task GetBrandByIdTest()
+ {
+ //Arrange
+ var brand = new Brand {
+ Name = "test"
+ };
+ await _brandService.InsertBrand(brand);
+
+ //Act
+ var layout = await _brandService.GetBrandById(brand.Id);
+
+ //Assert
+ Assert.IsNotNull(layout);
+ Assert.AreEqual("test", layout.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertBrandTest()
+ {
+ //Act
+ await _brandService.InsertBrand(new Brand());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateBrandTest()
+ {
+ //Arrange
+ var brand = new Brand {
+ Name = "test"
+ };
+ await _brandService.InsertBrand(brand);
+ brand.Name = "test2";
+
+ //Act
+ await _brandService.UpdateBrand(brand);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
+ }
+
+ [TestMethod]
+ public async Task DeleteBrandTest()
+ {
+ //Arrange
+ var brand1 = new Brand {
+ Name = "test1"
+ };
+ await _brandService.InsertBrand(brand1);
+ var brand2 = new Brand {
+ Name = "test2"
+ };
+ await _brandService.InsertBrand(brand2);
+
+ //Act
+ await _brandService.DeleteBrand(brand1);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
+ Assert.AreEqual(1, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetAllBrandsByDiscountTest()
{
- private IRepository<Brand> _repository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private BrandService _brandService;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
-
- _repository = new MongoDBRepositoryTest<Brand>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _brandService = new BrandService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object, new AccessControlConfig());
- }
-
-
- [TestMethod()]
- public async Task GetAllBrandsTest()
- {
- //Arrange
- await _brandService.InsertBrand(new Brand { Published = true });
- await _brandService.InsertBrand(new Brand { Published = true });
- await _brandService.InsertBrand(new Brand { Published = true });
-
- //Act
- var brand = await _brandService.GetAllBrands();
-
- //Assert
- Assert.AreEqual(3, brand.Count);
- }
-
- [TestMethod()]
- public async Task GetBrandByIdTest()
- {
- //Arrange
- var brand = new Brand {
- Name = "test"
- };
- await _brandService.InsertBrand(brand);
-
- //Act
- var layout = await _brandService.GetBrandById(brand.Id);
-
- //Assert
- Assert.IsNotNull(layout);
- Assert.AreEqual("test", layout.Name);
- }
-
- [TestMethod()]
- public async Task InsertBrandTest()
- {
- //Act
- await _brandService.InsertBrand(new Brand());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateBrandTest()
- {
- //Arrange
- var brand = new Brand {
- Name = "test"
- };
- await _brandService.InsertBrand(brand);
- brand.Name = "test2";
-
- //Act
- await _brandService.UpdateBrand(brand);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
-
- [TestMethod()]
- public async Task DeleteBrandTest()
- {
- //Arrange
- var brand1 = new Brand {
- Name = "test1"
- };
- await _brandService.InsertBrand(brand1);
- var brand2 = new Brand {
- Name = "test2"
- };
- await _brandService.InsertBrand(brand2);
-
- //Act
- await _brandService.DeleteBrand(brand1);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
- Assert.AreEqual(1, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetAllBrandsByDiscountTest()
- {
- //Arrange
- var brand1 = new Brand {
- Name = "test1"
- };
- await _brandService.InsertBrand(brand1);
- var brand2 = new Brand {
- Name = "test2"
- };
- brand2.AppliedDiscounts.Add("disc1");
-
- await _brandService.InsertBrand(brand2);
-
- //Act
- var result = await _brandService.GetAllBrandsByDiscount("disc1");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.Count);
- }
+ //Arrange
+ var brand1 = new Brand {
+ Name = "test1"
+ };
+ await _brandService.InsertBrand(brand1);
+ var brand2 = new Brand {
+ Name = "test2"
+ };
+ brand2.AppliedDiscounts.Add("disc1");
+
+ await _brandService.InsertBrand(brand2);
+
+ //Act
+ var result = await _brandService.GetAllBrandsByDiscount("disc1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceDbTest.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceDbTest.cs
index 85172f20a..2ed4c4168 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceDbTest.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceDbTest.cs
@@ -1,7 +1,7 @@
using Grand.Business.Catalog.Services.Categories;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,120 +9,121 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Categories
+namespace Grand.Business.Catalog.Tests.Services.Categories;
+
+[TestClass]
+public class CategoryLayoutServiceDbTest
{
- [TestClass()]
- public class CategoryLayoutServiceDbTest
+ private MemoryCacheBase _cacheBase;
+ private CategoryLayoutService _categoryLayoutService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CategoryLayout> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<CategoryLayout>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _categoryLayoutService = new CategoryLayoutService(_repository, _cacheBase, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetCategoryLayoutById()
+ {
+ //Arrange
+ var categoryLayout1 = new CategoryLayout {
+ Name = "test1"
+ };
+ await _categoryLayoutService.InsertCategoryLayout(categoryLayout1);
+
+ //Assert
+ var layout = await _categoryLayoutService.GetCategoryLayoutById(categoryLayout1.Id);
+
+ //Act
+ Assert.IsNotNull(layout);
+ Assert.AreEqual("test1", layout.Name);
+ }
+
+ [TestMethod]
+ public async Task GetAllCategoryLayouts()
+ {
+ //Arrange
+ await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
+ await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
+ await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
+
+ //Act
+ var layouts = await _categoryLayoutService.GetAllCategoryLayouts();
+
+ //Assert
+ Assert.AreEqual(3, layouts.Count);
+ }
+
+ [TestMethod]
+ public async Task DeleteCategoryLayout()
+ {
+ //Arrange
+ var categoryLayout1 = new CategoryLayout {
+ Name = "test1"
+ };
+ await _categoryLayoutService.InsertCategoryLayout(categoryLayout1);
+ var categoryLayout2 = new CategoryLayout {
+ Name = "test2"
+ };
+ await _categoryLayoutService.InsertCategoryLayout(categoryLayout2);
+
+ //Act
+ await _categoryLayoutService.DeleteCategoryLayout(categoryLayout1);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
+ Assert.AreEqual(1, _repository.Table.Count());
+ }
+
+
+ [TestMethod]
+ public async Task InsertCategoryLayout_True()
+ {
+ //Act
+ await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCategoryLayout_IsNotNull()
+ {
+ //Arrange
+ var categoryLayout = new CategoryLayout {
+ Name = "test"
+ };
+ await _categoryLayoutService.InsertCategoryLayout(categoryLayout);
+ categoryLayout.Name = "test2";
+
+ //Act
+ await _categoryLayoutService.UpdateCategoryLayout(categoryLayout);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
+ }
+
+ [TestMethod]
+ public async Task UpdateCategoryLayout_IsNull()
{
- private IRepository<CategoryLayout> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private CategoryLayoutService _categoryLayoutService;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<CategoryLayout>();
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _categoryLayoutService = new CategoryLayoutService(_repository, _cacheBase, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetCategoryLayoutById()
- {
- //Arrange
- var categoryLayout1 = new CategoryLayout {
- Name = "test1"
- };
- await _categoryLayoutService.InsertCategoryLayout(categoryLayout1);
-
- //Assert
- var layout = await _categoryLayoutService.GetCategoryLayoutById(categoryLayout1.Id);
-
- //Act
- Assert.IsNotNull(layout);
- Assert.AreEqual("test1", layout.Name);
- }
- [TestMethod()]
- public async Task GetAllCategoryLayouts()
- {
- //Arrange
- await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
- await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
- await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
-
- //Act
- var layouts = await _categoryLayoutService.GetAllCategoryLayouts();
-
- //Assert
- Assert.AreEqual(3, layouts.Count);
- }
-
- [TestMethod()]
- public async Task DeleteCategoryLayout()
- {
- //Arrange
- var categoryLayout1 = new CategoryLayout {
- Name = "test1"
- };
- await _categoryLayoutService.InsertCategoryLayout(categoryLayout1);
- var categoryLayout2 = new CategoryLayout {
- Name = "test2"
- };
- await _categoryLayoutService.InsertCategoryLayout(categoryLayout2);
-
- //Act
- await _categoryLayoutService.DeleteCategoryLayout(categoryLayout1);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
- Assert.AreEqual(1, _repository.Table.Count());
- }
-
-
- [TestMethod()]
- public async Task InsertCategoryLayout_True()
- {
- //Act
- await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCategoryLayout_IsNotNull()
- {
- //Arrange
- var categoryLayout = new CategoryLayout {
- Name = "test"
- };
- await _categoryLayoutService.InsertCategoryLayout(categoryLayout);
- categoryLayout.Name = "test2";
-
- //Act
- await _categoryLayoutService.UpdateCategoryLayout(categoryLayout);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
-
- [TestMethod()]
- public async Task UpdateCategoryLayout_IsNull()
- {
- //Arrange
- var categoryLayout = new CategoryLayout {
- Name = "test"
- };
- await _categoryLayoutService.InsertCategoryLayout(categoryLayout);
- categoryLayout.Name = "test2";
-
- //Act
- await _categoryLayoutService.UpdateCategoryLayout(categoryLayout);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test3"));
- }
+ //Arrange
+ var categoryLayout = new CategoryLayout {
+ Name = "test"
+ };
+ await _categoryLayoutService.InsertCategoryLayout(categoryLayout);
+ categoryLayout.Name = "test2";
+
+ //Act
+ await _categoryLayoutService.UpdateCategoryLayout(categoryLayout);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test3"));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceTest.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceTest.cs
index 7515409ea..cfa4309d3 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceTest.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryLayoutServiceTest.cs
@@ -1,69 +1,72 @@
using Grand.Business.Catalog.Services.Categories;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Categories
+namespace Grand.Business.Catalog.Tests.Services.Categories;
+
+[TestClass]
+public class CategoryLayoutServiceTest
{
- [TestClass()]
- public class CategoryLayoutServiceTest
+ private Mock<ICacheBase> _cacheMock;
+ private CategoryLayoutService _categoryLayoutService;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<CategoryLayout>> _repostioryMock;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<IRepository<CategoryLayout>> _repostioryMock;
- private Mock<ICacheBase> _cacheMock;
- private Mock<IMediator> _mediatorMock;
- private CategoryLayoutService _categoryLayoutService;
+ _repostioryMock = new Mock<IRepository<CategoryLayout>>();
+ _cacheMock = new Mock<ICacheBase>();
+ _mediatorMock = new Mock<IMediator>();
+ _categoryLayoutService =
+ new CategoryLayoutService(_repostioryMock.Object, _cacheMock.Object, _mediatorMock.Object);
+ }
- [TestInitialize()]
- public void Init()
- {
- _repostioryMock = new Mock<IRepository<CategoryLayout>>();
- _cacheMock = new Mock<ICacheBase>();
- _mediatorMock = new Mock<IMediator>();
- _categoryLayoutService = new CategoryLayoutService(_repostioryMock.Object, _cacheMock.Object, _mediatorMock.Object);
- }
+ [TestMethod]
+ public async Task GetCategoryLayoutById_InvokeMethods()
+ {
+ await _categoryLayoutService.GetCategoryLayoutById("1");
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<CategoryLayout>>>()), Times.Once);
+ }
- [TestMethod()]
- public async Task GetCategoryLayoutById_InvokeMethods()
- {
- await _categoryLayoutService.GetCategoryLayoutById("1");
- _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<CategoryLayout>>>()), Times.Once);
- }
- [TestMethod()]
- public async Task GetAllCategoryLayouts_InvokeMethods()
- {
- await _categoryLayoutService.GetAllCategoryLayouts();
- _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<CategoryLayout>>>>()), Times.Once);
- }
- [TestMethod()]
- public async Task DeleteCategoryLayout_ValidArguments_InvokeMethods()
- {
- await _categoryLayoutService.DeleteCategoryLayout(new CategoryLayout());
- _repostioryMock.Verify(c => c.DeleteAsync(It.IsAny<CategoryLayout>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CategoryLayout>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task GetAllCategoryLayouts_InvokeMethods()
+ {
+ await _categoryLayoutService.GetAllCategoryLayouts();
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<CategoryLayout>>>>()),
+ Times.Once);
+ }
+ [TestMethod]
+ public async Task DeleteCategoryLayout_ValidArguments_InvokeMethods()
+ {
+ await _categoryLayoutService.DeleteCategoryLayout(new CategoryLayout());
+ _repostioryMock.Verify(c => c.DeleteAsync(It.IsAny<CategoryLayout>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CategoryLayout>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertCategoryLayout_ValidArguments_InvokeMethods()
- {
- await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
- _repostioryMock.Verify(c => c.InsertAsync(It.IsAny<CategoryLayout>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CategoryLayout>>(), default), Times.Once);
- }
- [TestMethod()]
- public async Task UpdateCategoryLayout_ValidArguments_InvokeMethods()
- {
- await _categoryLayoutService.UpdateCategoryLayout(new CategoryLayout());
- _repostioryMock.Verify(c => c.UpdateAsync(It.IsAny<CategoryLayout>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CategoryLayout>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertCategoryLayout_ValidArguments_InvokeMethods()
+ {
+ await _categoryLayoutService.InsertCategoryLayout(new CategoryLayout());
+ _repostioryMock.Verify(c => c.InsertAsync(It.IsAny<CategoryLayout>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CategoryLayout>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task UpdateCategoryLayout_ValidArguments_InvokeMethods()
+ {
+ await _categoryLayoutService.UpdateCategoryLayout(new CategoryLayout());
+ _repostioryMock.Verify(c => c.UpdateAsync(It.IsAny<CategoryLayout>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CategoryLayout>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs
index 46e717af5..4893a324b 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceDbTests.cs
@@ -1,10 +1,11 @@
using Grand.Business.Catalog.Services.Categories;
using Grand.Business.Common.Services.Security;
using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -14,225 +15,235 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
+namespace Grand.Business.Catalog.Tests.Services.Categories;
-namespace Grand.Business.Catalog.Tests.Services.Categories
+[TestClass]
+public class CategoryServiceDbTests
{
- [TestClass()]
- public class CategoryServiceDbTests
- {
- private IRepository<Category> _categoryRepository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private IAclService _aclServiceMock;
- private CatalogSettings _settings;
- private CategoryService _categoryService;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
-
- _categoryRepository = new MongoDBRepositoryTest<Category>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
- _aclServiceMock = new AclService(new AccessControlConfig());
- _settings = new CatalogSettings();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _categoryService = new CategoryService(_cacheBase, _categoryRepository, _workContextMock.Object, _mediatorMock.Object, _aclServiceMock, new AccessControlConfig());
- }
-
- [TestMethod()]
- public async Task InsertCategory()
- {
- //Act
- await _categoryService.InsertCategory(new Category());
- //Assert
- Assert.IsTrue(_categoryRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCategory()
- {
- //Arrange
- var category = new Category { Name = "test" };
- await _categoryService.InsertCategory(category);
- category.Name = "test2";
- //Act
- await _categoryService.UpdateCategory(category);
- //Assert
- Assert.IsNotNull(_categoryRepository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
-
- [TestMethod()]
- public async Task DeleteCategory()
- {
- //Arrange
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- //Act
- await _categoryService.DeleteCategory(allCategory.FirstOrDefault(x => x.Id == "1"));
- //Assert
- Assert.IsTrue(_categoryRepository.Table.Count() == 4);
- Assert.IsNull(_categoryRepository.Table.FirstOrDefault(x => x.Id == "1"));
- }
-
- [TestMethod()]
- public async Task GetCategoryBreadCrumb()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var category = new Category { Id = "6", ParentCategoryId = "3", Published = true };
- await _categoryService.InsertCategory(category);
- var result = await _categoryService.GetCategoryBreadCrumb(category, false);
- Assert.IsTrue(result.Count == 2);
- Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("3")));
- }
-
- [TestMethod()]
- public void GetCategoryBreadCrumb_AllCategory()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var category = new Category { ParentCategoryId = "3" };
- var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
- Assert.IsTrue(result.Count == 0);
- }
-
- [TestMethod()]
- public async Task GetAllCategories()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetAllCategories();
- Assert.IsTrue(result.Count == 5);
- }
- [TestMethod()]
- public async Task GetMenuCategories()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetMenuCategories();
- Assert.IsTrue(result.Count == 1);
- }
-
- [TestMethod()]
- public async Task GetAllCategoriesByParentCategoryId()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetAllCategoriesByParentCategoryId("5");
- Assert.IsTrue(result.Count == 1);
- }
- [TestMethod()]
- public async Task GetAllCategoriesDisplayedOnHomePage()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetAllCategoriesDisplayedOnHomePage();
- Assert.IsTrue(result.Count == 2);
- }
- [TestMethod()]
- public async Task GetAllCategoriesFeaturedProductsOnHomePage()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetAllCategoriesFeaturedProductsOnHomePage();
- Assert.IsTrue(result.Count == 2);
- }
- [TestMethod()]
- public async Task GetAllCategoriesSearchBox()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetAllCategoriesSearchBox();
- Assert.IsTrue(result.Count == 2);
- }
- [TestMethod()]
- public async Task GetCategoryById_IsNotNull()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetCategoryById("1");
- Assert.IsNotNull(result);
- }
- [TestMethod()]
- public async Task GetCategoryById_IsNull()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = await _categoryService.GetCategoryById("10");
- Assert.IsNull(result);
- }
- [TestMethod()]
- public async Task GetCategoryBreadCrumb_ShouldReturnTwoElement()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var category = new Category { Id = "6", ParentCategoryId = "3", Published = true };
- await _categoryService.InsertCategory(category);
- var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
- Assert.IsTrue(result.Count == 2);
- Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("3")));
- }
-
- [TestMethod()]
- public void GetCategoryBreadCrumb_ShouldReturnThreeElement()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var category = new Category { Id = "6", ParentCategoryId = "1", Published = true };
- var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
- Assert.IsTrue(result.Count == 3);
- Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("1")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("5")));
- }
- [TestMethod()]
- public async Task GetFormattedBreadCrumb()
- {
- var exprectedString = "cat5 >> cat1 >> cat6";
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var category = new Category { Id = "6", Name = "cat6", ParentCategoryId = "1", Published = true };
- var result = await _categoryService.GetFormattedBreadCrumb(category);
- Assert.IsTrue(exprectedString.Equals(result));
- }
- [TestMethod()]
- public void GetFormattedBreadCrumb_ReturnExprectedString()
- {
- var exprectedString = "cat5 >> cat1 >> cat6";
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var category = new Category { Id = "6", Name = "cat6", ParentCategoryId = "1", Published = true };
- var result = _categoryService.GetFormattedBreadCrumb(category, allCategory);
- Assert.IsTrue(exprectedString.Equals(result));
- }
-
- [TestMethod()]
- public void GetFormattedBreadCrumb_ReturnEmptyString()
- {
- var allCategory = GetMockCategoryList();
- allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
- var result = _categoryService.GetFormattedBreadCrumb(null, allCategory);
- Assert.IsTrue(string.IsNullOrEmpty(result));
- }
-
-
- private IList<Category> GetMockCategoryList()
- {
- return new List<Category> {
- new Category { Id="1" ,Name="cat1",Published=true,ParentCategoryId="5",FeaturedProductsOnHomePage=true},
- new Category { Id="2" ,Name="cat2",Published=true,IncludeInMenu = true},
- new Category { Id="3" ,Name="cat3",Published=true,ShowOnHomePage=true,ShowOnSearchBox=true},
- new Category { Id="4" ,Name="cat4",Published=true,ShowOnHomePage=true,ShowOnSearchBox=true},
- new Category { Id="5" ,Name="cat5",Published=true,FeaturedProductsOnHomePage=true}
- };
- }
-
- }
-}
+ private IAclService _aclServiceMock;
+ private MemoryCacheBase _cacheBase;
+ private IRepository<Category> _categoryRepository;
+ private CategoryService _categoryService;
+ private Mock<IMediator> _mediatorMock;
+ private CatalogSettings _settings;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _categoryRepository = new MongoDBRepositoryTest<Category>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+ _aclServiceMock = new AclService(new AccessControlConfig());
+ _settings = new CatalogSettings();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _categoryService = new CategoryService(_cacheBase, _categoryRepository, _workContextMock.Object,
+ _mediatorMock.Object, _aclServiceMock, new AccessControlConfig());
+ }
+
+ [TestMethod]
+ public async Task InsertCategory()
+ {
+ //Act
+ await _categoryService.InsertCategory(new Category());
+ //Assert
+ Assert.IsTrue(_categoryRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCategory()
+ {
+ //Arrange
+ var category = new Category { Name = "test" };
+ await _categoryService.InsertCategory(category);
+ category.Name = "test2";
+ //Act
+ await _categoryService.UpdateCategory(category);
+ //Assert
+ Assert.IsNotNull(_categoryRepository.Table.FirstOrDefault(x => x.Name == "test2"));
+ }
+
+ [TestMethod]
+ public async Task DeleteCategory()
+ {
+ //Arrange
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ //Act
+ await _categoryService.DeleteCategory(allCategory.FirstOrDefault(x => x.Id == "1"));
+ //Assert
+ Assert.IsTrue(_categoryRepository.Table.Count() == 4);
+ Assert.IsNull(_categoryRepository.Table.FirstOrDefault(x => x.Id == "1"));
+ }
+
+ [TestMethod]
+ public async Task GetCategoryBreadCrumb()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var category = new Category { Id = "6", ParentCategoryId = "3", Published = true };
+ await _categoryService.InsertCategory(category);
+ var result = await _categoryService.GetCategoryBreadCrumb(category);
+ Assert.IsTrue(result.Count == 2);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("3")));
+ }
+
+ [TestMethod]
+ public void GetCategoryBreadCrumb_AllCategory()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var category = new Category { ParentCategoryId = "3" };
+ var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
+ Assert.IsTrue(result.Count == 0);
+ }
+
+ [TestMethod]
+ public async Task GetAllCategories()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetAllCategories();
+ Assert.IsTrue(result.Count == 5);
+ }
+
+ [TestMethod]
+ public async Task GetMenuCategories()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetMenuCategories();
+ Assert.IsTrue(result.Count == 1);
+ }
+
+ [TestMethod]
+ public async Task GetAllCategoriesByParentCategoryId()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetAllCategoriesByParentCategoryId("5");
+ Assert.IsTrue(result.Count == 1);
+ }
+
+ [TestMethod]
+ public async Task GetAllCategoriesDisplayedOnHomePage()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetAllCategoriesDisplayedOnHomePage();
+ Assert.IsTrue(result.Count == 2);
+ }
+
+ [TestMethod]
+ public async Task GetAllCategoriesFeaturedProductsOnHomePage()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetAllCategoriesFeaturedProductsOnHomePage();
+ Assert.IsTrue(result.Count == 2);
+ }
+
+ [TestMethod]
+ public async Task GetAllCategoriesSearchBox()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetAllCategoriesSearchBox();
+ Assert.IsTrue(result.Count == 2);
+ }
+
+ [TestMethod]
+ public async Task GetCategoryById_IsNotNull()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetCategoryById("1");
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCategoryById_IsNull()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = await _categoryService.GetCategoryById("10");
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCategoryBreadCrumb_ShouldReturnTwoElement()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var category = new Category { Id = "6", ParentCategoryId = "3", Published = true };
+ await _categoryService.InsertCategory(category);
+ var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
+ Assert.IsTrue(result.Count == 2);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("3")));
+ }
+
+ [TestMethod]
+ public void GetCategoryBreadCrumb_ShouldReturnThreeElement()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var category = new Category { Id = "6", ParentCategoryId = "1", Published = true };
+ var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
+ Assert.IsTrue(result.Count == 3);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("1")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("5")));
+ }
+
+ [TestMethod]
+ public async Task GetFormattedBreadCrumb()
+ {
+ var exprectedString = "cat5 >> cat1 >> cat6";
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var category = new Category { Id = "6", Name = "cat6", ParentCategoryId = "1", Published = true };
+ var result = await _categoryService.GetFormattedBreadCrumb(category);
+ Assert.IsTrue(exprectedString.Equals(result));
+ }
+
+ [TestMethod]
+ public void GetFormattedBreadCrumb_ReturnExprectedString()
+ {
+ var exprectedString = "cat5 >> cat1 >> cat6";
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var category = new Category { Id = "6", Name = "cat6", ParentCategoryId = "1", Published = true };
+ var result = _categoryService.GetFormattedBreadCrumb(category, allCategory);
+ Assert.IsTrue(exprectedString.Equals(result));
+ }
+
+ [TestMethod]
+ public void GetFormattedBreadCrumb_ReturnEmptyString()
+ {
+ var allCategory = GetMockCategoryList();
+ allCategory.ToList().ForEach(x => _categoryService.InsertCategory(x).GetAwaiter().GetResult());
+ var result = _categoryService.GetFormattedBreadCrumb(null, allCategory);
+ Assert.IsTrue(string.IsNullOrEmpty(result));
+ }
+
+
+ private IList<Category> GetMockCategoryList()
+ {
+ return new List<Category> {
+ new() {
+ Id = "1", Name = "cat1", Published = true, ParentCategoryId = "5", FeaturedProductsOnHomePage = true
+ },
+ new() { Id = "2", Name = "cat2", Published = true, IncludeInMenu = true },
+ new() { Id = "3", Name = "cat3", Published = true, ShowOnHomePage = true, ShowOnSearchBox = true },
+ new() { Id = "4", Name = "cat4", Published = true, ShowOnHomePage = true, ShowOnSearchBox = true },
+ new() { Id = "5", Name = "cat5", Published = true, FeaturedProductsOnHomePage = true }
+ };
+ }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs
index 6b4c059c9..ea84b5eaf 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/CategoryServiceTests.cs
@@ -1,9 +1,10 @@
using Grand.Business.Catalog.Services.Categories;
using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Catalog;
-using Grand.Domain.Customers;
using Grand.Data;
using Grand.Data.Mongo;
+using Grand.Domain.Catalog;
+using Grand.Domain.Customers;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -13,179 +14,182 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
+namespace Grand.Business.Catalog.Tests.Services.Categories;
-namespace Grand.Business.Catalog.Tests.Services.Categories
+[TestClass]
+public class CategoryServiceTests
{
- [TestClass()]
- public class CategoryServiceTests
+ private Mock<IAclService> _aclServiceMock;
+ private Mock<ICacheBase> _casheManagerMock;
+ private Mock<IRepository<Category>> _categoryRepositoryMock;
+ private CategoryService _categoryService;
+ private Mock<IMediator> _mediatorMock;
+ private ProductCategoryService _productCategoryService;
+ private Mock<MongoRepository<Product>> _productRepositoryMock;
+ private CatalogSettings _settings;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _casheManagerMock = new Mock<ICacheBase>();
+ _categoryRepositoryMock = new Mock<IRepository<Category>>();
+ _productRepositoryMock = new Mock<MongoRepository<Product>>(Mock.Of<IAuditInfoProvider>());
+ _workContextMock = new Mock<IWorkContext>();
+ _mediatorMock = new Mock<IMediator>();
+ _aclServiceMock = new Mock<IAclService>();
+ _settings = new CatalogSettings();
+ _categoryService = new CategoryService(_casheManagerMock.Object, _categoryRepositoryMock.Object,
+ _workContextMock.Object,
+ _mediatorMock.Object, _aclServiceMock.Object, new AccessControlConfig());
+ _productCategoryService = new ProductCategoryService(_productRepositoryMock.Object, _casheManagerMock.Object,
+ _workContextMock.Object, _mediatorMock.Object, new AccessControlConfig());
+ }
+
+ [TestMethod]
+ public void InsertCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _categoryService.InsertCategory(null),
+ "category");
+ }
+
+ [TestMethod]
+ public async Task InsertCategory_ValidArgument_InvokeRepositoryAndCache()
+ {
+ await _categoryService.InsertCategory(new Category());
+ _categoryRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Category>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Category>>(), default), Times.Once);
+ _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
+ }
+
+
+ [TestMethod]
+ public void UpdateCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _categoryService.UpdateCategory(null),
+ "category");
+ }
+
+ [TestMethod]
+ public async Task UpdateCategory_ValidArgument_InvokeRepositoryAndCache()
+ {
+ await _categoryService.UpdateCategory(new Category());
+ _categoryRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Category>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Category>>(), default), Times.Once);
+ _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
+ }
+
+ [TestMethod]
+ public void GetCategoryBreadCrumb_ShouldReturnEmptyList()
+ {
+ var allCategory = GetMockCategoryList();
+ var category = new Category { ParentCategoryId = "3" };
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
+ var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
+ Assert.IsTrue(result.Count == 0);
+ }
+
+ [TestMethod]
+ public void GetCategoryBreadCrumb_ShouldReturnTwoElement()
{
- private Mock<ICacheBase> _casheManagerMock;
- private Mock<IRepository<Category>> _categoryRepositoryMock;
- private Mock<MongoRepository<Product>> _productRepositoryMock;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IAclService> _aclServiceMock;
- private ProductCategoryService _productCategoryService;
- private CatalogSettings _settings;
- private CategoryService _categoryService;
-
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "";
-
- _casheManagerMock = new Mock<ICacheBase>();
- _categoryRepositoryMock = new Mock<IRepository<Category>>();
- _productRepositoryMock = new Mock<MongoRepository<Product>>(Mock.Of<IAuditInfoProvider>());
- _workContextMock = new Mock<IWorkContext>();
- _mediatorMock = new Mock<IMediator>();
- _aclServiceMock = new Mock<IAclService>();
- _settings = new CatalogSettings();
- _categoryService = new CategoryService(_casheManagerMock.Object, _categoryRepositoryMock.Object, _workContextMock.Object,
- _mediatorMock.Object, _aclServiceMock.Object, new AccessControlConfig());
- _productCategoryService = new ProductCategoryService(_productRepositoryMock.Object, _casheManagerMock.Object, _workContextMock.Object, _mediatorMock.Object, new AccessControlConfig());
- }
-
- [TestMethod()]
- public void InsertCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _categoryService.InsertCategory(null), "category");
- }
-
- [TestMethod()]
- public async Task InsertCategory_ValidArgument_InvokeRepositoryAndCache()
- {
- await _categoryService.InsertCategory(new Category());
- _categoryRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Category>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Category>>(), default), Times.Once);
- _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
- }
-
-
- [TestMethod()]
- public void UpdateCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _categoryService.UpdateCategory(null), "category");
- }
-
- [TestMethod()]
- public async Task UpdateCategory_ValidArgument_InvokeRepositoryAndCache()
- {
- await _categoryService.UpdateCategory(new Category());
- _categoryRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Category>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Category>>(), default), Times.Once);
- _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
- }
-
- [TestMethod()]
- public void GetCategoryBreadCrumb_ShouldReturnEmptyList()
- {
- var allCategory = GetMockCategoryList();
- var category = new Category { ParentCategoryId = "3" };
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
- var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
- Assert.IsTrue(result.Count == 0);
- }
-
- [TestMethod()]
- public void GetCategoryBreadCrumb_ShouldReturnTwoElement()
- {
- var allCategory = GetMockCategoryList();
- var category = new Category { Id = "6", ParentCategoryId = "3", Published = true };
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
- var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
- Assert.IsTrue(result.Count == 2);
- Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("3")));
- }
-
- [TestMethod()]
- public void GetCategoryBreadCrumb_ShouldReturnThreeElement()
- {
- var allCategory = GetMockCategoryList();
- var category = new Category { Id = "6", ParentCategoryId = "1", Published = true };
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
- var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
- Assert.IsTrue(result.Count == 3);
- Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("1")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("5")));
- }
-
- [TestMethod()]
- public void GetFormattedBreadCrumb_ReturnExprectedString()
- {
- var exprectedString = "cat5 >> cat1 >> cat6";
- var allCategory = GetMockCategoryList();
- var category = new Category { Id = "6", Name = "cat6", ParentCategoryId = "1", Published = true };
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
- var result = _categoryService.GetFormattedBreadCrumb(category, allCategory);
- Assert.IsTrue(exprectedString.Equals(result));
- }
-
- [TestMethod()]
- public void GetFormattedBreadCrumb_ReturnEmptyString()
- {
- var allCategory = GetMockCategoryList();
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
- _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
- var result = _categoryService.GetFormattedBreadCrumb(null, allCategory);
- Assert.IsTrue(string.IsNullOrEmpty(result));
- }
-
- [TestMethod()]
- public async Task DeleteProductCategory_InvokreRepositoryAndClearCache()
- {
- //var collectonMock = new Mock<IMongoCollection<Product>>();
- //_productRepositoryMock.Setup(p => p.Collection).Returns(collectonMock.Object);
- await _productCategoryService.DeleteProductCategory(new ProductCategory(), "1");
- //TODO
- //collectonMock.Verify(c => c.UpdateOneAsync(It.IsAny<FilterDefinition<Product>>(), It.IsAny<UpdateDefinition<Product>>(), null, default(CancellationToken)), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<ProductCategory>>(), default), Times.Once);
- //clear product cache and ProductCategory
- _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
- }
-
- [TestMethod()]
- public void DeleteProductCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _productCategoryService.DeleteProductCategory(null, "id"), "productCategory");
- }
-
- [TestMethod()]
- public async Task InsertProductCategory_InvokreRepositoryAndClearCache()
- {
- //var collectonMock = new Mock<IMongoCollection<Product>>();
- //_productRepositoryMock.Setup(p => p.Collection).Returns(collectonMock.Object);
- await _productCategoryService.InsertProductCategory(new ProductCategory(), "id");
- //TODO
- //collectonMock.Verify(c => c.UpdateOneAsync(It.IsAny<FilterDefinition<Product>>(), It.IsAny<UpdateDefinition<Product>>(), null, default(CancellationToken)), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<ProductCategory>>(), default), Times.Once);
- _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
- }
-
- [TestMethod()]
- public void InsertProductCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _productCategoryService.InsertProductCategory(null, "id"), "productCategory");
- }
-
- private IList<Category> GetMockCategoryList()
- {
- return new List<Category> {
- new Category { Id="1" ,Name="cat1",Published=true,ParentCategoryId="5"},
- new Category { Id="2" ,Name="cat2",Published=true},
- new Category { Id="3" ,Name="cat3",Published=true},
- new Category { Id="4" ,Name="cat4",Published=true},
- new Category { Id="5" ,Name="cat5",Published=true}
- };
- }
+ var allCategory = GetMockCategoryList();
+ var category = new Category { Id = "6", ParentCategoryId = "3", Published = true };
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
+ var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
+ Assert.IsTrue(result.Count == 2);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("3")));
+ }
+
+ [TestMethod]
+ public void GetCategoryBreadCrumb_ShouldReturnThreeElement()
+ {
+ var allCategory = GetMockCategoryList();
+ var category = new Category { Id = "6", ParentCategoryId = "1", Published = true };
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
+ var result = _categoryService.GetCategoryBreadCrumb(category, allCategory);
+ Assert.IsTrue(result.Count == 3);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("6")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("1")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("5")));
+ }
+
+ [TestMethod]
+ public void GetFormattedBreadCrumb_ReturnExprectedString()
+ {
+ var exprectedString = "cat5 >> cat1 >> cat6";
+ var allCategory = GetMockCategoryList();
+ var category = new Category { Id = "6", Name = "cat6", ParentCategoryId = "1", Published = true };
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
+ var result = _categoryService.GetFormattedBreadCrumb(category, allCategory);
+ Assert.IsTrue(exprectedString.Equals(result));
+ }
+
+ [TestMethod]
+ public void GetFormattedBreadCrumb_ReturnEmptyString()
+ {
+ var allCategory = GetMockCategoryList();
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<Customer>())).Returns(() => true);
+ _aclServiceMock.Setup(a => a.Authorize(It.IsAny<Category>(), It.IsAny<string>())).Returns(() => true);
+ var result = _categoryService.GetFormattedBreadCrumb(null, allCategory);
+ Assert.IsTrue(string.IsNullOrEmpty(result));
+ }
+ [TestMethod]
+ public async Task DeleteProductCategory_InvokreRepositoryAndClearCache()
+ {
+ //var collectonMock = new Mock<IMongoCollection<Product>>();
+ //_productRepositoryMock.Setup(p => p.Collection).Returns(collectonMock.Object);
+ await _productCategoryService.DeleteProductCategory(new ProductCategory(), "1");
+ //TODO
+ //collectonMock.Verify(c => c.UpdateOneAsync(It.IsAny<FilterDefinition<Product>>(), It.IsAny<UpdateDefinition<Product>>(), null, default(CancellationToken)), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<ProductCategory>>(), default), Times.Once);
+ //clear product cache and ProductCategory
+ _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
+ }
+
+ [TestMethod]
+ public void DeleteProductCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _productCategoryService.DeleteProductCategory(null, "id"), "productCategory");
+ }
+
+ [TestMethod]
+ public async Task InsertProductCategory_InvokreRepositoryAndClearCache()
+ {
+ //var collectonMock = new Mock<IMongoCollection<Product>>();
+ //_productRepositoryMock.Setup(p => p.Collection).Returns(collectonMock.Object);
+ await _productCategoryService.InsertProductCategory(new ProductCategory(), "id");
+ //TODO
+ //collectonMock.Verify(c => c.UpdateOneAsync(It.IsAny<FilterDefinition<Product>>(), It.IsAny<UpdateDefinition<Product>>(), null, default(CancellationToken)), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<ProductCategory>>(), default), Times.Once);
+ _casheManagerMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(2));
+ }
+
+ [TestMethod]
+ public void InsertProductCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _productCategoryService.InsertProductCategory(null, "id"), "productCategory");
+ }
+
+ private IList<Category> GetMockCategoryList()
+ {
+ return new List<Category> {
+ new() { Id = "1", Name = "cat1", Published = true, ParentCategoryId = "5" },
+ new() { Id = "2", Name = "cat2", Published = true },
+ new() { Id = "3", Name = "cat3", Published = true },
+ new() { Id = "4", Name = "cat4", Published = true },
+ new() { Id = "5", Name = "cat5", Published = true }
+ };
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs
index ff7e2e4ec..f363180f3 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Categories/ProductCategoryServiceTests.cs
@@ -1,8 +1,9 @@
using Grand.Business.Catalog.Services.Categories;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -12,119 +13,121 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Categories
+namespace Grand.Business.Catalog.Tests.Services.Categories;
+
+[TestClass]
+public class ProductCategoryServiceTests
{
- [TestClass()]
- public class ProductCategoryServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private ProductCategoryService _productCategoryService;
+ private IRepository<Product> _repository;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _repository = new MongoDBRepositoryTest<Product>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _productCategoryService = new ProductCategoryService(_repository, _cacheBase, _workContextMock.Object,
+ _mediatorMock.Object, new AccessControlConfig());
+ }
+
+
+ [TestMethod]
+ public async Task GetProductCategoriesByCategoryIdTest()
+ {
+ //Arrange
+ var p1 = new Product();
+ p1.ProductCategories.Add(new ProductCategory { CategoryId = "1" });
+ p1.ProductCategories.Add(new ProductCategory { CategoryId = "2" });
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ p2.ProductCategories.Add(new ProductCategory { CategoryId = "2" });
+ p2.ProductCategories.Add(new ProductCategory { CategoryId = "3" });
+ await _repository.InsertAsync(p2);
+
+ //Act
+ var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("1");
+ var pc2 = await _productCategoryService.GetProductCategoriesByCategoryId("2");
+
+ //Assert
+ Assert.AreEqual(1, pc1.Count);
+ Assert.AreEqual(2, pc2.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductCategoryTest()
{
- private ProductCategoryService _productCategoryService;
- private IRepository<Product> _repository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
-
- _repository = new MongoDBRepositoryTest<Product>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _productCategoryService = new ProductCategoryService(_repository, _cacheBase, _workContextMock.Object, _mediatorMock.Object, new AccessControlConfig());
- }
-
-
- [TestMethod()]
- public async Task GetProductCategoriesByCategoryIdTest()
- {
- //Arrange
- var p1 = new Product();
- p1.ProductCategories.Add(new ProductCategory { CategoryId = "1" });
- p1.ProductCategories.Add(new ProductCategory { CategoryId = "2" });
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- p2.ProductCategories.Add(new ProductCategory { CategoryId = "2" });
- p2.ProductCategories.Add(new ProductCategory { CategoryId = "3" });
- await _repository.InsertAsync(p2);
-
- //Act
- var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("1");
- var pc2 = await _productCategoryService.GetProductCategoriesByCategoryId("2");
-
- //Assert
- Assert.AreEqual(1, pc1.Count);
- Assert.AreEqual(2, pc2.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductCategoryTest()
- {
- //Arrange
- var p1 = new Product();
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- await _repository.InsertAsync(p2);
-
- //Act
- await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "1", DisplayOrder = 10 }, p1.Id);
- await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "2" }, p1.Id);
-
- var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("1");
-
- //Assert
- Assert.AreEqual(1, pc1.Count);
- Assert.AreEqual(10, pc1.FirstOrDefault().DisplayOrder);
- }
-
- [TestMethod()]
- public async Task UpdateProductCategoryTest()
- {
- //Arrange
- var p1 = new Product();
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- await _repository.InsertAsync(p2);
-
- //Act
- var pc = new ProductCategory { CategoryId = "1", DisplayOrder = 10 };
- await _productCategoryService.InsertProductCategory(pc, p1.Id);
- await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "2" }, p1.Id);
-
- pc.CategoryId = "10";
- pc.DisplayOrder = 5;
- await _productCategoryService.UpdateProductCategory(pc, p1.Id);
-
- var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("10");
-
- //Assert
- Assert.AreEqual(1, pc1.Count);
- Assert.AreEqual(5, pc1.FirstOrDefault().DisplayOrder);
- }
-
- [TestMethod()]
- public async Task DeleteProductCategoryTest()
- {
- //Arrange
- var p1 = new Product();
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- await _repository.InsertAsync(p2);
-
- //Act
- var pc = new ProductCategory { CategoryId = "1", DisplayOrder = 10 };
- await _productCategoryService.InsertProductCategory(pc, p1.Id);
- await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "2" }, p1.Id);
-
- await _productCategoryService.DeleteProductCategory(pc, p1.Id);
-
- var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("1");
-
- //Assert
- Assert.AreEqual(0, pc1.Count);
- }
+ //Arrange
+ var p1 = new Product();
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ await _repository.InsertAsync(p2);
+
+ //Act
+ await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "1", DisplayOrder = 10 },
+ p1.Id);
+ await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "2" }, p1.Id);
+
+ var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("1");
+
+ //Assert
+ Assert.AreEqual(1, pc1.Count);
+ Assert.AreEqual(10, pc1.FirstOrDefault().DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductCategoryTest()
+ {
+ //Arrange
+ var p1 = new Product();
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ await _repository.InsertAsync(p2);
+
+ //Act
+ var pc = new ProductCategory { CategoryId = "1", DisplayOrder = 10 };
+ await _productCategoryService.InsertProductCategory(pc, p1.Id);
+ await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "2" }, p1.Id);
+
+ pc.CategoryId = "10";
+ pc.DisplayOrder = 5;
+ await _productCategoryService.UpdateProductCategory(pc, p1.Id);
+
+ var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("10");
+
+ //Assert
+ Assert.AreEqual(1, pc1.Count);
+ Assert.AreEqual(5, pc1.FirstOrDefault().DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductCategoryTest()
+ {
+ //Arrange
+ var p1 = new Product();
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ await _repository.InsertAsync(p2);
+
+ //Act
+ var pc = new ProductCategory { CategoryId = "1", DisplayOrder = 10 };
+ await _productCategoryService.InsertProductCategory(pc, p1.Id);
+ await _productCategoryService.InsertProductCategory(new ProductCategory { CategoryId = "2" }, p1.Id);
+
+ await _productCategoryService.DeleteProductCategory(pc, p1.Id);
+
+ var pc1 = await _productCategoryService.GetProductCategoriesByCategoryId("1");
+
+ //Assert
+ Assert.AreEqual(0, pc1.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionLayoutServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionLayoutServiceTests.cs
index 48fe5460c..cb7bcc890 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionLayoutServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionLayoutServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Catalog.Services.Collections;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,105 +9,104 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Collections
+namespace Grand.Business.Catalog.Tests.Services.Collections;
+
+[TestClass]
+public class CollectionLayoutServiceTests
{
- [TestClass()]
- public class CollectionLayoutServiceTests
+ private MemoryCacheBase _cacheBase;
+ private CollectionLayoutService _collectionLayoutService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CollectionLayout> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<CollectionLayout>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _collectionLayoutService = new CollectionLayoutService(_repository, _cacheBase, _mediatorMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task GetAllCollectionLayoutsTest()
+ {
+ //Arrange
+ await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
+ await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
+ await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
+
+ //Act
+ var layouts = await _collectionLayoutService.GetAllCollectionLayouts();
+
+ //Assert
+ Assert.AreEqual(3, layouts.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCollectionLayoutByIdTest()
+ {
+ //Arrange
+ var collectionLayout = new CollectionLayout {
+ Name = "test"
+ };
+ await _collectionLayoutService.InsertCollectionLayout(collectionLayout);
+
+ //Act
+ var layout = await _collectionLayoutService.GetCollectionLayoutById(collectionLayout.Id);
+
+ //Assert
+ Assert.IsNotNull(layout);
+ Assert.AreEqual("test", layout.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertCollectionLayoutTest()
+ {
+ //Act
+ await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCollectionLayoutTest()
+ {
+ //Arrange
+ var categoryLayout = new CollectionLayout {
+ Name = "test"
+ };
+ await _collectionLayoutService.InsertCollectionLayout(categoryLayout);
+ categoryLayout.Name = "test2";
+
+ //Act
+ await _collectionLayoutService.UpdateCollectionLayout(categoryLayout);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
+ }
+
+ [TestMethod]
+ public async Task DeleteCollectionLayoutTest()
{
- private IRepository<CollectionLayout> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private CollectionLayoutService _collectionLayoutService;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<CollectionLayout>();
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _collectionLayoutService = new CollectionLayoutService(_repository, _cacheBase, _mediatorMock.Object);
- }
-
-
- [TestMethod()]
- public async Task GetAllCollectionLayoutsTest()
- {
- //Arrange
- await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
- await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
- await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
-
- //Act
- var layouts = await _collectionLayoutService.GetAllCollectionLayouts();
-
- //Assert
- Assert.AreEqual(3, layouts.Count);
- }
-
- [TestMethod()]
- public async Task GetCollectionLayoutByIdTest()
- {
- //Arrange
- var collectionLayout = new CollectionLayout {
- Name = "test"
- };
- await _collectionLayoutService.InsertCollectionLayout(collectionLayout);
-
- //Act
- var layout = await _collectionLayoutService.GetCollectionLayoutById(collectionLayout.Id);
-
- //Assert
- Assert.IsNotNull(layout);
- Assert.AreEqual("test", layout.Name);
- }
-
- [TestMethod()]
- public async Task InsertCollectionLayoutTest()
- {
- //Act
- await _collectionLayoutService.InsertCollectionLayout(new CollectionLayout());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCollectionLayoutTest()
- {
- //Arrange
- var categoryLayout = new CollectionLayout {
- Name = "test"
- };
- await _collectionLayoutService.InsertCollectionLayout(categoryLayout);
- categoryLayout.Name = "test2";
-
- //Act
- await _collectionLayoutService.UpdateCollectionLayout(categoryLayout);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
-
- [TestMethod()]
- public async Task DeleteCollectionLayoutTest()
- {
-
- //Arrange
- var collectionLayout1 = new CollectionLayout {
- Name = "test1"
- };
- await _collectionLayoutService.InsertCollectionLayout(collectionLayout1);
- var collectionLayout2 = new CollectionLayout {
- Name = "test2"
- };
- await _collectionLayoutService.InsertCollectionLayout(collectionLayout2);
-
- //Act
- await _collectionLayoutService.DeleteCollectionLayout(collectionLayout1);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
- Assert.AreEqual(1, _repository.Table.Count());
- }
+ //Arrange
+ var collectionLayout1 = new CollectionLayout {
+ Name = "test1"
+ };
+ await _collectionLayoutService.InsertCollectionLayout(collectionLayout1);
+ var collectionLayout2 = new CollectionLayout {
+ Name = "test2"
+ };
+ await _collectionLayoutService.InsertCollectionLayout(collectionLayout2);
+
+ //Act
+ await _collectionLayoutService.DeleteCollectionLayout(collectionLayout1);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
+ Assert.AreEqual(1, _repository.Table.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs
index 895d49f92..18a483e6c 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/CollectionServiceTests.cs
@@ -1,8 +1,8 @@
using Grand.Business.Catalog.Services.Collections;
using Grand.Business.Core.Interfaces.Catalog.Collections;
using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -11,84 +11,83 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Collections
+namespace Grand.Business.Catalog.Tests.Services.Collections;
+
+[TestClass]
+public class CollectionServiceTests
{
- [TestClass()]
- public class CollectionServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<IRepository<Collection>> _repositoryMock;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IAclService> _aclMock;
- private CatalogSettings _settings;
- private ICollectionService _collectionService;
+ private Mock<IAclService> _aclMock;
+ private Mock<ICacheBase> _cacheMock;
+ private ICollectionService _collectionService;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Collection>> _repositoryMock;
+ private CatalogSettings _settings;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _repositoryMock = new Mock<IRepository<Collection>>();
- _workContextMock = new Mock<IWorkContext>();
- _mediatorMock = new Mock<IMediator>();
- _aclMock = new Mock<IAclService>();
- _settings = new CatalogSettings();
- _collectionService = new CollectionService(_cacheMock.Object, _repositoryMock.Object, _workContextMock.Object
- , _mediatorMock.Object, _aclMock.Object, new AccessControlConfig());
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _repositoryMock = new Mock<IRepository<Collection>>();
+ _workContextMock = new Mock<IWorkContext>();
+ _mediatorMock = new Mock<IMediator>();
+ _aclMock = new Mock<IAclService>();
+ _settings = new CatalogSettings();
+ _collectionService = new CollectionService(_cacheMock.Object, _repositoryMock.Object, _workContextMock.Object
+ , _mediatorMock.Object, _aclMock.Object, new AccessControlConfig());
+ }
- [TestMethod()]
- public async Task DeleteCollection_ValidArguments_InvokeMethods()
- {
- await _collectionService.DeleteCollection(new Collection());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Collection>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Collection>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteCollection_ValidArguments_InvokeMethods()
+ {
+ await _collectionService.DeleteCollection(new Collection());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Collection>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Collection>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertCollection_ValidArguments_InvokeMethods()
- {
- await _collectionService.InsertCollection(new Collection());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Collection>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Collection>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertCollection_ValidArguments_InvokeMethods()
+ {
+ await _collectionService.InsertCollection(new Collection());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Collection>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Collection>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateCollection_ValidArguments_InvokeMethods()
- {
- await _collectionService.UpdateCollection(new Collection());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Collection>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Collection>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateCollection_ValidArguments_InvokeMethods()
+ {
+ await _collectionService.UpdateCollection(new Collection());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Collection>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Collection>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task GeCollectionById_ValidArgument_GetByCache()
- {
- await _collectionService.GetCollectionById("id");
- _cacheMock.Verify(c => c.GetAsync<Collection>(It.IsAny<string>(), It.IsAny<Func<Task<Collection>>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GeCollectionById_ValidArgument_GetByCache()
+ {
+ await _collectionService.GetCollectionById("id");
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Collection>>>()), Times.Once);
+ }
- [TestMethod()]
- public void DeleteCollection_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _collectionService.DeleteCollection(null));
- }
+ [TestMethod]
+ public void DeleteCollection_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _collectionService.DeleteCollection(null));
+ }
- [TestMethod()]
- public void InsertCollection_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _collectionService.InsertCollection(null));
- }
+ [TestMethod]
+ public void InsertCollection_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _collectionService.InsertCollection(null));
+ }
- [TestMethod()]
- public void UpdateCollection_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _collectionService.UpdateCollection(null));
- }
+ [TestMethod]
+ public void UpdateCollection_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _collectionService.UpdateCollection(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs
index ea1edb6a4..f6a1dbc51 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Collections/ProductCollectionServiceTests.cs
@@ -1,8 +1,9 @@
using Grand.Business.Catalog.Services.Collections;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -12,119 +13,121 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Collections
+namespace Grand.Business.Catalog.Tests.Services.Collections;
+
+[TestClass]
+public class ProductCollectionServiceTests
{
- [TestClass()]
- public class ProductCollectionServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private ProductCollectionService _productCollectionService;
+ private IRepository<Product> _repository;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _repository = new MongoDBRepositoryTest<Product>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _productCollectionService = new ProductCollectionService(_cacheBase, _repository, _workContextMock.Object,
+ _mediatorMock.Object, new AccessControlConfig());
+ }
+
+
+ [TestMethod]
+ public async Task GetProductCollectionsByCollectionIdTest()
+ {
+ //Arrange
+ var p1 = new Product();
+ p1.ProductCollections.Add(new ProductCollection { CollectionId = "1" });
+ p1.ProductCollections.Add(new ProductCollection { CollectionId = "2" });
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ p2.ProductCollections.Add(new ProductCollection { CollectionId = "2" });
+ p2.ProductCollections.Add(new ProductCollection { CollectionId = "3" });
+ await _repository.InsertAsync(p2);
+
+ //Act
+ var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("1", "");
+ var pc2 = await _productCollectionService.GetProductCollectionsByCollectionId("2", "");
+
+ //Assert
+ Assert.AreEqual(1, pc1.Count);
+ Assert.AreEqual(2, pc2.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductCollectionTest()
{
- private ProductCollectionService _productCollectionService;
- private IRepository<Product> _repository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
-
- _repository = new MongoDBRepositoryTest<Product>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _productCollectionService = new ProductCollectionService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object, new AccessControlConfig());
- }
-
-
- [TestMethod()]
- public async Task GetProductCollectionsByCollectionIdTest()
- {
- //Arrange
- var p1 = new Product();
- p1.ProductCollections.Add(new ProductCollection { CollectionId = "1" });
- p1.ProductCollections.Add(new ProductCollection { CollectionId = "2" });
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- p2.ProductCollections.Add(new ProductCollection { CollectionId = "2" });
- p2.ProductCollections.Add(new ProductCollection { CollectionId = "3" });
- await _repository.InsertAsync(p2);
-
- //Act
- var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("1", "");
- var pc2 = await _productCollectionService.GetProductCollectionsByCollectionId("2", "");
-
- //Assert
- Assert.AreEqual(1, pc1.Count);
- Assert.AreEqual(2, pc2.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductCollectionTest()
- {
- //Arrange
- var p1 = new Product();
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- await _repository.InsertAsync(p2);
-
- //Act
- await _productCollectionService.InsertProductCollection(new ProductCollection { CollectionId = "1", DisplayOrder = 10 }, p1.Id);
- await _productCollectionService.InsertProductCollection(new ProductCollection { CollectionId = "2" }, p1.Id);
-
- var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("1", "");
-
- //Assert
- Assert.AreEqual(1, pc1.Count);
- Assert.AreEqual(10, pc1.FirstOrDefault().DisplayOrder);
- }
-
- [TestMethod()]
- public async Task UpdateProductCollectionTest()
- {
- //Arrange
- var p1 = new Product();
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- await _repository.InsertAsync(p2);
-
- //Act
- var pc = new ProductCollection { CollectionId = "1", DisplayOrder = 10 };
- await _productCollectionService.InsertProductCollection(pc, p1.Id);
- await _productCollectionService.InsertProductCollection(new ProductCollection { CollectionId = "2" }, p1.Id);
-
- pc.CollectionId = "10";
- pc.DisplayOrder = 5;
- await _productCollectionService.UpdateProductCollection(pc, p1.Id);
-
- var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("10", "");
-
- //Assert
- Assert.AreEqual(1, pc1.Count);
- Assert.AreEqual(5, pc1.FirstOrDefault().DisplayOrder);
- }
-
- [TestMethod()]
- public async Task DeleteProductCollectionTest()
- {
- //Arrange
- var p1 = new Product();
- await _repository.InsertAsync(p1);
- var p2 = new Product();
- await _repository.InsertAsync(p2);
-
- //Act
- var pc = new ProductCollection { CollectionId = "1", DisplayOrder = 10 };
- await _productCollectionService.InsertProductCollection(pc, p1.Id);
- await _productCollectionService.InsertProductCollection(new ProductCollection { CollectionId = "2" }, p1.Id);
-
- await _productCollectionService.DeleteProductCollection(pc, p1.Id);
-
- var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("1", "");
-
- //Assert
- Assert.AreEqual(0, pc1.Count);
- }
+ //Arrange
+ var p1 = new Product();
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ await _repository.InsertAsync(p2);
+
+ //Act
+ await _productCollectionService.InsertProductCollection(
+ new ProductCollection { CollectionId = "1", DisplayOrder = 10 }, p1.Id);
+ await _productCollectionService.InsertProductCollection(new ProductCollection { CollectionId = "2" }, p1.Id);
+
+ var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("1", "");
+
+ //Assert
+ Assert.AreEqual(1, pc1.Count);
+ Assert.AreEqual(10, pc1.FirstOrDefault().DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductCollectionTest()
+ {
+ //Arrange
+ var p1 = new Product();
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ await _repository.InsertAsync(p2);
+
+ //Act
+ var pc = new ProductCollection { CollectionId = "1", DisplayOrder = 10 };
+ await _productCollectionService.InsertProductCollection(pc, p1.Id);
+ await _productCollectionService.InsertProductCollection(new ProductCollection { CollectionId = "2" }, p1.Id);
+
+ pc.CollectionId = "10";
+ pc.DisplayOrder = 5;
+ await _productCollectionService.UpdateProductCollection(pc, p1.Id);
+
+ var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("10", "");
+
+ //Assert
+ Assert.AreEqual(1, pc1.Count);
+ Assert.AreEqual(5, pc1.FirstOrDefault().DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductCollectionTest()
+ {
+ //Arrange
+ var p1 = new Product();
+ await _repository.InsertAsync(p1);
+ var p2 = new Product();
+ await _repository.InsertAsync(p2);
+
+ //Act
+ var pc = new ProductCollection { CollectionId = "1", DisplayOrder = 10 };
+ await _productCollectionService.InsertProductCollection(pc, p1.Id);
+ await _productCollectionService.InsertProductCollection(new ProductCollection { CollectionId = "2" }, p1.Id);
+
+ await _productCollectionService.DeleteProductCollection(pc, p1.Id);
+
+ var pc1 = await _productCollectionService.GetProductCollectionsByCollectionId("1", "");
+
+ //Assert
+ Assert.AreEqual(0, pc1.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs
index 848a84263..797f1dfca 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/GeoLookupServiceTests.cs
@@ -4,35 +4,35 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Directory
+namespace Grand.Business.Catalog.Tests.Services.Directory;
+
+[TestClass]
+public class GeoLookupServiceTests
{
- [TestClass()]
- public class GeoLookupServiceTests
+ private readonly string IPAddressUS = "142.250.203.206";
+ private Mock<ILogger<GeoLookupService>> _loggerMock;
+ private GeoLookupService _service;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<ILogger<GeoLookupService>> _loggerMock;
- private GeoLookupService _service;
- private string IPAddressUS = "142.250.203.206";
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "../../../../../Web/Grand.Web/";
- _loggerMock = new Mock<ILogger<GeoLookupService>>();
- _service = new GeoLookupService(_loggerMock.Object);
- }
+ CommonPath.BaseDirectory = "../../../../../Web/Grand.Web/";
+ _loggerMock = new Mock<ILogger<GeoLookupService>>();
+ _service = new GeoLookupService(_loggerMock.Object);
+ }
- [TestMethod()]
- public void CountryIsoCodeTest()
- {
- var countryiso = _service.CountryIsoCode(IPAddressUS);
- Assert.AreEqual("US", countryiso);
- }
+ [TestMethod]
+ public void CountryIsoCodeTest()
+ {
+ var countryiso = _service.CountryIsoCode(IPAddressUS);
+ Assert.AreEqual("US", countryiso);
+ }
- [TestMethod()]
- public void CountryNameTest()
- {
- var countryname = _service.CountryName(IPAddressUS);
- Assert.AreEqual("United States", countryname);
- }
+ [TestMethod]
+ public void CountryNameTest()
+ {
+ var countryname = _service.CountryName(IPAddressUS);
+ Assert.AreEqual("United States", countryname);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/MeasureServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/MeasureServiceTests.cs
index 94723cbe1..8070d763d 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/MeasureServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/MeasureServiceTests.cs
@@ -7,102 +7,101 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Directory
+namespace Grand.Business.Catalog.Tests.Services.Directory;
+
+[TestClass]
+public class MeasureServiceTests
{
- [TestClass()]
- public class MeasureServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<IRepository<MeasureDimension>> _mdRepositoryMock;
- private Mock<IRepository<MeasureWeight>> _mwRepositoryMock;
- private Mock<IRepository<MeasureUnit>> _muRepositoryMock;
- private MeasureSettings _settings;
- private Mock<IMediator> _mediatorMock;
- private MeasureService _measureService;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IRepository<MeasureDimension>> _mdRepositoryMock;
+ private MeasureService _measureService;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<MeasureUnit>> _muRepositoryMock;
+ private Mock<IRepository<MeasureWeight>> _mwRepositoryMock;
+ private MeasureSettings _settings;
- [TestInitialize()]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _mdRepositoryMock = new Mock<IRepository<MeasureDimension>>();
- _mwRepositoryMock = new Mock<IRepository<MeasureWeight>>();
- _muRepositoryMock = new Mock<IRepository<MeasureUnit>>();
- _settings = new MeasureSettings();
- _mediatorMock = new Mock<IMediator>();
- _measureService = new MeasureService(_cacheMock.Object, _mdRepositoryMock.Object, _mwRepositoryMock.Object,
- _muRepositoryMock.Object, _settings, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _mdRepositoryMock = new Mock<IRepository<MeasureDimension>>();
+ _mwRepositoryMock = new Mock<IRepository<MeasureWeight>>();
+ _muRepositoryMock = new Mock<IRepository<MeasureUnit>>();
+ _settings = new MeasureSettings();
+ _mediatorMock = new Mock<IMediator>();
+ _measureService = new MeasureService(_cacheMock.Object, _mdRepositoryMock.Object, _mwRepositoryMock.Object,
+ _muRepositoryMock.Object, _settings, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task InsertMeasureDimension_ValidArgument()
- {
- await _measureService.InsertMeasureDimension(new MeasureDimension());
- _mdRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<MeasureDimension>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MeasureDimension>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertMeasureDimension_ValidArgument()
+ {
+ await _measureService.InsertMeasureDimension(new MeasureDimension());
+ _mdRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<MeasureDimension>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MeasureDimension>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateMeasureDimension_ValidArgument()
- {
- await _measureService.UpdateMeasureDimension(new MeasureDimension());
- _mdRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MeasureDimension>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MeasureDimension>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateMeasureDimension_ValidArgument()
+ {
+ await _measureService.UpdateMeasureDimension(new MeasureDimension());
+ _mdRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MeasureDimension>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MeasureDimension>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteMeasureDimensiony_ValidArgument()
- {
- await _measureService.DeleteMeasureDimension(new MeasureDimension());
- _mdRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MeasureDimension>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MeasureDimension>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteMeasureDimensiony_ValidArgument()
+ {
+ await _measureService.DeleteMeasureDimension(new MeasureDimension());
+ _mdRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MeasureDimension>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MeasureDimension>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertMeasureWeight_ValidArgument()
- {
- await _measureService.InsertMeasureWeight(new MeasureWeight());
- _mwRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<MeasureWeight>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MeasureWeight>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertMeasureWeight_ValidArgument()
+ {
+ await _measureService.InsertMeasureWeight(new MeasureWeight());
+ _mwRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<MeasureWeight>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MeasureWeight>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateMeasureWeight_ValidArgument()
- {
- await _measureService.UpdateMeasureWeight(new MeasureWeight());
- _mwRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MeasureWeight>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MeasureWeight>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateMeasureWeight_ValidArgument()
+ {
+ await _measureService.UpdateMeasureWeight(new MeasureWeight());
+ _mwRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MeasureWeight>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MeasureWeight>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteMeasureWeight_ValidArgument()
- {
- await _measureService.DeleteMeasureWeight(new MeasureWeight());
- _mwRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MeasureWeight>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MeasureWeight>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteMeasureWeight_ValidArgument()
+ {
+ await _measureService.DeleteMeasureWeight(new MeasureWeight());
+ _mwRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MeasureWeight>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MeasureWeight>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertMeasureUnit_ValidArgument()
- {
- await _measureService.InsertMeasureUnit(new MeasureUnit());
- _muRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<MeasureUnit>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MeasureUnit>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertMeasureUnit_ValidArgument()
+ {
+ await _measureService.InsertMeasureUnit(new MeasureUnit());
+ _muRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<MeasureUnit>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MeasureUnit>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateMeasureUnit_ValidArgument()
- {
- await _measureService.UpdateMeasureUnit(new MeasureUnit());
- _muRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MeasureUnit>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MeasureUnit>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateMeasureUnit_ValidArgument()
+ {
+ await _measureService.UpdateMeasureUnit(new MeasureUnit());
+ _muRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MeasureUnit>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MeasureUnit>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteMeasureUnit_ValidArgument()
- {
- await _measureService.DeleteMeasureWeight(new MeasureWeight());
- _mwRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MeasureWeight>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MeasureWeight>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteMeasureUnit_ValidArgument()
+ {
+ await _measureService.DeleteMeasureWeight(new MeasureWeight());
+ _mwRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MeasureWeight>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MeasureWeight>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/SearchTermServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/SearchTermServiceTests.cs
index a3cdc08e6..60cc265b8 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/SearchTermServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Directory/SearchTermServiceTests.cs
@@ -1,69 +1,68 @@
using Grand.Business.Catalog.Services.Directory;
-using Grand.Domain.Common;
using Grand.Data;
+using Grand.Domain.Common;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Directory
+namespace Grand.Business.Catalog.Tests.Services.Directory;
+
+[TestClass]
+public class SearchTermServiceTests
{
- [TestClass()]
- public class SearchTermServiceTests
- {
- private Mock<IRepository<SearchTerm>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private SearchTermService _service;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<SearchTerm>> _repositoryMock;
+ private SearchTermService _service;
- [TestInitialize()]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<SearchTerm>>();
- _mediatorMock = new Mock<IMediator>();
- _service = new SearchTermService(_repositoryMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<SearchTerm>>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new SearchTermService(_repositoryMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task InsertSearchTerm_ValidArgument()
- {
- await _service.InsertSearchTerm(new SearchTerm());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<SearchTerm>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<SearchTerm>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertSearchTerm_ValidArgument()
+ {
+ await _service.InsertSearchTerm(new SearchTerm());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<SearchTerm>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<SearchTerm>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateSearchTerm_ValidArgument()
- {
- await _service.UpdateSearchTerm(new SearchTerm());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<SearchTerm>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<SearchTerm>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateSearchTerm_ValidArgument()
+ {
+ await _service.UpdateSearchTerm(new SearchTerm());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<SearchTerm>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<SearchTerm>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteSearchTerm_ValidArgument()
- {
- await _service.DeleteSearchTerm(new SearchTerm());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<SearchTerm>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<SearchTerm>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteSearchTerm_ValidArgument()
+ {
+ await _service.DeleteSearchTerm(new SearchTerm());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<SearchTerm>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<SearchTerm>>(), default), Times.Once);
+ }
- [TestMethod()]
- public void InsertSearchTerm_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertSearchTerm(null));
- }
+ [TestMethod]
+ public void InsertSearchTerm_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertSearchTerm(null));
+ }
- [TestMethod()]
- public void UpdateSearchTerm_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateSearchTerm(null));
- }
+ [TestMethod]
+ public void UpdateSearchTerm_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateSearchTerm(null));
+ }
- [TestMethod()]
- public void DeleteSearchTerm_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteSearchTerm(null));
- }
+ [TestMethod]
+ public void DeleteSearchTerm_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteSearchTerm(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountAmountProviderTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountAmountProviderTests.cs
index 848464835..ac82e1d8b 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountAmountProviderTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountAmountProviderTests.cs
@@ -3,25 +3,24 @@ using Grand.Domain.Catalog;
using Grand.Domain.Customers;
using Grand.Domain.Discounts;
-namespace Grand.Business.Catalog.Tests.Services.Discounts
+namespace Grand.Business.Catalog.Tests.Services.Discounts;
+
+public class DiscountAmountProviderTests : IDiscountAmountProvider
{
- public class DiscountAmountProviderTests : IDiscountAmountProvider
- {
- public string ConfigurationUrl => throw new NotImplementedException();
+ public string ConfigurationUrl => throw new NotImplementedException();
- public string SystemName => "SampleDiscountAmountProvider";
+ public string SystemName => "SampleDiscountAmountProvider";
- public string FriendlyName => throw new NotImplementedException();
+ public string FriendlyName => throw new NotImplementedException();
- public int Priority => throw new NotImplementedException();
+ public int Priority => throw new NotImplementedException();
- public IList<string> LimitedToStores => new List<string>();
+ public IList<string> LimitedToStores => new List<string>();
- public IList<string> LimitedToGroups => new List<string>();
+ public IList<string> LimitedToGroups => new List<string>();
- public async Task<double> DiscountAmount(Discount discount, Customer customer, Product product, double amount)
- {
- return await Task.FromResult(9);
- }
+ public async Task<double> DiscountAmount(Discount discount, Customer customer, Product product, double amount)
+ {
+ return await Task.FromResult(9);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountProviderTest.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountProviderTest.cs
index 913624f8c..16520d1b2 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountProviderTest.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountProviderTest.cs
@@ -1,49 +1,44 @@
using Grand.Business.Core.Interfaces.Catalog.Discounts;
using Grand.Business.Core.Utilities.Catalog;
-namespace Grand.Business.Catalog.Tests.Services.Discounts
-{
- public class DiscountProviderTest : IDiscountProvider
- {
- private IList<string> limitedToStores = new List<string>();
- private IList<string> limitedToGroups = new List<string>();
+namespace Grand.Business.Catalog.Tests.Services.Discounts;
- public string ConfigurationUrl => throw new NotImplementedException();
+public class DiscountProviderTest : IDiscountProvider
+{
+ public string ConfigurationUrl => throw new NotImplementedException();
- public string SystemName => "SampleDiscountProvider";
+ public string SystemName => "SampleDiscountProvider";
- public string FriendlyName => throw new NotImplementedException();
+ public string FriendlyName => throw new NotImplementedException();
- public int Priority => throw new NotImplementedException();
+ public int Priority => throw new NotImplementedException();
- public IList<string> LimitedToStores => limitedToStores;
+ public IList<string> LimitedToStores { get; } = new List<string>();
- public IList<string> LimitedToGroups => limitedToGroups;
+ public IList<string> LimitedToGroups { get; } = new List<string>();
- public IList<IDiscountRule> GetRequirementRules()
- {
- return new List<IDiscountRule> { new DiscountRuleValidTest() };
- }
+ public IList<IDiscountRule> GetRequirementRules()
+ {
+ return new List<IDiscountRule> { new DiscountRuleValidTest() };
}
+}
- public class DiscountRuleValidTest : IDiscountRule
+public class DiscountRuleValidTest : IDiscountRule
+{
+ public string SystemName => "RuleSystemName";
+
+ public string FriendlyName => throw new NotImplementedException();
+
+ public async Task<DiscountRuleValidationResult> CheckRequirement(DiscountRuleValidationRequest request)
{
- public string SystemName => "RuleSystemName";
-
- public string FriendlyName => throw new NotImplementedException();
-
- public async Task<DiscountRuleValidationResult> CheckRequirement(DiscountRuleValidationRequest request)
- {
- var result = new DiscountRuleValidationResult {
- IsValid = true
- };
- return await Task.FromResult(result);
- }
-
- public string GetConfigurationUrl(string discountId, string discountRequirementId)
- {
- throw new NotImplementedException();
- }
+ var result = new DiscountRuleValidationResult {
+ IsValid = true
+ };
+ return await Task.FromResult(result);
}
-}
+ public string GetConfigurationUrl(string discountId, string discountRequirementId)
+ {
+ throw new NotImplementedException();
+ }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs
index db12bcdcf..162c1e2d1 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Discounts/DiscountServiceTests.cs
@@ -1,14 +1,14 @@
-using DotLiquid.Util;
-using Grand.Business.Catalog.Queries.Handlers;
+using Grand.Business.Catalog.Queries.Handlers;
using Grand.Business.Catalog.Services.Discounts;
using Grand.Business.Core.Interfaces.Catalog.Discounts;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Queries.Catalog;
using Grand.Business.Core.Utilities.Catalog;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
+using Grand.Domain.Common;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Directory;
using Grand.Domain.Discounts;
using Grand.Domain.Stores;
@@ -21,816 +21,837 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Discounts
+namespace Grand.Business.Catalog.Tests.Services.Discounts;
+
+[TestClass]
+public class DiscountServiceTests
{
- [TestClass()]
- public class DiscountServiceTests
- {
- private IRepository<Discount> _repository;
- private IRepository<DiscountCoupon> _discountCouponRepository;
- private IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;
- private Mock<ITranslationService> _translationServiceMock;
- private GetDiscountUsageHistoryQueryHandler handler;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private DiscountService _dicountService;
- private MemoryCacheBase _cacheBase;
- private GetDiscountAmountProviderHandler _getDiscountAmountProviderHandler;
- private IEnumerable<IDiscountProvider> _discountProviders;
- private IEnumerable<IDiscountAmountProvider> _discountAmountProviders;
- private DiscountProviderLoader _discountProviderLoader;
- private DiscountValidationService _discountValidationService;
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
-
- _repository = new MongoDBRepositoryTest<Discount>();
- _discountCouponRepository = new MongoDBRepositoryTest<DiscountCoupon>();
- _discountUsageHistoryRepository = new MongoDBRepositoryTest<DiscountUsageHistory>();
- _workContextMock = new Mock<IWorkContext>();
- _translationServiceMock = new Mock<ITranslationService>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _discountProviders = new List<IDiscountProvider> { new DiscountProviderTest() };
- _discountAmountProviders = new List<IDiscountAmountProvider> { new DiscountAmountProviderTests() };
- _discountProviderLoader = new DiscountProviderLoader(_discountProviders, _discountAmountProviders);
- _discountValidationService = new DiscountValidationService(_discountProviderLoader, _discountCouponRepository, _mediatorMock.Object);
- _dicountService = new DiscountService(_cacheBase, _repository, _discountCouponRepository, _discountUsageHistoryRepository, _mediatorMock.Object, new AccessControlConfig());
- handler = new GetDiscountUsageHistoryQueryHandler(_discountUsageHistoryRepository);
- _getDiscountAmountProviderHandler = new GetDiscountAmountProviderHandler(_discountProviderLoader);
- }
-
- [TestMethod()]
- public async Task GetDiscountByIdTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test"
- };
- await _dicountService.InsertDiscount(discount);
-
- //Act
- var result = await _dicountService.GetDiscountById(discount.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task GetAllDiscountsTest()
- {
- //Arrange
- var discount1 = new Discount {
- Name = "test1",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount1);
-
- var discount2 = new Discount {
- Name = "test2",
- IsEnabled = true
- };
-
- await _dicountService.InsertDiscount(discount2);
-
- //Act
- var result = await _dicountService.GetDiscountsQuery(null);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task InsertDiscountTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test"
- };
- //Act
- await _dicountService.InsertDiscount(discount);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x=>x.Name == "test"));
- Assert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Name == "test").Name);
-
- }
-
- [TestMethod()]
- public async Task UpdateDiscountTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test"
- };
- await _dicountService.InsertDiscount(discount);
-
- //Act
- discount.Name = "test2";
- await _dicountService.UpdateDiscount(discount);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- Assert.AreEqual("test2", _repository.Table.FirstOrDefault(x => x.Name == "test2").Name);
- }
-
- [TestMethod()]
- public async Task DeleteDiscountTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test"
- };
- await _dicountService.InsertDiscount(discount);
-
- //Act
- await _dicountService.DeleteDiscount(discount);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
- }
-
- [TestMethod()]
- public void LoadDiscountProviderBySystemNameTest_NotNull()
- {
- //Act
- var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName");
- //Assert
- Assert.IsNotNull(provider);
- }
- [TestMethod()]
- public void LoadDiscountProviderBySystemNameTest_Null()
- {
- //Act
- var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName2");
- //Assert
- Assert.IsNull(provider);
- }
-
- [TestMethod()]
- public void LoadAllDiscountProvidersTest()
- {
- //Act
- var providers = _discountProviderLoader.LoadAllDiscountProviders();
- //Assert
- Assert.AreEqual(1, providers.Count);
- }
-
- [TestMethod()]
- public async Task GetDiscountByCouponCodeTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- //Act
- var coupon = await _dicountService.GetDiscountByCouponCode("TEST123");
-
- //Assert
- Assert.IsNotNull(coupon);
- Assert.AreEqual(discount.Id, coupon.Id);
- }
-
- [TestMethod()]
- public async Task GetAllCouponCodesByDiscountIdTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var discountCoupon1 = new DiscountCoupon {
- CouponCode = "TEST124",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon1);
- var discountCoupon2 = new DiscountCoupon {
- CouponCode = "TEST125",
- DiscountId = "id"
- };
- await _discountCouponRepository.InsertAsync(discountCoupon2);
- //Act
- var coupon = await _dicountService.GetAllCouponCodesByDiscountId(discount.Id);
- //Assert
- Assert.AreEqual(2, coupon.Count);
- }
-
- [TestMethod()]
- public async Task GetDiscountCodeByIdTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var discountCoupon1 = new DiscountCoupon {
- CouponCode = "TEST124",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon1);
- var discountCoupon2 = new DiscountCoupon {
- CouponCode = "TEST125",
- DiscountId = "id"
- };
- await _discountCouponRepository.InsertAsync(discountCoupon2);
- //Act
- var coupon = await _dicountService.GetDiscountCodeById(discountCoupon.Id);
- //Assert
- Assert.IsNotNull(coupon);
- Assert.AreEqual("TEST123", coupon.CouponCode);
- }
-
- [TestMethod()]
- public async Task GetDiscountCodeByCodeTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var discountCoupon1 = new DiscountCoupon {
- CouponCode = "TEST124",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon1);
- var discountCoupon2 = new DiscountCoupon {
- CouponCode = "TEST125",
- DiscountId = "id"
- };
- await _discountCouponRepository.InsertAsync(discountCoupon2);
- //Act
- var coupon = await _dicountService.GetDiscountCodeByCode(discountCoupon.CouponCode);
- //Assert
- Assert.IsNotNull(coupon);
- Assert.AreEqual("TEST123", coupon.CouponCode);
- }
-
- [TestMethod()]
- public async Task DeleteDiscountCouponTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var discountCoupon1 = new DiscountCoupon {
- CouponCode = "TEST124",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon1);
- var discountCoupon2 = new DiscountCoupon {
- CouponCode = "TEST125",
- DiscountId = "id"
- };
- await _discountCouponRepository.InsertAsync(discountCoupon2);
-
- //Act
- await _dicountService.DeleteDiscountCoupon(discountCoupon);
- //Assert
- Assert.IsNull(_discountCouponRepository.Table.FirstOrDefault(x=>x.Id == discountCoupon.Id));
- }
-
- [TestMethod()]
- public async Task InsertDiscountCouponTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id
- };
- //Act
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- //Assert
- Assert.IsNotNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id));
- }
-
- [TestMethod()]
- public async Task DiscountCouponSetAsUsedTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- //Act
- await _dicountService.DiscountCouponSetAsUsed("TEST123", true);
-
- //Assert
- Assert.IsNotNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id));
- Assert.IsTrue(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id).Used);
- }
-
- [TestMethod()]
- public async Task CancelDiscountTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- var discountUsageHistory = new DiscountUsageHistory {
- DiscountId = discount.Id,
- OrderId = "123",
- CouponCode = "TEST123"
- };
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
-
- //Act
- await _dicountService.CancelDiscount("123");
-
- //Assert
- Assert.IsTrue(_discountUsageHistoryRepository.Table.FirstOrDefault(x=>x.Id == discountUsageHistory.Id).Canceled);
- Assert.IsFalse(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id).Used);
- }
-
- [TestMethod()]
- public async Task ValidateDiscountTest_Valid_CouponCodesToValidate()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true,
- CurrencyCode = "USD"
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var customer = new Customer();
- customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST123", StoreId = "" });
- //Act
- var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Domain.Directory.Currency { CurrencyCode = "USD" });
- //Assert
- Assert.IsTrue(result.IsValid);
- }
- [TestMethod()]
- public async Task ValidateDiscountTest_InValid_CouponCodesToValidate()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true,
- CurrencyCode = "USD",
- RequiresCouponCode = true
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var customer = new Customer();
- customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
- //Act
- var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });
- //Assert
- Assert.IsFalse(result.IsValid);
- }
- [TestMethod()]
- public async Task ValidateDiscountTest_InValid_CurrencyCode()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true,
- CurrencyCode = "EUR"
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var customer = new Customer();
- customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
- //Act
- var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });
- //Assert
- Assert.IsFalse(result.IsValid);
- }
-
- [TestMethod()]
- public async Task ValidateDiscountTest_InValid_EndDateUtc()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true,
- CurrencyCode = "USD",
- EndDateUtc = DateTime.UtcNow.AddDays(-1)
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var customer = new Customer();
- customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
- //Act
- var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });
- //Assert
- Assert.IsFalse(result.IsValid);
- }
- [TestMethod()]
- public async Task ValidateDiscountTest_InValid_Disable()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = false,
- CurrencyCode = "USD"
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
- var customer = new Customer();
- customer.UserFields.Add(new Domain.Common.UserField { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
- //Act
- var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(), new Currency { CurrencyCode = "USD" });
- //Assert
- Assert.IsFalse(result.IsValid);
- }
- [TestMethod()]
- public async Task GetDiscountUsageHistoryByIdTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- var discountUsageHistory = new DiscountUsageHistory {
- DiscountId = discount.Id,
- OrderId = "123",
- CouponCode = "TEST123"
- };
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
-
- //Act
- await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
-
- //Assert
- Assert.IsNotNull(_discountUsageHistoryRepository.Table.FirstOrDefault(x => x.Id == discountUsageHistory.Id));
-
- }
-
- [TestMethod()]
- public async Task GetAllDiscountUsageHistoryTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- var discountUsageHistory = new DiscountUsageHistory {
- DiscountId = discount.Id,
- OrderId = "123",
- CouponCode = "TEST123"
- };
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
- var discountUsageHistory2 = new DiscountUsageHistory {
- DiscountId = discount.Id,
- OrderId = "124",
- CouponCode = "TEST123"
- };
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory2);
- //Act
- var usageHistory = await handler.Handle(new GetDiscountUsageHistoryQuery(), CancellationToken.None);
-
- //Assert
- Assert.AreEqual(2, usageHistory.Count);
-
- }
-
- [TestMethod()]
- public async Task InsertDiscountUsageHistoryTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- var discountUsageHistory = new DiscountUsageHistory {
- DiscountId = discount.Id,
- OrderId = "123",
- CouponCode = "TEST123"
- };
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
-
- //Act
- var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
-
- //Assert
- Assert.IsNotNull(usageHistory);
- Assert.AreEqual(discountUsageHistory.CouponCode, usageHistory.CouponCode);
- }
-
- [TestMethod()]
- public async Task UpdateDiscountUsageHistoryTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- var discountUsageHistory = new DiscountUsageHistory {
- DiscountId = discount.Id,
- OrderId = "123",
- CouponCode = "TEST123"
- };
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
-
- //Act
- discountUsageHistory.OrderId = "12";
- await _discountUsageHistoryRepository.UpdateAsync(discountUsageHistory);
- var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
-
- //Assert
- Assert.IsNotNull(usageHistory);
- Assert.AreEqual(discountUsageHistory.OrderId, usageHistory.OrderId);
- }
-
- [TestMethod()]
- public async Task DeleteDiscountUsageHistoryTest()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
- var discountCoupon = new DiscountCoupon {
- CouponCode = "TEST123",
- DiscountId = discount.Id,
- Used = true
- };
- await _discountCouponRepository.InsertAsync(discountCoupon);
-
- var discountUsageHistory = new DiscountUsageHistory {
- DiscountId = discount.Id,
- OrderId = "123",
- CouponCode = "TEST123"
- };
- await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
-
- //Act
- await _discountUsageHistoryRepository.DeleteAsync(discountUsageHistory);
- var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
-
- //Assert
- Assert.IsNull(usageHistory);
- }
-
- [TestMethod()]
- public async Task GetDiscountAmountTest_global()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- DiscountAmount = 10,
- CurrencyCode = "USD",
- IsEnabled = true
- };
- await _dicountService.InsertDiscount(discount);
-
- //Act
- var discountamount = await _dicountService.GetDiscountAmount(discount,
- new Customer(),
- new Domain.Directory.Currency { CurrencyCode = "USD" },new Product(), 100);
-
- //Assert
- Assert.AreEqual(discount.DiscountAmount, discountamount);
- }
- public async Task GetDiscountAmountTest_AssignedToAllProducts()
- {
- //Arrange
- var discount = new Discount {
- Name = "test",
- DiscountAmount = 10,
- CurrencyCode = "USD",
- IsEnabled = true,
- DiscountTypeId = DiscountType.AssignedToAllProducts
- };
- await _dicountService.InsertDiscount(discount);
-
- //Act
- var discountamount = await _dicountService.GetDiscountAmount(discount,
- new Customer(),
- new Domain.Directory.Currency { CurrencyCode = "USD" }, new Product(), 100);
-
- //Assert
- Assert.AreEqual(discount.DiscountAmount, discountamount);
- }
- [TestMethod()]
- public async Task GetPreferredDiscountTest()
- {
- //Arrange
- var discount1 = new Discount {
- Name = "test",
- DiscountAmount = 10,
- CurrencyCode = "USD",
- IsEnabled = true,
- DiscountTypeId = DiscountType.AssignedToAllProducts
- };
- await _dicountService.InsertDiscount(discount1);
- var discount2 = new Discount {
- Name = "test",
- DiscountAmount = 20,
- CurrencyCode = "USD",
- IsEnabled = true,
- DiscountTypeId = DiscountType.AssignedToAllProducts
- };
- await _dicountService.InsertDiscount(discount2);
- //Act
- var discountamount = await _dicountService.GetPreferredDiscount(
- new List<ApplyDiscount> {
- new ApplyDiscount { DiscountId = discount1.Id, IsCumulative = false },
- new ApplyDiscount { DiscountId = discount2.Id, IsCumulative = false }
- },
- new Customer(),
- new Domain.Directory.Currency { CurrencyCode = "USD" }, new Product(), 100);
-
- //Assert
- Assert.AreEqual(discount2.DiscountAmount, discountamount.discountAmount);
- }
-
- [TestMethod()]
- public async Task GetPreferredDiscountTest_IsCumulative_True()
- {
- //Arrange
- var discount1 = new Discount {
- Name = "test",
- DiscountAmount = 10,
- CurrencyCode = "USD",
- IsEnabled = true,
- DiscountTypeId = DiscountType.AssignedToAllProducts
- };
- await _dicountService.InsertDiscount(discount1);
- var discount2 = new Discount {
- Name = "test",
- DiscountAmount = 20,
- CurrencyCode = "USD",
- IsEnabled = true,
- DiscountTypeId = DiscountType.AssignedToAllProducts
- };
- await _dicountService.InsertDiscount(discount2);
- //Act
- var discountamount = await _dicountService.GetPreferredDiscount(
- new List<ApplyDiscount> {
- new ApplyDiscount { DiscountId = discount1.Id, IsCumulative = true },
- new ApplyDiscount { DiscountId = discount2.Id, IsCumulative = true }
- },
- new Customer(),
- new Domain.Directory.Currency { CurrencyCode = "USD" }, new Product(), 100);
-
- //Assert
- Assert.AreEqual(discount1.DiscountAmount + discount2.DiscountAmount, discountamount.discountAmount);
- }
-
- [TestMethod()]
- public async Task GetDiscountAmountProviderTest()
- {
- //Arrange
- var discount1 = new Discount {
- Name = "test",
- DiscountAmount = 10,
- CurrencyCode = "USD",
- IsEnabled = true,
- CalculateByPlugin = true,
- DiscountPluginName = "SampleDiscountAmountProvider",
- DiscountTypeId = DiscountType.AssignedToAllProducts
- };
- await _dicountService.InsertDiscount(discount1);
- //Act
- var amount = await _getDiscountAmountProviderHandler.Handle(new GetDiscountAmountProvider(discount1, new Customer(), new Product(), new Currency(), 100), CancellationToken.None);
- //Assert
- Assert.AreEqual(9, amount);
- }
-
- [TestMethod()]
- public void LoadDiscountAmountProviderBySystemNameTest()
- {
- //Act
- var discountProvider = _discountProviderLoader.LoadDiscountAmountProviderBySystemName("SampleDiscountAmountProvider");
- //Assert
- Assert.IsNotNull(discountProvider);
- }
-
- [TestMethod()]
- public void LoadDiscountAmountProvidersTest()
- {
- //Act
- var discountProviders = _discountProviderLoader.LoadDiscountAmountProviders();
- //Assert
- Assert.AreEqual(1, discountProviders.Count);
- }
+ private MemoryCacheBase _cacheBase;
+ private DiscountService _dicountService;
+ private IEnumerable<IDiscountAmountProvider> _discountAmountProviders;
+ private IRepository<DiscountCoupon> _discountCouponRepository;
+ private DiscountProviderLoader _discountProviderLoader;
+ private IEnumerable<IDiscountProvider> _discountProviders;
+ private IRepository<DiscountUsageHistory> _discountUsageHistoryRepository;
+ private DiscountValidationService _discountValidationService;
+ private GetDiscountAmountProviderHandler _getDiscountAmountProviderHandler;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Discount> _repository;
+ private Mock<ITranslationService> _translationServiceMock;
+ private Mock<IWorkContext> _workContextMock;
+ private GetDiscountUsageHistoryQueryHandler handler;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _repository = new MongoDBRepositoryTest<Discount>();
+ _discountCouponRepository = new MongoDBRepositoryTest<DiscountCoupon>();
+ _discountUsageHistoryRepository = new MongoDBRepositoryTest<DiscountUsageHistory>();
+ _workContextMock = new Mock<IWorkContext>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _discountProviders = new List<IDiscountProvider> { new DiscountProviderTest() };
+ _discountAmountProviders = new List<IDiscountAmountProvider> { new DiscountAmountProviderTests() };
+ _discountProviderLoader = new DiscountProviderLoader(_discountProviders, _discountAmountProviders);
+ _discountValidationService =
+ new DiscountValidationService(_discountProviderLoader, _discountCouponRepository, _mediatorMock.Object);
+ _dicountService = new DiscountService(_cacheBase, _repository, _discountCouponRepository,
+ _discountUsageHistoryRepository, _mediatorMock.Object, new AccessControlConfig());
+ handler = new GetDiscountUsageHistoryQueryHandler(_discountUsageHistoryRepository);
+ _getDiscountAmountProviderHandler = new GetDiscountAmountProviderHandler(_discountProviderLoader);
+ }
+
+ [TestMethod]
+ public async Task GetDiscountByIdTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test"
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ //Act
+ var result = await _dicountService.GetDiscountById(discount.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task GetAllDiscountsTest()
+ {
+ //Arrange
+ var discount1 = new Discount {
+ Name = "test1",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount1);
+
+ var discount2 = new Discount {
+ Name = "test2",
+ IsEnabled = true
+ };
+
+ await _dicountService.InsertDiscount(discount2);
+
+ //Act
+ var result = await _dicountService.GetDiscountsQuery(null);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertDiscountTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test"
+ };
+ //Act
+ await _dicountService.InsertDiscount(discount);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
+ Assert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Name == "test").Name);
+ }
+
+ [TestMethod]
+ public async Task UpdateDiscountTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test"
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ //Act
+ discount.Name = "test2";
+ await _dicountService.UpdateDiscount(discount);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
+ Assert.AreEqual("test2", _repository.Table.FirstOrDefault(x => x.Name == "test2").Name);
+ }
+
+ [TestMethod]
+ public async Task DeleteDiscountTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test"
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ //Act
+ await _dicountService.DeleteDiscount(discount);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
+ }
+
+ [TestMethod]
+ public void LoadDiscountProviderBySystemNameTest_NotNull()
+ {
+ //Act
+ var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName");
+ //Assert
+ Assert.IsNotNull(provider);
+ }
+
+ [TestMethod]
+ public void LoadDiscountProviderBySystemNameTest_Null()
+ {
+ //Act
+ var provider = _discountProviderLoader.LoadDiscountProviderByRuleSystemName("RuleSystemName2");
+ //Assert
+ Assert.IsNull(provider);
+ }
+
+ [TestMethod]
+ public void LoadAllDiscountProvidersTest()
+ {
+ //Act
+ var providers = _discountProviderLoader.LoadAllDiscountProviders();
+ //Assert
+ Assert.AreEqual(1, providers.Count);
+ }
+
+ [TestMethod]
+ public async Task GetDiscountByCouponCodeTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ //Act
+ var coupon = await _dicountService.GetDiscountByCouponCode("TEST123");
+
+ //Assert
+ Assert.IsNotNull(coupon);
+ Assert.AreEqual(discount.Id, coupon.Id);
+ }
+
+ [TestMethod]
+ public async Task GetAllCouponCodesByDiscountIdTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var discountCoupon1 = new DiscountCoupon {
+ CouponCode = "TEST124",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon1);
+ var discountCoupon2 = new DiscountCoupon {
+ CouponCode = "TEST125",
+ DiscountId = "id"
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon2);
+ //Act
+ var coupon = await _dicountService.GetAllCouponCodesByDiscountId(discount.Id);
+ //Assert
+ Assert.AreEqual(2, coupon.Count);
+ }
+
+ [TestMethod]
+ public async Task GetDiscountCodeByIdTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var discountCoupon1 = new DiscountCoupon {
+ CouponCode = "TEST124",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon1);
+ var discountCoupon2 = new DiscountCoupon {
+ CouponCode = "TEST125",
+ DiscountId = "id"
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon2);
+ //Act
+ var coupon = await _dicountService.GetDiscountCodeById(discountCoupon.Id);
+ //Assert
+ Assert.IsNotNull(coupon);
+ Assert.AreEqual("TEST123", coupon.CouponCode);
+ }
+
+ [TestMethod]
+ public async Task GetDiscountCodeByCodeTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var discountCoupon1 = new DiscountCoupon {
+ CouponCode = "TEST124",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon1);
+ var discountCoupon2 = new DiscountCoupon {
+ CouponCode = "TEST125",
+ DiscountId = "id"
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon2);
+ //Act
+ var coupon = await _dicountService.GetDiscountCodeByCode(discountCoupon.CouponCode);
+ //Assert
+ Assert.IsNotNull(coupon);
+ Assert.AreEqual("TEST123", coupon.CouponCode);
+ }
+
+ [TestMethod]
+ public async Task DeleteDiscountCouponTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var discountCoupon1 = new DiscountCoupon {
+ CouponCode = "TEST124",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon1);
+ var discountCoupon2 = new DiscountCoupon {
+ CouponCode = "TEST125",
+ DiscountId = "id"
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon2);
+
+ //Act
+ await _dicountService.DeleteDiscountCoupon(discountCoupon);
+ //Assert
+ Assert.IsNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id));
+ }
+
+ [TestMethod]
+ public async Task InsertDiscountCouponTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id
+ };
+ //Act
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ //Assert
+ Assert.IsNotNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id));
+ }
+
+ [TestMethod]
+ public async Task DiscountCouponSetAsUsedTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ //Act
+ await _dicountService.DiscountCouponSetAsUsed("TEST123", true);
+
+ //Assert
+ Assert.IsNotNull(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id));
+ Assert.IsTrue(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id).Used);
+ }
+
+ [TestMethod]
+ public async Task CancelDiscountTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ var discountUsageHistory = new DiscountUsageHistory {
+ DiscountId = discount.Id,
+ OrderId = "123",
+ CouponCode = "TEST123"
+ };
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
+
+ //Act
+ await _dicountService.CancelDiscount("123");
+
+ //Assert
+ Assert.IsTrue(_discountUsageHistoryRepository.Table.FirstOrDefault(x => x.Id == discountUsageHistory.Id)
+ .Canceled);
+ Assert.IsFalse(_discountCouponRepository.Table.FirstOrDefault(x => x.Id == discountCoupon.Id).Used);
+ }
+
+ [TestMethod]
+ public async Task ValidateDiscountTest_Valid_CouponCodesToValidate()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true,
+ CurrencyCode = "USD"
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var customer = new Customer();
+ customer.UserFields.Add(new UserField
+ { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST123", StoreId = "" });
+ //Act
+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(),
+ new Currency { CurrencyCode = "USD" });
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ValidateDiscountTest_InValid_CouponCodesToValidate()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true,
+ CurrencyCode = "USD",
+ RequiresCouponCode = true
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var customer = new Customer();
+ customer.UserFields.Add(new UserField
+ { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
+ //Act
+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(),
+ new Currency { CurrencyCode = "USD" });
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ValidateDiscountTest_InValid_CurrencyCode()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true,
+ CurrencyCode = "EUR"
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var customer = new Customer();
+ customer.UserFields.Add(new UserField
+ { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
+ //Act
+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(),
+ new Currency { CurrencyCode = "USD" });
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ValidateDiscountTest_InValid_EndDateUtc()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true,
+ CurrencyCode = "USD",
+ EndDateUtc = DateTime.UtcNow.AddDays(-1)
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var customer = new Customer();
+ customer.UserFields.Add(new UserField
+ { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
+ //Act
+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(),
+ new Currency { CurrencyCode = "USD" });
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ValidateDiscountTest_InValid_Disable()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = false,
+ CurrencyCode = "USD"
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+ var customer = new Customer();
+ customer.UserFields.Add(new UserField
+ { Key = SystemCustomerFieldNames.DiscountCoupons, Value = "TEST12", StoreId = "" });
+ //Act
+ var result = await _discountValidationService.ValidateDiscount(discount, customer, new Store(),
+ new Currency { CurrencyCode = "USD" });
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task GetDiscountUsageHistoryByIdTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ var discountUsageHistory = new DiscountUsageHistory {
+ DiscountId = discount.Id,
+ OrderId = "123",
+ CouponCode = "TEST123"
+ };
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
+
+ //Act
+ await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
+
+ //Assert
+ Assert.IsNotNull(_discountUsageHistoryRepository.Table.FirstOrDefault(x => x.Id == discountUsageHistory.Id));
+ }
+
+ [TestMethod]
+ public async Task GetAllDiscountUsageHistoryTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ var discountUsageHistory = new DiscountUsageHistory {
+ DiscountId = discount.Id,
+ OrderId = "123",
+ CouponCode = "TEST123"
+ };
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
+ var discountUsageHistory2 = new DiscountUsageHistory {
+ DiscountId = discount.Id,
+ OrderId = "124",
+ CouponCode = "TEST123"
+ };
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory2);
+ //Act
+ var usageHistory = await handler.Handle(new GetDiscountUsageHistoryQuery(), CancellationToken.None);
+
+ //Assert
+ Assert.AreEqual(2, usageHistory.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertDiscountUsageHistoryTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ var discountUsageHistory = new DiscountUsageHistory {
+ DiscountId = discount.Id,
+ OrderId = "123",
+ CouponCode = "TEST123"
+ };
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
+
+ //Act
+ var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
+
+ //Assert
+ Assert.IsNotNull(usageHistory);
+ Assert.AreEqual(discountUsageHistory.CouponCode, usageHistory.CouponCode);
+ }
+
+ [TestMethod]
+ public async Task UpdateDiscountUsageHistoryTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ var discountUsageHistory = new DiscountUsageHistory {
+ DiscountId = discount.Id,
+ OrderId = "123",
+ CouponCode = "TEST123"
+ };
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
+
+ //Act
+ discountUsageHistory.OrderId = "12";
+ await _discountUsageHistoryRepository.UpdateAsync(discountUsageHistory);
+ var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
+
+ //Assert
+ Assert.IsNotNull(usageHistory);
+ Assert.AreEqual(discountUsageHistory.OrderId, usageHistory.OrderId);
+ }
+
+ [TestMethod]
+ public async Task DeleteDiscountUsageHistoryTest()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+ var discountCoupon = new DiscountCoupon {
+ CouponCode = "TEST123",
+ DiscountId = discount.Id,
+ Used = true
+ };
+ await _discountCouponRepository.InsertAsync(discountCoupon);
+
+ var discountUsageHistory = new DiscountUsageHistory {
+ DiscountId = discount.Id,
+ OrderId = "123",
+ CouponCode = "TEST123"
+ };
+ await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory);
+
+ //Act
+ await _discountUsageHistoryRepository.DeleteAsync(discountUsageHistory);
+ var usageHistory = await _dicountService.GetDiscountUsageHistoryById(discountUsageHistory.Id);
+
+ //Assert
+ Assert.IsNull(usageHistory);
+ }
+
+ [TestMethod]
+ public async Task GetDiscountAmountTest_global()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ DiscountAmount = 10,
+ CurrencyCode = "USD",
+ IsEnabled = true
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ //Act
+ var discountamount = await _dicountService.GetDiscountAmount(discount,
+ new Customer(),
+ new Currency { CurrencyCode = "USD" }, new Product(), 100);
+
+ //Assert
+ Assert.AreEqual(discount.DiscountAmount, discountamount);
+ }
+
+ public async Task GetDiscountAmountTest_AssignedToAllProducts()
+ {
+ //Arrange
+ var discount = new Discount {
+ Name = "test",
+ DiscountAmount = 10,
+ CurrencyCode = "USD",
+ IsEnabled = true,
+ DiscountTypeId = DiscountType.AssignedToAllProducts
+ };
+ await _dicountService.InsertDiscount(discount);
+
+ //Act
+ var discountamount = await _dicountService.GetDiscountAmount(discount,
+ new Customer(),
+ new Currency { CurrencyCode = "USD" }, new Product(), 100);
+
+ //Assert
+ Assert.AreEqual(discount.DiscountAmount, discountamount);
+ }
+
+ [TestMethod]
+ public async Task GetPreferredDiscountTest()
+ {
+ //Arrange
+ var discount1 = new Discount {
+ Name = "test",
+ DiscountAmount = 10,
+ CurrencyCode = "USD",
+ IsEnabled = true,
+ DiscountTypeId = DiscountType.AssignedToAllProducts
+ };
+ await _dicountService.InsertDiscount(discount1);
+ var discount2 = new Discount {
+ Name = "test",
+ DiscountAmount = 20,
+ CurrencyCode = "USD",
+ IsEnabled = true,
+ DiscountTypeId = DiscountType.AssignedToAllProducts
+ };
+ await _dicountService.InsertDiscount(discount2);
+ //Act
+ var discountamount = await _dicountService.GetPreferredDiscount(
+ new List<ApplyDiscount> {
+ new() { DiscountId = discount1.Id, IsCumulative = false },
+ new() { DiscountId = discount2.Id, IsCumulative = false }
+ },
+ new Customer(),
+ new Currency { CurrencyCode = "USD" }, new Product(), 100);
+
+ //Assert
+ Assert.AreEqual(discount2.DiscountAmount, discountamount.discountAmount);
+ }
+
+ [TestMethod]
+ public async Task GetPreferredDiscountTest_IsCumulative_True()
+ {
+ //Arrange
+ var discount1 = new Discount {
+ Name = "test",
+ DiscountAmount = 10,
+ CurrencyCode = "USD",
+ IsEnabled = true,
+ DiscountTypeId = DiscountType.AssignedToAllProducts
+ };
+ await _dicountService.InsertDiscount(discount1);
+ var discount2 = new Discount {
+ Name = "test",
+ DiscountAmount = 20,
+ CurrencyCode = "USD",
+ IsEnabled = true,
+ DiscountTypeId = DiscountType.AssignedToAllProducts
+ };
+ await _dicountService.InsertDiscount(discount2);
+ //Act
+ var discountamount = await _dicountService.GetPreferredDiscount(
+ new List<ApplyDiscount> {
+ new() { DiscountId = discount1.Id, IsCumulative = true },
+ new() { DiscountId = discount2.Id, IsCumulative = true }
+ },
+ new Customer(),
+ new Currency { CurrencyCode = "USD" }, new Product(), 100);
+
+ //Assert
+ Assert.AreEqual(discount1.DiscountAmount + discount2.DiscountAmount, discountamount.discountAmount);
+ }
+
+ [TestMethod]
+ public async Task GetDiscountAmountProviderTest()
+ {
+ //Arrange
+ var discount1 = new Discount {
+ Name = "test",
+ DiscountAmount = 10,
+ CurrencyCode = "USD",
+ IsEnabled = true,
+ CalculateByPlugin = true,
+ DiscountPluginName = "SampleDiscountAmountProvider",
+ DiscountTypeId = DiscountType.AssignedToAllProducts
+ };
+ await _dicountService.InsertDiscount(discount1);
+ //Act
+ var amount = await _getDiscountAmountProviderHandler.Handle(
+ new GetDiscountAmountProvider(discount1, new Customer(), new Product(), new Currency(), 100),
+ CancellationToken.None);
+ //Assert
+ Assert.AreEqual(9, amount);
+ }
+
+ [TestMethod]
+ public void LoadDiscountAmountProviderBySystemNameTest()
+ {
+ //Act
+ var discountProvider =
+ _discountProviderLoader.LoadDiscountAmountProviderBySystemName("SampleDiscountAmountProvider");
+ //Assert
+ Assert.IsNotNull(discountProvider);
+ }
+
+ [TestMethod]
+ public void LoadDiscountAmountProvidersTest()
+ {
+ //Act
+ var discountProviders = _discountProviderLoader.LoadDiscountAmountProviders();
+ //Assert
+ Assert.AreEqual(1, discountProviders.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
index 59b4f9b05..e094276c0 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/BrandImportDataObjectTests.cs
@@ -6,11 +6,13 @@ using Grand.Business.Core.Interfaces.Catalog.Brands;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Storage;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Localization;
+using Grand.Domain.Seo;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -21,157 +23,166 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.ExportImport
+namespace Grand.Business.Catalog.Tests.Services.ExportImport;
+
+[TestClass]
+public class BrandImportDataObjectTests
{
- [TestClass()]
- public class BrandImportDataObjectTests
- {
- private BrandImportDataObject _brandImportDataObject;
- private IBrandService _brandService;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IPictureService> _pictureServiceMock;
- private Mock<IBrandLayoutService> _brandLayoutServiceMock;
- private Mock<ISlugService> _slugServiceMock;
- private Mock<ILanguageService> _languageServiceMock;
+ private BrandImportDataObject _brandImportDataObject;
+ private Mock<IBrandLayoutService> _brandLayoutServiceMock;
+ private IBrandService _brandService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<ILanguageService> _languageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IPictureService> _pictureServiceMock;
- private IRepository<Brand> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
+ private IRepository<Brand> _repository;
+ private Mock<ISlugService> _slugServiceMock;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- InitAutoMapper();
+ [TestInitialize]
+ public void Init()
+ {
+ InitAutoMapper();
+
+ _repository = new MongoDBRepositoryTest<Brand>();
+
+ _pictureServiceMock = new Mock<IPictureService>();
+ _brandLayoutServiceMock = new Mock<IBrandLayoutService>();
+ _slugServiceMock = new Mock<ISlugService>();
+ _languageServiceMock = new Mock<ILanguageService>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _brandService = new BrandService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object,
+ new AccessControlConfig());
+
+ _brandImportDataObject = new BrandImportDataObject(_brandService, _pictureServiceMock.Object,
+ _brandLayoutServiceMock.Object, _slugServiceMock.Object, _languageServiceMock.Object, new SeoSettings());
+ }
- _repository = new MongoDBRepositoryTest<Brand>();
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert()
+ {
+ //Arrange
+ var brands = new List<BrandDto>();
+ brands.Add(new BrandDto { Name = "test1", Published = true });
+ brands.Add(new BrandDto { Name = "test2", Published = true });
+ brands.Add(new BrandDto { Name = "test3", Published = true });
+ _brandLayoutServiceMock.Setup(c => c.GetBrandLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new BrandLayout()));
+ _brandLayoutServiceMock.Setup(c => c.GetAllBrandLayouts())
+ .Returns(Task.FromResult<IList<BrandLayout>>(new List<BrandLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _brandImportDataObject.Execute(brands);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ }
- _pictureServiceMock = new Mock<IPictureService>();
- _brandLayoutServiceMock = new Mock<IBrandLayoutService>();
- _slugServiceMock = new Mock<ISlugService>();
- _languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ [TestMethod]
+ public async Task ExecuteTest_Import_Update()
+ {
+ //Arrange
+ var brand1 = new Brand {
+ Name = "insert1"
+ };
+ await _brandService.InsertBrand(brand1);
+ var brand2 = new Brand {
+ Name = "insert2"
+ };
+ await _brandService.InsertBrand(brand2);
+ var brand3 = new Brand {
+ Name = "insert3"
+ };
+ await _brandService.InsertBrand(brand3);
+
+
+ var brands = new List<BrandDto>();
+ brands.Add(new BrandDto { Id = brand1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
+ brands.Add(new BrandDto { Id = brand2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
+ brands.Add(new BrandDto { Id = brand3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _brandLayoutServiceMock.Setup(c => c.GetBrandLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new BrandLayout()));
+ _brandLayoutServiceMock.Setup(c => c.GetAllBrandLayouts())
+ .Returns(Task.FromResult<IList<BrandLayout>>(new List<BrandLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _brandImportDataObject.Execute(brands);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Published);
+ }
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _brandService = new BrandService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object, new AccessControlConfig());
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert_Update()
+ {
+ //Arrange
+ var brand3 = new Brand {
+ Name = "insert3"
+ };
+ await _brandService.InsertBrand(brand3);
+
+ var brands = new List<BrandDto>();
+ brands.Add(new BrandDto { Name = "update1", Published = false, DisplayOrder = 1 });
+ brands.Add(new BrandDto { Name = "update2", Published = false, DisplayOrder = 2 });
+ brands.Add(new BrandDto { Id = brand3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _brandLayoutServiceMock.Setup(c => c.GetBrandLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new BrandLayout()));
+ _brandLayoutServiceMock.Setup(c => c.GetAllBrandLayouts())
+ .Returns(Task.FromResult<IList<BrandLayout>>(new List<BrandLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _brandImportDataObject.Execute(brands);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Published);
+ }
- _brandImportDataObject = new BrandImportDataObject(_brandService, _pictureServiceMock.Object, _brandLayoutServiceMock.Object, _slugServiceMock.Object, _languageServiceMock.Object, new Domain.Seo.SeoSettings());
- }
+ private void InitAutoMapper()
+ {
+ var typeSearcher = new TypeSearcher();
+ //find mapper configurations provided by other assemblies
+ var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert()
- {
- //Arrange
- var brands = new List<BrandDto>();
- brands.Add(new BrandDto { Name = "test1", Published = true });
- brands.Add(new BrandDto { Name = "test2", Published = true });
- brands.Add(new BrandDto { Name = "test3", Published = true });
- _brandLayoutServiceMock.Setup(c => c.GetBrandLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new BrandLayout()));
- _brandLayoutServiceMock.Setup(c => c.GetAllBrandLayouts()).Returns(Task.FromResult<IList<BrandLayout>>(new List<BrandLayout> { new BrandLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _brandImportDataObject.Execute(brands);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
-
- }
- [TestMethod()]
- public async Task ExecuteTest_Import_Update()
- {
- //Arrange
- var brand1 = new Brand {
- Name = "insert1"
- };
- await _brandService.InsertBrand(brand1);
- var brand2 = new Brand {
- Name = "insert2"
- };
- await _brandService.InsertBrand(brand2);
- var brand3 = new Brand {
- Name = "insert3"
- };
- await _brandService.InsertBrand(brand3);
-
-
- var brands = new List<BrandDto>();
- brands.Add(new BrandDto { Id = brand1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
- brands.Add(new BrandDto { Id = brand2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
- brands.Add(new BrandDto { Id = brand3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _brandLayoutServiceMock.Setup(c => c.GetBrandLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new BrandLayout()));
- _brandLayoutServiceMock.Setup(c => c.GetAllBrandLayouts()).Returns(Task.FromResult<IList<BrandLayout>>(new List<BrandLayout> { new BrandLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _brandImportDataObject.Execute(brands);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Published);
-
- }
-
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert_Update()
- {
- //Arrange
- var brand3 = new Brand {
- Name = "insert3"
- };
- await _brandService.InsertBrand(brand3);
-
- var brands = new List<BrandDto>();
- brands.Add(new BrandDto { Name = "update1", Published = false, DisplayOrder = 1 });
- brands.Add(new BrandDto { Name = "update2", Published = false, DisplayOrder = 2 });
- brands.Add(new BrandDto { Id = brand3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _brandLayoutServiceMock.Setup(c => c.GetBrandLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new BrandLayout()));
- _brandLayoutServiceMock.Setup(c => c.GetAllBrandLayouts()).Returns(Task.FromResult<IList<BrandLayout>>(new List<BrandLayout> { new BrandLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _brandImportDataObject.Execute(brands);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == brand3.Id).Published);
-
- }
-
- private void InitAutoMapper()
+ //create and sort instances of mapper configurations
+ var instances = mapperConfigurations
+ .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
+ .OrderBy(mapperConfiguration => mapperConfiguration.Order);
+
+ //create AutoMapper configuration
+ var config = new MapperConfiguration(cfg =>
{
- var typeSearcher = new TypeSearcher();
- //find mapper configurations provided by other assemblies
- var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
-
- //create and sort instances of mapper configurations
- var instances = mapperConfigurations
- .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
- .OrderBy(mapperConfiguration => mapperConfiguration.Order);
-
- //create AutoMapper configuration
- var config = new MapperConfiguration(cfg =>
- {
- foreach (var instance in instances)
- {
- cfg.AddProfile(instance.GetType());
- }
- });
-
- //register automapper
- AutoMapperConfig.Init(config);
- }
+ foreach (var instance in instances) cfg.AddProfile(instance.GetType());
+ });
+
+ //register automapper
+ AutoMapperConfig.Init(config);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
index 2f6e494a8..a7cef7ebf 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CategoryImportDataObjectTests.cs
@@ -7,11 +7,13 @@ using Grand.Business.Core.Interfaces.Catalog.Categories;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Storage;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Localization;
+using Grand.Domain.Seo;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -22,157 +24,166 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.ExportImport
+namespace Grand.Business.Catalog.Tests.Services.ExportImport;
+
+[TestClass]
+public class CategoryImportDataObjectTests
{
- [TestClass()]
- public class CategoryImportDataObjectTests
- {
- private CategoryImportDataObject _categoryImportDataObject;
- private ICategoryService _categoryService;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IPictureService> _pictureServiceMock;
- private Mock<ICategoryLayoutService> _categoryLayoutServiceMock;
- private Mock<ISlugService> _slugServiceMock;
- private Mock<ILanguageService> _languageServiceMock;
+ private MemoryCacheBase _cacheBase;
+ private CategoryImportDataObject _categoryImportDataObject;
+ private Mock<ICategoryLayoutService> _categoryLayoutServiceMock;
+ private ICategoryService _categoryService;
+ private Mock<ILanguageService> _languageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IPictureService> _pictureServiceMock;
- private IRepository<Category> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
+ private IRepository<Category> _repository;
+ private Mock<ISlugService> _slugServiceMock;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- InitAutoMapper();
+ [TestInitialize]
+ public void Init()
+ {
+ InitAutoMapper();
+
+ _repository = new MongoDBRepositoryTest<Category>();
+
+ _pictureServiceMock = new Mock<IPictureService>();
+ _categoryLayoutServiceMock = new Mock<ICategoryLayoutService>();
+ _slugServiceMock = new Mock<ISlugService>();
+ _languageServiceMock = new Mock<ILanguageService>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _categoryService = new CategoryService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object,
+ new AclService(new AccessControlConfig()), new AccessControlConfig());
+
+ _categoryImportDataObject = new CategoryImportDataObject(_categoryService, _pictureServiceMock.Object,
+ _categoryLayoutServiceMock.Object, _slugServiceMock.Object, _languageServiceMock.Object, new SeoSettings());
+ }
- _repository = new MongoDBRepositoryTest<Category>();
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert()
+ {
+ //Arrange
+ var categorys = new List<CategoryDto>();
+ categorys.Add(new CategoryDto { Name = "test1", Published = true });
+ categorys.Add(new CategoryDto { Name = "test2", Published = true });
+ categorys.Add(new CategoryDto { Name = "test3", Published = true });
+ _categoryLayoutServiceMock.Setup(c => c.GetCategoryLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new CategoryLayout()));
+ _categoryLayoutServiceMock.Setup(c => c.GetAllCategoryLayouts())
+ .Returns(Task.FromResult<IList<CategoryLayout>>(new List<CategoryLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _categoryImportDataObject.Execute(categorys);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ }
- _pictureServiceMock = new Mock<IPictureService>();
- _categoryLayoutServiceMock = new Mock<ICategoryLayoutService>();
- _slugServiceMock = new Mock<ISlugService>();
- _languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ [TestMethod]
+ public async Task ExecuteTest_Import_Update()
+ {
+ //Arrange
+ var category1 = new Category {
+ Name = "insert1"
+ };
+ await _categoryService.InsertCategory(category1);
+ var category2 = new Category {
+ Name = "insert2"
+ };
+ await _categoryService.InsertCategory(category2);
+ var category3 = new Category {
+ Name = "insert3"
+ };
+ await _categoryService.InsertCategory(category3);
+
+
+ var categorys = new List<CategoryDto>();
+ categorys.Add(new CategoryDto { Id = category1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
+ categorys.Add(new CategoryDto { Id = category2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
+ categorys.Add(new CategoryDto { Id = category3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _categoryLayoutServiceMock.Setup(c => c.GetCategoryLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new CategoryLayout()));
+ _categoryLayoutServiceMock.Setup(c => c.GetAllCategoryLayouts())
+ .Returns(Task.FromResult<IList<CategoryLayout>>(new List<CategoryLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _categoryImportDataObject.Execute(categorys);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Published);
+ }
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _categoryService = new CategoryService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object, new AclService(new AccessControlConfig()), new AccessControlConfig());
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert_Update()
+ {
+ //Arrange
+ var category3 = new Category {
+ Name = "insert3"
+ };
+ await _categoryService.InsertCategory(category3);
+
+ var categorys = new List<CategoryDto>();
+ categorys.Add(new CategoryDto { Name = "update1", Published = false, DisplayOrder = 1 });
+ categorys.Add(new CategoryDto { Name = "update2", Published = false, DisplayOrder = 2 });
+ categorys.Add(new CategoryDto { Id = category3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _categoryLayoutServiceMock.Setup(c => c.GetCategoryLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new CategoryLayout()));
+ _categoryLayoutServiceMock.Setup(c => c.GetAllCategoryLayouts())
+ .Returns(Task.FromResult<IList<CategoryLayout>>(new List<CategoryLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _categoryImportDataObject.Execute(categorys);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Published);
+ }
- _categoryImportDataObject = new CategoryImportDataObject(_categoryService, _pictureServiceMock.Object, _categoryLayoutServiceMock.Object, _slugServiceMock.Object, _languageServiceMock.Object, new Domain.Seo.SeoSettings());
- }
+ private void InitAutoMapper()
+ {
+ var typeSearcher = new TypeSearcher();
+ //find mapper configurations provided by other assemblies
+ var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert()
- {
- //Arrange
- var categorys = new List<CategoryDto>();
- categorys.Add(new CategoryDto { Name = "test1", Published = true });
- categorys.Add(new CategoryDto { Name = "test2", Published = true });
- categorys.Add(new CategoryDto { Name = "test3", Published = true });
- _categoryLayoutServiceMock.Setup(c => c.GetCategoryLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new CategoryLayout()));
- _categoryLayoutServiceMock.Setup(c => c.GetAllCategoryLayouts()).Returns(Task.FromResult<IList<CategoryLayout>>(new List<CategoryLayout> { new CategoryLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _categoryImportDataObject.Execute(categorys);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
-
- }
- [TestMethod()]
- public async Task ExecuteTest_Import_Update()
- {
- //Arrange
- var category1 = new Category {
- Name = "insert1"
- };
- await _categoryService.InsertCategory(category1);
- var category2 = new Category {
- Name = "insert2"
- };
- await _categoryService.InsertCategory(category2);
- var category3 = new Category {
- Name = "insert3"
- };
- await _categoryService.InsertCategory(category3);
-
-
- var categorys = new List<CategoryDto>();
- categorys.Add(new CategoryDto { Id = category1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
- categorys.Add(new CategoryDto { Id = category2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
- categorys.Add(new CategoryDto { Id = category3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _categoryLayoutServiceMock.Setup(c => c.GetCategoryLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new CategoryLayout()));
- _categoryLayoutServiceMock.Setup(c => c.GetAllCategoryLayouts()).Returns(Task.FromResult<IList<CategoryLayout>>(new List<CategoryLayout> { new CategoryLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _categoryImportDataObject.Execute(categorys);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Published);
-
- }
-
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert_Update()
- {
- //Arrange
- var category3 = new Category {
- Name = "insert3"
- };
- await _categoryService.InsertCategory(category3);
-
- var categorys = new List<CategoryDto>();
- categorys.Add(new CategoryDto { Name = "update1", Published = false, DisplayOrder = 1 });
- categorys.Add(new CategoryDto { Name = "update2", Published = false, DisplayOrder = 2 });
- categorys.Add(new CategoryDto { Id = category3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _categoryLayoutServiceMock.Setup(c => c.GetCategoryLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new CategoryLayout()));
- _categoryLayoutServiceMock.Setup(c => c.GetAllCategoryLayouts()).Returns(Task.FromResult<IList<CategoryLayout>>(new List<CategoryLayout> { new CategoryLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _categoryImportDataObject.Execute(categorys);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == category3.Id).Published);
-
- }
-
- private void InitAutoMapper()
+ //create and sort instances of mapper configurations
+ var instances = mapperConfigurations
+ .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
+ .OrderBy(mapperConfiguration => mapperConfiguration.Order);
+
+ //create AutoMapper configuration
+ var config = new MapperConfiguration(cfg =>
{
- var typeSearcher = new TypeSearcher();
- //find mapper configurations provided by other assemblies
- var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
-
- //create and sort instances of mapper configurations
- var instances = mapperConfigurations
- .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
- .OrderBy(mapperConfiguration => mapperConfiguration.Order);
-
- //create AutoMapper configuration
- var config = new MapperConfiguration(cfg =>
- {
- foreach (var instance in instances)
- {
- cfg.AddProfile(instance.GetType());
- }
- });
-
- //register automapper
- AutoMapperConfig.Init(config);
- }
+ foreach (var instance in instances) cfg.AddProfile(instance.GetType());
+ });
+
+ //register automapper
+ AutoMapperConfig.Init(config);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
index db868f6f3..5d71388a2 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/CollectionImportDataObjectTests.cs
@@ -7,11 +7,13 @@ using Grand.Business.Core.Interfaces.Catalog.Collections;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Storage;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Localization;
+using Grand.Domain.Seo;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -22,157 +24,171 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.ExportImport
+namespace Grand.Business.Catalog.Tests.Services.ExportImport;
+
+[TestClass]
+public class CollectionImportDataObjectTests
{
- [TestClass()]
- public class CollectionImportDataObjectTests
- {
- private CollectionImportDataObject _collectionImportDataObject;
- private ICollectionService _collectionService;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IPictureService> _pictureServiceMock;
- private Mock<ICollectionLayoutService> _collectionLayoutServiceMock;
- private Mock<ISlugService> _slugServiceMock;
- private Mock<ILanguageService> _languageServiceMock;
+ private MemoryCacheBase _cacheBase;
+ private CollectionImportDataObject _collectionImportDataObject;
+ private Mock<ICollectionLayoutService> _collectionLayoutServiceMock;
+ private ICollectionService _collectionService;
+ private Mock<ILanguageService> _languageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IPictureService> _pictureServiceMock;
- private IRepository<Collection> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
+ private IRepository<Collection> _repository;
+ private Mock<ISlugService> _slugServiceMock;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- InitAutoMapper();
+ [TestInitialize]
+ public void Init()
+ {
+ InitAutoMapper();
+
+ _repository = new MongoDBRepositoryTest<Collection>();
+
+ _pictureServiceMock = new Mock<IPictureService>();
+ _collectionLayoutServiceMock = new Mock<ICollectionLayoutService>();
+ _slugServiceMock = new Mock<ISlugService>();
+ _languageServiceMock = new Mock<ILanguageService>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _collectionService = new CollectionService(_cacheBase, _repository, _workContextMock.Object,
+ _mediatorMock.Object, new AclService(new AccessControlConfig()), new AccessControlConfig());
+
+ _collectionImportDataObject = new CollectionImportDataObject(_collectionService, _pictureServiceMock.Object,
+ _collectionLayoutServiceMock.Object, _slugServiceMock.Object, _languageServiceMock.Object,
+ new SeoSettings());
+ }
- _repository = new MongoDBRepositoryTest<Collection>();
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert()
+ {
+ //Arrange
+ var collections = new List<CollectionDto>();
+ collections.Add(new CollectionDto { Name = "test1", Published = true });
+ collections.Add(new CollectionDto { Name = "test2", Published = true });
+ collections.Add(new CollectionDto { Name = "test3", Published = true });
+ _collectionLayoutServiceMock.Setup(c => c.GetCollectionLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new CollectionLayout()));
+ _collectionLayoutServiceMock.Setup(c => c.GetAllCollectionLayouts())
+ .Returns(Task.FromResult<IList<CollectionLayout>>(new List<CollectionLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _collectionImportDataObject.Execute(collections);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ }
- _pictureServiceMock = new Mock<IPictureService>();
- _collectionLayoutServiceMock = new Mock<ICollectionLayoutService>();
- _slugServiceMock = new Mock<ISlugService>();
- _languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ [TestMethod]
+ public async Task ExecuteTest_Import_Update()
+ {
+ //Arrange
+ var collection1 = new Collection {
+ Name = "insert1"
+ };
+ await _collectionService.InsertCollection(collection1);
+ var collection2 = new Collection {
+ Name = "insert2"
+ };
+ await _collectionService.InsertCollection(collection2);
+ var collection3 = new Collection {
+ Name = "insert3"
+ };
+ await _collectionService.InsertCollection(collection3);
+
+
+ var collections = new List<CollectionDto>();
+ collections.Add(
+ new CollectionDto { Id = collection1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
+ collections.Add(
+ new CollectionDto { Id = collection2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
+ collections.Add(
+ new CollectionDto { Id = collection3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _collectionLayoutServiceMock.Setup(c => c.GetCollectionLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new CollectionLayout()));
+ _collectionLayoutServiceMock.Setup(c => c.GetAllCollectionLayouts())
+ .Returns(Task.FromResult<IList<CollectionLayout>>(new List<CollectionLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _collectionImportDataObject.Execute(collections);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Published);
+ }
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _collectionService = new CollectionService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object, new AclService(new AccessControlConfig()), new AccessControlConfig());
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert_Update()
+ {
+ //Arrange
+ var collection3 = new Collection {
+ Name = "insert3"
+ };
+ await _collectionService.InsertCollection(collection3);
+
+ var collections = new List<CollectionDto>();
+ collections.Add(new CollectionDto { Name = "update1", Published = false, DisplayOrder = 1 });
+ collections.Add(new CollectionDto { Name = "update2", Published = false, DisplayOrder = 2 });
+ collections.Add(
+ new CollectionDto { Id = collection3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _collectionLayoutServiceMock.Setup(c => c.GetCollectionLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new CollectionLayout()));
+ _collectionLayoutServiceMock.Setup(c => c.GetAllCollectionLayouts())
+ .Returns(Task.FromResult<IList<CollectionLayout>>(new List<CollectionLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _collectionImportDataObject.Execute(collections);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Published);
+ }
- _collectionImportDataObject = new CollectionImportDataObject(_collectionService, _pictureServiceMock.Object, _collectionLayoutServiceMock.Object, _slugServiceMock.Object, _languageServiceMock.Object, new Domain.Seo.SeoSettings());
- }
+ private void InitAutoMapper()
+ {
+ var typeSearcher = new TypeSearcher();
+ //find mapper configurations provided by other assemblies
+ var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert()
- {
- //Arrange
- var collections = new List<CollectionDto>();
- collections.Add(new CollectionDto { Name = "test1", Published = true });
- collections.Add(new CollectionDto { Name = "test2", Published = true });
- collections.Add(new CollectionDto { Name = "test3", Published = true });
- _collectionLayoutServiceMock.Setup(c => c.GetCollectionLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new CollectionLayout()));
- _collectionLayoutServiceMock.Setup(c => c.GetAllCollectionLayouts()).Returns(Task.FromResult<IList<CollectionLayout>>(new List<CollectionLayout> { new CollectionLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _collectionImportDataObject.Execute(collections);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
-
- }
- [TestMethod()]
- public async Task ExecuteTest_Import_Update()
- {
- //Arrange
- var collection1 = new Collection {
- Name = "insert1"
- };
- await _collectionService.InsertCollection(collection1);
- var collection2 = new Collection {
- Name = "insert2"
- };
- await _collectionService.InsertCollection(collection2);
- var collection3 = new Collection {
- Name = "insert3"
- };
- await _collectionService.InsertCollection(collection3);
-
-
- var collections = new List<CollectionDto>();
- collections.Add(new CollectionDto { Id = collection1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
- collections.Add(new CollectionDto { Id = collection2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
- collections.Add(new CollectionDto { Id = collection3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _collectionLayoutServiceMock.Setup(c => c.GetCollectionLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new CollectionLayout()));
- _collectionLayoutServiceMock.Setup(c => c.GetAllCollectionLayouts()).Returns(Task.FromResult<IList<CollectionLayout>>(new List<CollectionLayout> { new CollectionLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _collectionImportDataObject.Execute(collections);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Published);
-
- }
-
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert_Update()
- {
- //Arrange
- var collection3 = new Collection {
- Name = "insert3"
- };
- await _collectionService.InsertCollection(collection3);
-
- var collections = new List<CollectionDto>();
- collections.Add(new CollectionDto { Name = "update1", Published = false, DisplayOrder = 1 });
- collections.Add(new CollectionDto { Name = "update2", Published = false, DisplayOrder = 2 });
- collections.Add(new CollectionDto { Id = collection3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _collectionLayoutServiceMock.Setup(c => c.GetCollectionLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new CollectionLayout()));
- _collectionLayoutServiceMock.Setup(c => c.GetAllCollectionLayouts()).Returns(Task.FromResult<IList<CollectionLayout>>(new List<CollectionLayout> { new CollectionLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _collectionImportDataObject.Execute(collections);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == collection3.Id).Published);
-
- }
-
- private void InitAutoMapper()
+ //create and sort instances of mapper configurations
+ var instances = mapperConfigurations
+ .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
+ .OrderBy(mapperConfiguration => mapperConfiguration.Order);
+
+ //create AutoMapper configuration
+ var config = new MapperConfiguration(cfg =>
{
- var typeSearcher = new TypeSearcher();
- //find mapper configurations provided by other assemblies
- var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
-
- //create and sort instances of mapper configurations
- var instances = mapperConfigurations
- .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
- .OrderBy(mapperConfiguration => mapperConfiguration.Order);
-
- //create AutoMapper configuration
- var config = new MapperConfiguration(cfg =>
- {
- foreach (var instance in instances)
- {
- cfg.AddProfile(instance.GetType());
- }
- });
-
- //register automapper
- AutoMapperConfig.Init(config);
- }
+ foreach (var instance in instances) cfg.AddProfile(instance.GetType());
+ });
+
+ //register automapper
+ AutoMapperConfig.Init(config);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
index 7091b6e99..120378b96 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/ExportImport/ProductImportDataObjectTests.cs
@@ -13,11 +13,16 @@ using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Seo;
using Grand.Business.Core.Interfaces.Storage;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Directory;
using Grand.Domain.Localization;
+using Grand.Domain.Seo;
+using Grand.Domain.Shipping;
+using Grand.Domain.Stores;
+using Grand.Domain.Tax;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -28,222 +33,256 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.ExportImport
+namespace Grand.Business.Catalog.Tests.Services.ExportImport;
+
+[TestClass]
+public class ProductImportDataObjectTests
{
- [TestClass()]
- public class ProductImportDataObjectTests
+ private Mock<IBrandService> _brandServiceMock;
+ private MemoryCacheBase _cacheBase;
+ private Mock<ICategoryService> _categoryServiceMock;
+ private Mock<ICollectionService> _collectionServiceMock;
+
+ private Mock<IDeliveryDateService> _deliveryDateServiceMock;
+ private Mock<ILanguageService> _languageServiceMock;
+ private Mock<IMeasureService> _measureServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IPictureService> _pictureServiceMock;
+ private Mock<IProductCategoryService> _productCategoryServiceMock;
+ private Mock<IProductCollectionService> _productCollectionServiceMock;
+ private ProductImportDataObject _productImportDataObject;
+ private Mock<IProductLayoutService> _productLayoutServiceMock;
+ private IProductService _productService;
+
+ private IRepository<Product> _repository;
+ private Mock<ISlugService> _slugServiceMock;
+ private Mock<ITaxCategoryService> _taxServiceMock;
+ private Mock<IWarehouseService> _warehouseServiceMock;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
{
- private ProductImportDataObject _productImportDataObject;
- private IProductService _productService;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IPictureService> _pictureServiceMock;
- private Mock<IProductLayoutService> _productLayoutServiceMock;
- private Mock<ISlugService> _slugServiceMock;
- private Mock<ILanguageService> _languageServiceMock;
-
- private Mock<IDeliveryDateService> _deliveryDateServiceMock;
- private Mock<ITaxCategoryService> _taxServiceMock;
- private Mock<IWarehouseService> _warehouseServiceMock;
- private Mock<IMeasureService> _measureServiceMock;
- private Mock<ICategoryService> _categoryServiceMock;
- private Mock<IProductCategoryService> _productCategoryServiceMock;
- private Mock<IBrandService> _brandServiceMock;
- private Mock<ICollectionService> _collectionServiceMock;
- private Mock<IProductCollectionService> _productCollectionServiceMock;
-
- private IRepository<Product> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void Init()
- {
- InitAutoMapper();
-
- _repository = new MongoDBRepositoryTest<Product>();
-
- _pictureServiceMock = new Mock<IPictureService>();
- _productLayoutServiceMock = new Mock<IProductLayoutService>();
- _slugServiceMock = new Mock<ISlugService>();
- _languageServiceMock = new Mock<ILanguageService>();
- _deliveryDateServiceMock = new Mock<IDeliveryDateService>();
- _brandServiceMock = new Mock<IBrandService>();
- _collectionServiceMock = new Mock<ICollectionService>();
- _taxServiceMock = new Mock<ITaxCategoryService>();
- _categoryServiceMock = new Mock<ICategoryService>();
- _warehouseServiceMock = new Mock<IWarehouseService>();
- _measureServiceMock = new Mock<IMeasureService>();
- _productCategoryServiceMock = new Mock<IProductCategoryService>();
- _productCollectionServiceMock = new Mock<IProductCollectionService>();
-
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
-
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _productService = new ProductService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object, new AclService(new AccessControlConfig()));
-
- _productImportDataObject = new ProductImportDataObject
- (_productService, _pictureServiceMock.Object, _productLayoutServiceMock.Object, _deliveryDateServiceMock.Object,
- _taxServiceMock.Object, _warehouseServiceMock.Object, _measureServiceMock.Object, _slugServiceMock.Object, _languageServiceMock.Object,
- _categoryServiceMock.Object, _productCategoryServiceMock.Object, _brandServiceMock.Object, _collectionServiceMock.Object,
- _productCollectionServiceMock.Object,
- new Domain.Seo.SeoSettings());
- }
-
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert()
- {
- //Arrange
- var products = new List<ProductDto>();
- products.Add(new ProductDto { Name = "test1", Published = true });
- products.Add(new ProductDto { Name = "test2", Published = true });
- products.Add(new ProductDto { Name = "test3", Published = true });
-
- _productLayoutServiceMock.Setup(c => c.GetProductLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new ProductLayout()));
- _productLayoutServiceMock.Setup(c => c.GetAllProductLayouts()).Returns(Task.FromResult<IList<ProductLayout>>(new List<ProductLayout> { new ProductLayout() }));
-
- _deliveryDateServiceMock.Setup(c => c.GetDeliveryDateById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Shipping.DeliveryDate()));
- _deliveryDateServiceMock.Setup(c => c.GetAllDeliveryDates()).Returns(Task.FromResult<IList<Domain.Shipping.DeliveryDate>>(new List<Domain.Shipping.DeliveryDate> { new Domain.Shipping.DeliveryDate() }));
-
- _taxServiceMock.Setup(c => c.GetTaxCategoryById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Tax.TaxCategory()));
- _taxServiceMock.Setup(c => c.GetAllTaxCategories()).Returns(Task.FromResult<IList<Domain.Tax.TaxCategory>>(new List<Domain.Tax.TaxCategory> { new Domain.Tax.TaxCategory() }));
+ InitAutoMapper();
+
+ _repository = new MongoDBRepositoryTest<Product>();
+
+ _pictureServiceMock = new Mock<IPictureService>();
+ _productLayoutServiceMock = new Mock<IProductLayoutService>();
+ _slugServiceMock = new Mock<ISlugService>();
+ _languageServiceMock = new Mock<ILanguageService>();
+ _deliveryDateServiceMock = new Mock<IDeliveryDateService>();
+ _brandServiceMock = new Mock<IBrandService>();
+ _collectionServiceMock = new Mock<ICollectionService>();
+ _taxServiceMock = new Mock<ITaxCategoryService>();
+ _categoryServiceMock = new Mock<ICategoryService>();
+ _warehouseServiceMock = new Mock<IWarehouseService>();
+ _measureServiceMock = new Mock<IMeasureService>();
+ _productCategoryServiceMock = new Mock<IProductCategoryService>();
+ _productCollectionServiceMock = new Mock<IProductCollectionService>();
+
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _productService = new ProductService(_cacheBase, _repository, _workContextMock.Object, _mediatorMock.Object,
+ new AclService(new AccessControlConfig()));
+
+ _productImportDataObject = new ProductImportDataObject
+ (_productService, _pictureServiceMock.Object, _productLayoutServiceMock.Object, _deliveryDateServiceMock.Object,
+ _taxServiceMock.Object, _warehouseServiceMock.Object, _measureServiceMock.Object, _slugServiceMock.Object,
+ _languageServiceMock.Object,
+ _categoryServiceMock.Object, _productCategoryServiceMock.Object, _brandServiceMock.Object,
+ _collectionServiceMock.Object,
+ _productCollectionServiceMock.Object,
+ new SeoSettings());
+ }
- _warehouseServiceMock.Setup(c => c.GetWarehouseById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Shipping.Warehouse()));
- _warehouseServiceMock.Setup(c => c.GetAllWarehouses()).Returns(Task.FromResult<IList<Domain.Shipping.Warehouse>>(new List<Domain.Shipping.Warehouse> { new Domain.Shipping.Warehouse() }));
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert()
+ {
+ //Arrange
+ var products = new List<ProductDto>();
+ products.Add(new ProductDto { Name = "test1", Published = true });
+ products.Add(new ProductDto { Name = "test2", Published = true });
+ products.Add(new ProductDto { Name = "test3", Published = true });
+
+ _productLayoutServiceMock.Setup(c => c.GetProductLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new ProductLayout()));
+ _productLayoutServiceMock.Setup(c => c.GetAllProductLayouts())
+ .Returns(Task.FromResult<IList<ProductLayout>>(new List<ProductLayout> { new() }));
+
+ _deliveryDateServiceMock.Setup(c => c.GetDeliveryDateById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new DeliveryDate()));
+ _deliveryDateServiceMock.Setup(c => c.GetAllDeliveryDates())
+ .Returns(Task.FromResult<IList<DeliveryDate>>(new List<DeliveryDate> { new() }));
+
+ _taxServiceMock.Setup(c => c.GetTaxCategoryById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new TaxCategory()));
+ _taxServiceMock.Setup(c => c.GetAllTaxCategories())
+ .Returns(Task.FromResult<IList<TaxCategory>>(new List<TaxCategory> { new() }));
+
+ _warehouseServiceMock.Setup(c => c.GetWarehouseById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new Warehouse()));
+ _warehouseServiceMock.Setup(c => c.GetAllWarehouses())
+ .Returns(Task.FromResult<IList<Warehouse>>(new List<Warehouse> { new() }));
+
+ _measureServiceMock.Setup(c => c.GetMeasureUnitById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new MeasureUnit()));
+ _measureServiceMock.Setup(c => c.GetAllMeasureUnits())
+ .Returns(Task.FromResult<IList<MeasureUnit>>(new List<MeasureUnit> { new() }));
+
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+
+ //Act
+ await _productImportDataObject.Execute(products);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ }
- _measureServiceMock.Setup(c => c.GetMeasureUnitById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Directory.MeasureUnit()));
- _measureServiceMock.Setup(c => c.GetAllMeasureUnits()).Returns(Task.FromResult<IList<Domain.Directory.MeasureUnit>>(new List<Domain.Directory.MeasureUnit> { new Domain.Directory.MeasureUnit() }));
+ [TestMethod]
+ public async Task ExecuteTest_Import_Update()
+ {
+ //Arrange
+ var product1 = new Product {
+ Name = "insert1"
+ };
+ await _productService.InsertProduct(product1);
+ var product2 = new Product {
+ Name = "insert2"
+ };
+ await _productService.InsertProduct(product2);
+ var product3 = new Product {
+ Name = "insert3"
+ };
+ await _productService.InsertProduct(product3);
+
+
+ var products = new List<ProductDto>();
+ products.Add(new ProductDto { Id = product1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
+ products.Add(new ProductDto { Id = product2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
+ products.Add(new ProductDto { Id = product3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _productLayoutServiceMock.Setup(c => c.GetProductLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new ProductLayout()));
+ _productLayoutServiceMock.Setup(c => c.GetAllProductLayouts())
+ .Returns(Task.FromResult<IList<ProductLayout>>(new List<ProductLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+
+ _deliveryDateServiceMock.Setup(c => c.GetDeliveryDateById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new DeliveryDate()));
+ _deliveryDateServiceMock.Setup(c => c.GetAllDeliveryDates())
+ .Returns(Task.FromResult<IList<DeliveryDate>>(new List<DeliveryDate> { new() }));
+
+ _taxServiceMock.Setup(c => c.GetTaxCategoryById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new TaxCategory()));
+ _taxServiceMock.Setup(c => c.GetAllTaxCategories())
+ .Returns(Task.FromResult<IList<TaxCategory>>(new List<TaxCategory> { new() }));
+
+ _warehouseServiceMock.Setup(c => c.GetWarehouseById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new Warehouse()));
+ _warehouseServiceMock.Setup(c => c.GetAllWarehouses())
+ .Returns(Task.FromResult<IList<Warehouse>>(new List<Warehouse> { new() }));
+
+ _measureServiceMock.Setup(c => c.GetMeasureUnitById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new MeasureUnit()));
+ _measureServiceMock.Setup(c => c.GetAllMeasureUnits())
+ .Returns(Task.FromResult<IList<MeasureUnit>>(new List<MeasureUnit> { new() }));
+
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _productImportDataObject.Execute(products);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Published);
+ }
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert_Update()
+ {
+ //Arrange
+ var product3 = new Product {
+ Name = "insert3"
+ };
+ await _productService.InsertProduct(product3);
+
+ var products = new List<ProductDto>();
+ products.Add(new ProductDto { Name = "update1", Published = false, DisplayOrder = 1 });
+ products.Add(new ProductDto { Name = "update2", Published = false, DisplayOrder = 2 });
+ products.Add(new ProductDto { Id = product3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
+
+ _productLayoutServiceMock.Setup(c => c.GetProductLayoutById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new ProductLayout()));
+ _productLayoutServiceMock.Setup(c => c.GetAllProductLayouts())
+ .Returns(Task.FromResult<IList<ProductLayout>>(new List<ProductLayout> { new() }));
+ _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+
+ _deliveryDateServiceMock.Setup(c => c.GetDeliveryDateById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new DeliveryDate()));
+ _deliveryDateServiceMock.Setup(c => c.GetAllDeliveryDates())
+ .Returns(Task.FromResult<IList<DeliveryDate>>(new List<DeliveryDate> { new() }));
+
+ _taxServiceMock.Setup(c => c.GetTaxCategoryById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new TaxCategory()));
+ _taxServiceMock.Setup(c => c.GetAllTaxCategories())
+ .Returns(Task.FromResult<IList<TaxCategory>>(new List<TaxCategory> { new() }));
+
+ _warehouseServiceMock.Setup(c => c.GetWarehouseById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new Warehouse()));
+ _warehouseServiceMock.Setup(c => c.GetAllWarehouses())
+ .Returns(Task.FromResult<IList<Warehouse>>(new List<Warehouse> { new() }));
+
+ _measureServiceMock.Setup(c => c.GetMeasureUnitById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new MeasureUnit()));
+ _measureServiceMock.Setup(c => c.GetAllMeasureUnits())
+ .Returns(Task.FromResult<IList<MeasureUnit>>(new List<MeasureUnit> { new() }));
+
+ _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>()))
+ .Returns(Task.FromResult(new EntityUrl { Slug = "slug" }));
+ //Act
+ await _productImportDataObject.Execute(products);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(3, _repository.Table.Count());
+ Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Name);
+ Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).DisplayOrder);
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Published);
+ }
- //Act
- await _productImportDataObject.Execute(products);
+ private void InitAutoMapper()
+ {
+ var typeSearcher = new TypeSearcher();
+ //find mapper configurations provided by other assemblies
+ var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
+ //create and sort instances of mapper configurations
+ var instances = mapperConfigurations
+ .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
+ .OrderBy(mapperConfiguration => mapperConfiguration.Order);
- }
- [TestMethod()]
- public async Task ExecuteTest_Import_Update()
+ //create AutoMapper configuration
+ var config = new MapperConfiguration(cfg =>
{
- //Arrange
- var product1 = new Product {
- Name = "insert1"
- };
- await _productService.InsertProduct(product1);
- var product2 = new Product {
- Name = "insert2"
- };
- await _productService.InsertProduct(product2);
- var product3 = new Product {
- Name = "insert3"
- };
- await _productService.InsertProduct(product3);
-
-
- var products = new List<ProductDto>();
- products.Add(new ProductDto { Id = product1.Id, Name = "update1", Published = false, DisplayOrder = 1 });
- products.Add(new ProductDto { Id = product2.Id, Name = "update2", Published = false, DisplayOrder = 2 });
- products.Add(new ProductDto { Id = product3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _productLayoutServiceMock.Setup(c => c.GetProductLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new ProductLayout()));
- _productLayoutServiceMock.Setup(c => c.GetAllProductLayouts()).Returns(Task.FromResult<IList<ProductLayout>>(new List<ProductLayout> { new ProductLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
-
- _deliveryDateServiceMock.Setup(c => c.GetDeliveryDateById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Shipping.DeliveryDate()));
- _deliveryDateServiceMock.Setup(c => c.GetAllDeliveryDates()).Returns(Task.FromResult<IList<Domain.Shipping.DeliveryDate>>(new List<Domain.Shipping.DeliveryDate> { new Domain.Shipping.DeliveryDate() }));
-
- _taxServiceMock.Setup(c => c.GetTaxCategoryById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Tax.TaxCategory()));
- _taxServiceMock.Setup(c => c.GetAllTaxCategories()).Returns(Task.FromResult<IList<Domain.Tax.TaxCategory>>(new List<Domain.Tax.TaxCategory> { new Domain.Tax.TaxCategory() }));
-
- _warehouseServiceMock.Setup(c => c.GetWarehouseById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Shipping.Warehouse()));
- _warehouseServiceMock.Setup(c => c.GetAllWarehouses()).Returns(Task.FromResult<IList<Domain.Shipping.Warehouse>>(new List<Domain.Shipping.Warehouse> { new Domain.Shipping.Warehouse() }));
-
- _measureServiceMock.Setup(c => c.GetMeasureUnitById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Directory.MeasureUnit()));
- _measureServiceMock.Setup(c => c.GetAllMeasureUnits()).Returns(Task.FromResult<IList<Domain.Directory.MeasureUnit>>(new List<Domain.Directory.MeasureUnit> { new Domain.Directory.MeasureUnit() }));
-
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _productImportDataObject.Execute(products);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Published);
-
- }
-
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert_Update()
- {
- //Arrange
- var product3 = new Product {
- Name = "insert3"
- };
- await _productService.InsertProduct(product3);
-
- var products = new List<ProductDto>();
- products.Add(new ProductDto { Name = "update1", Published = false, DisplayOrder = 1 });
- products.Add(new ProductDto { Name = "update2", Published = false, DisplayOrder = 2 });
- products.Add(new ProductDto { Id = product3.Id, Name = "update3", Published = false, DisplayOrder = 3 });
-
- _productLayoutServiceMock.Setup(c => c.GetProductLayoutById(It.IsAny<string>())).Returns(Task.FromResult(new ProductLayout()));
- _productLayoutServiceMock.Setup(c => c.GetAllProductLayouts()).Returns(Task.FromResult<IList<ProductLayout>>(new List<ProductLayout> { new ProductLayout() }));
- _languageServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
-
- _deliveryDateServiceMock.Setup(c => c.GetDeliveryDateById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Shipping.DeliveryDate()));
- _deliveryDateServiceMock.Setup(c => c.GetAllDeliveryDates()).Returns(Task.FromResult<IList<Domain.Shipping.DeliveryDate>>(new List<Domain.Shipping.DeliveryDate> { new Domain.Shipping.DeliveryDate() }));
-
- _taxServiceMock.Setup(c => c.GetTaxCategoryById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Tax.TaxCategory()));
- _taxServiceMock.Setup(c => c.GetAllTaxCategories()).Returns(Task.FromResult<IList<Domain.Tax.TaxCategory>>(new List<Domain.Tax.TaxCategory> { new Domain.Tax.TaxCategory() }));
+ foreach (var instance in instances) cfg.AddProfile(instance.GetType());
+ });
- _warehouseServiceMock.Setup(c => c.GetWarehouseById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Shipping.Warehouse()));
- _warehouseServiceMock.Setup(c => c.GetAllWarehouses()).Returns(Task.FromResult<IList<Domain.Shipping.Warehouse>>(new List<Domain.Shipping.Warehouse> { new Domain.Shipping.Warehouse() }));
-
- _measureServiceMock.Setup(c => c.GetMeasureUnitById(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Directory.MeasureUnit()));
- _measureServiceMock.Setup(c => c.GetAllMeasureUnits()).Returns(Task.FromResult<IList<Domain.Directory.MeasureUnit>>(new List<Domain.Directory.MeasureUnit> { new Domain.Directory.MeasureUnit() }));
-
- _slugServiceMock.Setup(c => c.GetBySlug(It.IsAny<string>())).Returns(Task.FromResult(new Domain.Seo.EntityUrl { Slug = "slug" }));
- //Act
- await _productImportDataObject.Execute(products);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(3, _repository.Table.Count());
- Assert.AreEqual("update3", _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Name);
- Assert.AreEqual(3, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).DisplayOrder);
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == product3.Id).Published);
-
- }
-
- private void InitAutoMapper()
- {
- var typeSearcher = new TypeSearcher();
- //find mapper configurations provided by other assemblies
- var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();
-
- //create and sort instances of mapper configurations
- var instances = mapperConfigurations
- .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))
- .OrderBy(mapperConfiguration => mapperConfiguration.Order);
-
- //create AutoMapper configuration
- var config = new MapperConfiguration(cfg =>
- {
- foreach (var instance in instances)
- {
- cfg.AddProfile(instance.GetType());
- }
- });
-
- //register automapper
- AutoMapperConfig.Init(config);
- }
+ //register automapper
+ AutoMapperConfig.Init(config);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs
index 728cb8c6c..42d923150 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceFormatterTests.cs
@@ -15,175 +15,174 @@ using Grand.SharedKernel.Extensions;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
+using System.Globalization;
-namespace Grand.Business.Catalog.Tests.Services.Prices
+namespace Grand.Business.Catalog.Tests.Services.Prices;
+
+[TestClass]
+public class PriceFormatterTests
{
- [TestClass()]
- public class PriceFormatterTests
+ private IAclService _aclService;
+ private IRepository<Currency> _currencyRepo;
+ private ICurrencyService _currencyService;
+ private CurrencySettings _currencySettings;
+ private IMediator _eventPublisher;
+ private IPriceFormatter _priceFormatter;
+ private IServiceProvider _serviceProvider;
+
+ private TaxSettings _taxSettings;
+ private ITranslationService _translationService;
+ private IWorkContext _workContext;
+ private Mock<IWorkContext> tempWorkContext;
+
+ [TestInitialize]
+ public void TestInitialize()
{
- private IRepository<Currency> _currencyRepo;
- private ICurrencyService _currencyService;
- private CurrencySettings _currencySettings;
- private IWorkContext _workContext;
- private Mock<IWorkContext> tempWorkContext;
-
- private TaxSettings _taxSettings;
- private IPriceFormatter _priceFormatter;
- private IAclService _aclService;
- private IServiceProvider _serviceProvider;
- private IMediator _eventPublisher;
- private ITranslationService _translationService;
-
- [TestInitialize()]
- public void TestInitialize()
+ CommonPath.BaseDirectory = "";
+
+ var eventPublisher = new Mock<IMediator>();
+ _eventPublisher = eventPublisher.Object;
+
+ var cacheManager = new Mock<ICacheBase>();
+ tempWorkContext = new Mock<IWorkContext>();
{
- CommonPath.BaseDirectory = "";
-
- var eventPublisher = new Mock<IMediator>();
- _eventPublisher = eventPublisher.Object;
-
- var cacheManager = new Mock<ICacheBase>();
- tempWorkContext = new Mock<IWorkContext>();
- {
- _workContext = tempWorkContext.Object;
- }
- _currencySettings = new CurrencySettings();
- var currency01 = new Currency {
- Id = "1",
- Name = "Euro",
- CurrencyCode = "EUR",
- DisplayLocale = "",
- CustomFormatting = "€0.00",
- DisplayOrder = 1,
- Published = true
- };
-
- var currency02 = new Currency {
- Id = "1",
- Name = "US Dollar",
- CurrencyCode = "USD",
- DisplayLocale = "en-US",
- CustomFormatting = "",
- DisplayOrder = 2,
- Published = true
- };
-
- var tempCurrencyRepo = new Mock<IRepository<Currency>>();
- {
- var tempIMongoCollection = new Mock<MongoRepository<Currency>>(Mock.Of<IAuditInfoProvider>()).Object;
- tempIMongoCollection.Insert(currency01);
- tempIMongoCollection.Insert(currency02);
- tempCurrencyRepo.Setup(x => x.Table).Returns(tempIMongoCollection.Table);
- }
-
- _aclService = new Mock<IAclService>().Object;
- _serviceProvider = new Mock<IServiceProvider>().Object;
-
- _currencyRepo = new Mock<IRepository<Currency>>().Object;
-
-
- _currencyService = new CurrencyService(
- cacheManager.Object,
- _currencyRepo,
- _aclService,
- _currencySettings,
- null);
-
- _taxSettings = new TaxSettings();
-
- var tempLocalizationService = new Mock<ITranslationService>();
- {
- tempLocalizationService.Setup(x => x.GetResource("Products.InclTaxSuffix", "1", "", false)).Returns("{0} incl tax");
- tempLocalizationService.Setup(x => x.GetResource("Products.ExclTaxSuffix", "1", "", false)).Returns("{0} excl tax");
- _translationService = tempLocalizationService.Object;
- }
-
- _priceFormatter = new PriceFormatter(_workContext);
+ _workContext = tempWorkContext.Object;
}
-
- [TestMethod()]
- public void Can_formatPrice_with_custom_currencyFormatting()
+ _currencySettings = new CurrencySettings();
+ var currency01 = new Currency {
+ Id = "1",
+ Name = "Euro",
+ CurrencyCode = "EUR",
+ DisplayLocale = "",
+ CustomFormatting = "€0.00",
+ DisplayOrder = 1,
+ Published = true
+ };
+
+ var currency02 = new Currency {
+ Id = "1",
+ Name = "US Dollar",
+ CurrencyCode = "USD",
+ DisplayLocale = "en-US",
+ CustomFormatting = "",
+ DisplayOrder = 2,
+ Published = true
+ };
+
+ var tempCurrencyRepo = new Mock<IRepository<Currency>>();
{
- Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
-
- var currency0111 = new Currency {
- Id = "1",
- Name = "Euro",
- CurrencyCode = "EUR",
- DisplayLocale = "",
- CustomFormatting = "€0.00",
- DisplayOrder = 1,
- Published = true,
- CreatedOnUtc = DateTime.UtcNow,
- UpdatedOnUtc = DateTime.UtcNow,
- RoundingTypeId = RoundingType.Rounding001,
- MidpointRoundId = MidpointRounding.AwayFromZero
- };
-
- var language0111 = new Language {
- Id = "1",
- Name = "English",
- LanguageCulture = "en-US"
- };
-
- Assert.AreEqual("€412.20", _priceFormatter.FormatPrice(412.2, currency0111));
+ var tempIMongoCollection = new Mock<MongoRepository<Currency>>(Mock.Of<IAuditInfoProvider>()).Object;
+ tempIMongoCollection.Insert(currency01);
+ tempIMongoCollection.Insert(currency02);
+ tempCurrencyRepo.Setup(x => x.Table).Returns(tempIMongoCollection.Table);
}
- [TestMethod()]
- public void Can_formatPrice_with_distinct_currencyDisplayLocale()
- {
+ _aclService = new Mock<IAclService>().Object;
+ _serviceProvider = new Mock<IServiceProvider>().Object;
- var usd_currency = new Currency {
- Id = "1",
- Name = "US Dollar",
- CurrencyCode = "USD",
- DisplayLocale = "en-US",
- MidpointRoundId = MidpointRounding.AwayFromZero
-
- };
- var gbp_currency = new Currency {
- Id = "2",
- Name = "great british pound",
- CurrencyCode = "GBP",
- DisplayLocale = "en-GB",
- MidpointRoundId = MidpointRounding.AwayFromZero
- };
- var euro_currency = new Currency {
- Id = "3",
- Name = "Euro",
- CurrencyCode = "EUR",
- DisplayLocale = "en_150",
- MidpointRoundId = MidpointRounding.AwayFromZero
- };
- var language = new Language {
- Id = "1",
- Name = "English",
- LanguageCulture = "en-US"
- };
- Assert.AreEqual("$1,234.50", _priceFormatter.FormatPrice(1234.5, usd_currency));
- Assert.AreEqual("£1,234.50", _priceFormatter.FormatPrice(1234.5, gbp_currency));
- }
+ _currencyRepo = new Mock<IRepository<Currency>>().Object;
- [TestMethod()]
- public void Can_formatPrice_with_showCurrencyCode()
- {
- //DisplayCurrecyLabel = true $123.00 (USD)
- //DisplayCurrecyLabel = false $123.00
-
- var currency = new Currency {
- Id = "1",
- Name = "US Dollar",
- CurrencyCode = "USD",
- DisplayLocale = "en-US"
- };
- var language = new Language {
- Id = "1",
- Name = "English",
- LanguageCulture = "en-US"
- };
-
- Assert.AreEqual("$18,888.10", _priceFormatter.FormatPrice(18888.1, currency));
+ _currencyService = new CurrencyService(
+ cacheManager.Object,
+ _currencyRepo,
+ _aclService,
+ _currencySettings,
+ null);
+
+ _taxSettings = new TaxSettings();
+
+ var tempLocalizationService = new Mock<ITranslationService>();
+ {
+ tempLocalizationService.Setup(x => x.GetResource("Products.InclTaxSuffix", "1", "", false))
+ .Returns("{0} incl tax");
+ tempLocalizationService.Setup(x => x.GetResource("Products.ExclTaxSuffix", "1", "", false))
+ .Returns("{0} excl tax");
+ _translationService = tempLocalizationService.Object;
}
+
+ _priceFormatter = new PriceFormatter(_workContext);
+ }
+
+ [TestMethod]
+ public void Can_formatPrice_with_custom_currencyFormatting()
+ {
+ Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
+
+ var currency0111 = new Currency {
+ Id = "1",
+ Name = "Euro",
+ CurrencyCode = "EUR",
+ DisplayLocale = "",
+ CustomFormatting = "€0.00",
+ DisplayOrder = 1,
+ Published = true,
+ CreatedOnUtc = DateTime.UtcNow,
+ UpdatedOnUtc = DateTime.UtcNow,
+ RoundingTypeId = RoundingType.Rounding001,
+ MidpointRoundId = MidpointRounding.AwayFromZero
+ };
+
+ var language0111 = new Language {
+ Id = "1",
+ Name = "English",
+ LanguageCulture = "en-US"
+ };
+
+ Assert.AreEqual("€412.20", _priceFormatter.FormatPrice(412.2, currency0111));
+ }
+
+ [TestMethod]
+ public void Can_formatPrice_with_distinct_currencyDisplayLocale()
+ {
+ var usd_currency = new Currency {
+ Id = "1",
+ Name = "US Dollar",
+ CurrencyCode = "USD",
+ DisplayLocale = "en-US",
+ MidpointRoundId = MidpointRounding.AwayFromZero
+ };
+ var gbp_currency = new Currency {
+ Id = "2",
+ Name = "great british pound",
+ CurrencyCode = "GBP",
+ DisplayLocale = "en-GB",
+ MidpointRoundId = MidpointRounding.AwayFromZero
+ };
+ var euro_currency = new Currency {
+ Id = "3",
+ Name = "Euro",
+ CurrencyCode = "EUR",
+ DisplayLocale = "en_150",
+ MidpointRoundId = MidpointRounding.AwayFromZero
+ };
+ var language = new Language {
+ Id = "1",
+ Name = "English",
+ LanguageCulture = "en-US"
+ };
+ Assert.AreEqual("$1,234.50", _priceFormatter.FormatPrice(1234.5, usd_currency));
+ Assert.AreEqual("£1,234.50", _priceFormatter.FormatPrice(1234.5, gbp_currency));
+ }
+
+ [TestMethod]
+ public void Can_formatPrice_with_showCurrencyCode()
+ {
+ //DisplayCurrecyLabel = true $123.00 (USD)
+ //DisplayCurrecyLabel = false $123.00
+
+ var currency = new Currency {
+ Id = "1",
+ Name = "US Dollar",
+ CurrencyCode = "USD",
+ DisplayLocale = "en-US"
+ };
+ var language = new Language {
+ Id = "1",
+ Name = "English",
+ LanguageCulture = "en-US"
+ };
+
+ Assert.AreEqual("$18,888.10", _priceFormatter.FormatPrice(18888.1, currency));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs
index 50be4ffe4..9a985ab41 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Prices/PriceServiceTests.cs
@@ -9,11 +9,11 @@ using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Utilities.Catalog;
+using Grand.Data;
+using Grand.Data.Mongo;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
-using Grand.Data;
-using Grand.Data.Mongo;
using Grand.Domain.Directory;
using Grand.Domain.Discounts;
using Grand.Domain.Orders;
@@ -25,305 +25,345 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Prices
+namespace Grand.Business.Catalog.Tests.Services.Prices;
+
+[TestClass]
+public class PriceServiceTests
{
- [TestClass()]
- public class PriceServiceTests
+ private IBrandService _brandService;
+ private CatalogSettings _catalogSettings;
+ private ICategoryService _categoryService;
+ private ICollectionService _collectionService;
+ private Currency _currency;
+ private ICurrencyService _currencyService;
+ private CurrencySettings _currencySettings;
+ private IDiscountService _discountService;
+ private Mock<IDiscountValidationService> _discountValidationService;
+ private IMediator _eventPublisher;
+ private IPricingService _pricingService;
+ private IProductService _productService;
+ private ShoppingCartSettings _shoppingCartSettings;
+ private Store _store;
+ private IWorkContext _workContext;
+ private Mock<IDiscountService> tempDiscountServiceMock;
+ private Mock<IProductService> tempProductService;
+ private Mock<IWorkContext> tempWorkContext;
+
+ [TestInitialize]
+ public void TestInitialize()
{
- private Store _store;
- private Currency _currency;
- private CurrencySettings _currencySettings;
- private Mock<IWorkContext> tempWorkContext;
- private IWorkContext _workContext;
- private Mock<IDiscountService> tempDiscountServiceMock;
- private IDiscountService _discountService;
- private ICategoryService _categoryService;
- private IBrandService _brandService;
- private ICollectionService _collectionService;
- private Mock<IProductService> tempProductService;
- private IProductService _productService;
- private ShoppingCartSettings _shoppingCartSettings;
- private CatalogSettings _catalogSettings;
- private IPricingService _pricingService;
- private ICurrencyService _currencyService;
- private IMediator _eventPublisher;
- private Mock<IDiscountValidationService> _discountValidationService;
-
- [TestInitialize()]
- public void TestInitialize()
- {
- CommonPath.BaseDirectory = "";
-
- _store = new Store { Id = "1" };
- tempWorkContext = new Mock<IWorkContext>();
- {
- tempWorkContext.Setup(instance => instance.WorkingCurrency).Returns(_currency);
- tempWorkContext.Setup(c => c.CurrentStore).Returns(_store);
- _workContext = tempWorkContext.Object;
- }
-
- tempDiscountServiceMock = new Mock<IDiscountService>();
- {
- _discountService = tempDiscountServiceMock.Object;
- }
-
- _categoryService = new Mock<ICategoryService>().Object;
- _collectionService = new Mock<ICollectionService>().Object;
- _brandService = new Mock<IBrandService>().Object;
- _discountValidationService = new Mock<IDiscountValidationService>();
-
- tempProductService = new Mock<IProductService>();
- {
- _productService = tempProductService.Object;
- }
- _shoppingCartSettings = new ShoppingCartSettings();
- _catalogSettings = new CatalogSettings();
- var eventPublisher = new Mock<IMediator>();
- _eventPublisher = eventPublisher.Object;
-
- _currencySettings = new CurrencySettings {
- PrimaryExchangeRateCurrencyId = "1",
- PrimaryStoreCurrencyId = "1"
- };
- //_currencyService = new Mock<ICurrencyService>().Object;
- _currency = new Currency { Id = "1", CurrencyCode = "USD", Rate = 1, Published = true, MidpointRoundId = System.MidpointRounding.ToEven, RoundingTypeId = RoundingType.Rounding001 };
-
- var tempCurrency = new Mock<ICurrencyService>();
- {
- tempCurrency.Setup(instance => instance.GetPrimaryStoreCurrency()).Returns(Task.FromResult(_currency));
- //tempCurrency.Setup(instance => instance.ConvertToPrimaryStoreCurrency(It.IsAny<double>(), _currency)).ReturnsAsync(5);
- //_currencyService = tempCurrency.Object;
- }
- var cacheManager = new Mock<ICacheBase>().Object;
- IRepository<Currency> _currencyRepository;
- var tempCurrencyRepository = new Mock<IRepository<Currency>>();
- {
- var IMongoCollection = new Mock<MongoRepository<Currency>>(Mock.Of<IAuditInfoProvider>()).Object;
- IMongoCollection.Insert(_currency);
-
-
- tempCurrencyRepository.Setup(x => x.Table).Returns(IMongoCollection.Table);
- tempCurrencyRepository.Setup(x => x.GetByIdAsync(_currency.Id)).ReturnsAsync(_currency);
- _currencyRepository = tempCurrencyRepository.Object;
- }
-
- IAclService _aclService = new Mock<IAclService>().Object;
- var _serviceProvider = new Mock<IServiceProvider>().Object;
-
- _currencyService = new CurrencyService(
- cacheManager, _currencyRepository, _aclService,
- _currencySettings, _eventPublisher);
-
-
- _pricingService = new PricingService(
- _workContext,
- _discountService,
- _categoryService,
- _brandService,
- _collectionService,
- _productService,
- _eventPublisher,
- _currencyService,
- _discountValidationService.Object,
- _shoppingCartSettings,
- _catalogSettings);
- }
+ CommonPath.BaseDirectory = "";
- [TestMethod()]
- public async Task Can_get_final_product_price()
+ _store = new Store { Id = "1" };
+ tempWorkContext = new Mock<IWorkContext>();
{
- var product = new Product {
- Id = "1",
- Name = "product name 01",
- Price = 49.99,
- EnteredPrice = false,
- Published = true
- };
- product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
-
- var currency = new Currency { Id = "1", CurrencyCode = "USD", Rate = 1, Published = true, MidpointRoundId = System.MidpointRounding.ToEven, RoundingTypeId = RoundingType.Rounding001 };
- var customer = new Customer();
- var pr = await _pricingService.GetFinalPrice(product, customer, _store, currency, 0, false, 1);
- Assert.AreEqual(49.99, pr.finalPrice);
- //returned price FOR ONE UNIT should be the same, even if quantity is different than 1
- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 10)).finalPrice);
+ tempWorkContext.Setup(instance => instance.WorkingCurrency).Returns(_currency);
+ tempWorkContext.Setup(c => c.CurrentStore).Returns(_store);
+ _workContext = tempWorkContext.Object;
}
- [TestMethod()]
- public async Task Can_get_final_product_price_with_tier_prices()
+ tempDiscountServiceMock = new Mock<IDiscountService>();
{
- var product = new Product {
- Id = "1",
- Name = "product name 01",
- Price = 49.99,
- EnteredPrice = false,
- Published = true
- };
- product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
- //TierPrice is simply "the more you buy, the less you pay"
- product.TierPrices.Add(new TierPrice { Price = 10, Quantity = 10, CurrencyCode = "USD" });
- product.TierPrices.Add(new TierPrice { Price = 2, Quantity = 200, CurrencyCode = "USD" });
-
- Customer customer = new Customer();
-
- /*
- quantity: <=9 price: 49.99
- quantity: 10-199 price: 10
- quantity: >=200 price: 2
- */
-
- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 1)).finalPrice);
- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 5)).finalPrice);
- Assert.AreEqual(49.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 9)).finalPrice);
-
- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 10)).finalPrice);
- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 11)).finalPrice);
- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 151)).finalPrice);
- Assert.AreEqual(10, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 199)).finalPrice);
-
- var p1 = (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 200)).finalPrice;
- Assert.AreEqual(2, p1);
- Assert.AreEqual(2, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 201)).finalPrice);
- Assert.AreEqual(2, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 22201)).finalPrice);
+ _discountService = tempDiscountServiceMock.Object;
}
+ _categoryService = new Mock<ICategoryService>().Object;
+ _collectionService = new Mock<ICollectionService>().Object;
+ _brandService = new Mock<IBrandService>().Object;
+ _discountValidationService = new Mock<IDiscountValidationService>();
- [TestMethod()]
- public async Task Can_get_final_product_price_with_additionalFee()
+ tempProductService = new Mock<IProductService>();
{
- //tests if price is valid for additional charge (additional fee)
- var product = new Product {
- Id = "1",
- Name = "product name 01",
- Price = 49.99,
- EnteredPrice = false,
- Published = true
- };
- product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
- var customer = new Customer();
-
- //additional charge +1000
- //==1049.99
- Assert.AreEqual(1049.99, (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 1000, false, 1)).finalPrice);
+ _productService = tempProductService.Object;
}
-
- [TestMethod()]
- public async Task Can_get_final_product_price_with_discount()
+ _shoppingCartSettings = new ShoppingCartSettings();
+ _catalogSettings = new CatalogSettings();
+ var eventPublisher = new Mock<IMediator>();
+ _eventPublisher = eventPublisher.Object;
+
+ _currencySettings = new CurrencySettings {
+ PrimaryExchangeRateCurrencyId = "1",
+ PrimaryStoreCurrencyId = "1"
+ };
+ //_currencyService = new Mock<ICurrencyService>().Object;
+ _currency = new Currency {
+ Id = "1", CurrencyCode = "USD", Rate = 1, Published = true, MidpointRoundId = MidpointRounding.ToEven,
+ RoundingTypeId = RoundingType.Rounding001
+ };
+
+ var tempCurrency = new Mock<ICurrencyService>();
{
- var product = new Product {
- Id = "1",
- Name = "product name 01",
- Price = 49.99,
- EnteredPrice = false,
- Published = true
- };
- product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
- var customer = new Customer();
-
- var discount001 = new Discount {
- Id = "1",
- Name = "Discount 001",
- DiscountTypeId = DiscountType.AssignedToSkus,
- DiscountAmount = 10,
- DiscountLimitationId = DiscountLimitationType.Nolimits,
- CurrencyCode = _currency.CurrencyCode
- };
-
- tempDiscountServiceMock.Setup(x => x.GetDiscountById(discount001.Id)).ReturnsAsync(discount001);
-
- product.AppliedDiscounts.Add(discount001.Id);
-
- _discountValidationService.Setup(x => x.ValidateDiscount(discount001, customer, _store, _currency)).ReturnsAsync(new DiscountValidationResult { IsValid = true });
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToSkus, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount> { discount001 });
-
- var discountAmount = discount001.DiscountAmount;
- tempDiscountServiceMock.Setup(x => x.GetPreferredDiscount(It.IsAny<List<ApplyDiscount>>(), customer, _currency, product, 49.99)).ReturnsAsync((new List<ApplyDiscount>(), 10));
-
- //it should return 39.99 - price cheaper about 10
- var finalprice = await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, true, 1);
- var pp = finalprice.finalPrice;
-
- Assert.AreEqual(39.99, pp);
+ tempCurrency.Setup(instance => instance.GetPrimaryStoreCurrency()).Returns(Task.FromResult(_currency));
+ //tempCurrency.Setup(instance => instance.ConvertToPrimaryStoreCurrency(It.IsAny<double>(), _currency)).ReturnsAsync(5);
+ //_currencyService = tempCurrency.Object;
}
-
- [TestMethod()]
- public async Task Can_get_shopping_cart_item_unitPrice()
+ var cacheManager = new Mock<ICacheBase>().Object;
+ IRepository<Currency> _currencyRepository;
+ var tempCurrencyRepository = new Mock<IRepository<Currency>>();
{
- var customer001 = new Customer { Id = "98767" };
- tempWorkContext.Setup(x => x.CurrentCustomer).Returns(customer001);
- tempWorkContext.Setup(x => x.WorkingCurrency).Returns(_currency);
- var product001 = new Product {
- Id = "242422",
- Name = "product name 01",
- Price = 49.99,
- EnteredPrice = false,
- Published = true
- };
- product001.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
- tempProductService.Setup(x => x.GetProductById("242422", false)).ReturnsAsync(product001);
-
-
- var shoppingCartItem = new ShoppingCartItem {
- ProductId = product001.Id,
- Quantity = 2
- };
-
- customer001.ShoppingCartItems.Add(shoppingCartItem);
-
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- var pp = (await _pricingService.GetUnitPrice(shoppingCartItem, product001)).unitprice;
- Assert.AreEqual(49.99, pp);
- }
+ var IMongoCollection = new Mock<MongoRepository<Currency>>(Mock.Of<IAuditInfoProvider>()).Object;
+ IMongoCollection.Insert(_currency);
- [TestMethod()]
- public async Task Can_get_shopping_cart_item_subTotal()
- {
- var product001 = new Product {
- Id = "242422",
- Name = "product name 01",
- Price = 55.11,
- EnteredPrice = false,
- Published = true
- };
- product001.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 55.11 });
- tempProductService.Setup(x => x.GetProductById("242422", false)).ReturnsAsync(product001);
-
- var customer001 = new Customer { Id = "98767" };
- tempWorkContext.Setup(x => x.CurrentCustomer).Returns(customer001);
- tempWorkContext.Setup(x => x.WorkingCurrency).Returns(_currency);
- var shoppingCartItem = new ShoppingCartItem {
- ProductId = product001.Id, //222
- Quantity = 2
- };
-
- customer001.ShoppingCartItems.Add(shoppingCartItem);
-
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- tempDiscountServiceMock.Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode)).ReturnsAsync(new List<Discount>());
- var subtotal = (await _pricingService.GetSubTotal(shoppingCartItem, product001)).subTotal;
- Assert.AreEqual(110.22, subtotal);
- }
- [TestMethod()]
- public async Task Can_get_product_cost()
- {
- var product001 = new Product {
- Id = "242422",
- Name = "product name 01",
- Price = 55.11,
- EnteredPrice = false,
- Published = true,
- ProductCost = 20
- };
-
- var productCost = await _pricingService.GetProductCost(product001, new List<CustomAttribute>());
-
- Assert.AreEqual(20, productCost);
+
+ tempCurrencyRepository.Setup(x => x.Table).Returns(IMongoCollection.Table);
+ tempCurrencyRepository.Setup(x => x.GetByIdAsync(_currency.Id)).ReturnsAsync(_currency);
+ _currencyRepository = tempCurrencyRepository.Object;
}
+
+ var _aclService = new Mock<IAclService>().Object;
+ var _serviceProvider = new Mock<IServiceProvider>().Object;
+
+ _currencyService = new CurrencyService(
+ cacheManager, _currencyRepository, _aclService,
+ _currencySettings, _eventPublisher);
+
+
+ _pricingService = new PricingService(
+ _workContext,
+ _discountService,
+ _categoryService,
+ _brandService,
+ _collectionService,
+ _productService,
+ _eventPublisher,
+ _currencyService,
+ _discountValidationService.Object,
+ _shoppingCartSettings,
+ _catalogSettings);
+ }
+
+ [TestMethod]
+ public async Task Can_get_final_product_price()
+ {
+ var product = new Product {
+ Id = "1",
+ Name = "product name 01",
+ Price = 49.99,
+ EnteredPrice = false,
+ Published = true
+ };
+ product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
+
+ var currency = new Currency {
+ Id = "1", CurrencyCode = "USD", Rate = 1, Published = true, MidpointRoundId = MidpointRounding.ToEven,
+ RoundingTypeId = RoundingType.Rounding001
+ };
+ var customer = new Customer();
+ var pr = await _pricingService.GetFinalPrice(product, customer, _store, currency, 0, false);
+ Assert.AreEqual(49.99, pr.finalPrice);
+ //returned price FOR ONE UNIT should be the same, even if quantity is different than 1
+ Assert.AreEqual(49.99,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 10)).finalPrice);
+ }
+
+ [TestMethod]
+ public async Task Can_get_final_product_price_with_tier_prices()
+ {
+ var product = new Product {
+ Id = "1",
+ Name = "product name 01",
+ Price = 49.99,
+ EnteredPrice = false,
+ Published = true
+ };
+ product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
+ //TierPrice is simply "the more you buy, the less you pay"
+ product.TierPrices.Add(new TierPrice { Price = 10, Quantity = 10, CurrencyCode = "USD" });
+ product.TierPrices.Add(new TierPrice { Price = 2, Quantity = 200, CurrencyCode = "USD" });
+
+ var customer = new Customer();
+
+ /*
+ quantity: <=9 price: 49.99
+ quantity: 10-199 price: 10
+ quantity: >=200 price: 2
+ */
+
+ Assert.AreEqual(49.99,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false)).finalPrice);
+ Assert.AreEqual(49.99,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 5)).finalPrice);
+ Assert.AreEqual(49.99,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 9)).finalPrice);
+
+ Assert.AreEqual(10,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 10)).finalPrice);
+ Assert.AreEqual(10,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 11)).finalPrice);
+ Assert.AreEqual(10,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 151)).finalPrice);
+ Assert.AreEqual(10,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 199)).finalPrice);
+
+ var p1 = (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 200)).finalPrice;
+ Assert.AreEqual(2, p1);
+ Assert.AreEqual(2,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 201)).finalPrice);
+ Assert.AreEqual(2,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 0, false, 22201)).finalPrice);
+ }
+
+
+ [TestMethod]
+ public async Task Can_get_final_product_price_with_additionalFee()
+ {
+ //tests if price is valid for additional charge (additional fee)
+ var product = new Product {
+ Id = "1",
+ Name = "product name 01",
+ Price = 49.99,
+ EnteredPrice = false,
+ Published = true
+ };
+ product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
+ var customer = new Customer();
+
+ //additional charge +1000
+ //==1049.99
+ Assert.AreEqual(1049.99,
+ (await _pricingService.GetFinalPrice(product, customer, _store, _currency, 1000, false)).finalPrice);
+ }
+
+ [TestMethod]
+ public async Task Can_get_final_product_price_with_discount()
+ {
+ var product = new Product {
+ Id = "1",
+ Name = "product name 01",
+ Price = 49.99,
+ EnteredPrice = false,
+ Published = true
+ };
+ product.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
+ var customer = new Customer();
+
+ var discount001 = new Discount {
+ Id = "1",
+ Name = "Discount 001",
+ DiscountTypeId = DiscountType.AssignedToSkus,
+ DiscountAmount = 10,
+ DiscountLimitationId = DiscountLimitationType.Nolimits,
+ CurrencyCode = _currency.CurrencyCode
+ };
+
+ tempDiscountServiceMock.Setup(x => x.GetDiscountById(discount001.Id)).ReturnsAsync(discount001);
+
+ product.AppliedDiscounts.Add(discount001.Id);
+
+ _discountValidationService.Setup(x => x.ValidateDiscount(discount001, customer, _store, _currency))
+ .ReturnsAsync(new DiscountValidationResult { IsValid = true });
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToSkus, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount> { discount001 });
+
+ var discountAmount = discount001.DiscountAmount;
+ tempDiscountServiceMock
+ .Setup(x => x.GetPreferredDiscount(It.IsAny<List<ApplyDiscount>>(), customer, _currency, product, 49.99))
+ .ReturnsAsync((new List<ApplyDiscount>(), 10));
+
+ //it should return 39.99 - price cheaper about 10
+ var finalprice = await _pricingService.GetFinalPrice(product, customer, _store, _currency);
+ var pp = finalprice.finalPrice;
+
+ Assert.AreEqual(39.99, pp);
+ }
+
+ [TestMethod]
+ public async Task Can_get_shopping_cart_item_unitPrice()
+ {
+ var customer001 = new Customer { Id = "98767" };
+ tempWorkContext.Setup(x => x.CurrentCustomer).Returns(customer001);
+ tempWorkContext.Setup(x => x.WorkingCurrency).Returns(_currency);
+ var product001 = new Product {
+ Id = "242422",
+ Name = "product name 01",
+ Price = 49.99,
+ EnteredPrice = false,
+ Published = true
+ };
+ product001.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 49.99 });
+ tempProductService.Setup(x => x.GetProductById("242422", false)).ReturnsAsync(product001);
+
+
+ var shoppingCartItem = new ShoppingCartItem {
+ ProductId = product001.Id,
+ Quantity = 2
+ };
+
+ customer001.ShoppingCartItems.Add(shoppingCartItem);
+
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ var pp = (await _pricingService.GetUnitPrice(shoppingCartItem, product001)).unitprice;
+ Assert.AreEqual(49.99, pp);
+ }
+
+ [TestMethod]
+ public async Task Can_get_shopping_cart_item_subTotal()
+ {
+ var product001 = new Product {
+ Id = "242422",
+ Name = "product name 01",
+ Price = 55.11,
+ EnteredPrice = false,
+ Published = true
+ };
+ product001.ProductPrices.Add(new ProductPrice { CurrencyCode = "USD", Price = 55.11 });
+ tempProductService.Setup(x => x.GetProductById("242422", false)).ReturnsAsync(product001);
+
+ var customer001 = new Customer { Id = "98767" };
+ tempWorkContext.Setup(x => x.CurrentCustomer).Returns(customer001);
+ tempWorkContext.Setup(x => x.WorkingCurrency).Returns(_currency);
+ var shoppingCartItem = new ShoppingCartItem {
+ ProductId = product001.Id, //222
+ Quantity = 2
+ };
+
+ customer001.ShoppingCartItems.Add(shoppingCartItem);
+
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCategories, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToCollections, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ tempDiscountServiceMock
+ .Setup(x => x.GetActiveDiscountsByContext(DiscountType.AssignedToAllProducts, "1", _currency.CurrencyCode))
+ .ReturnsAsync(new List<Discount>());
+ var subtotal = (await _pricingService.GetSubTotal(shoppingCartItem, product001)).subTotal;
+ Assert.AreEqual(110.22, subtotal);
+ }
+
+ [TestMethod]
+ public async Task Can_get_product_cost()
+ {
+ var product001 = new Product {
+ Id = "242422",
+ Name = "product name 01",
+ Price = 55.11,
+ EnteredPrice = false,
+ Published = true,
+ ProductCost = 20
+ };
+
+ var productCost = await _pricingService.GetProductCost(product001, new List<CustomAttribute>());
+
+ Assert.AreEqual(20, productCost);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/AuctionServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/AuctionServiceTests.cs
index d227aa8e3..cfe78acad 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/AuctionServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/AuctionServiceTests.cs
@@ -1,8 +1,10 @@
using Grand.Business.Catalog.Services.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Localization;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -12,265 +14,266 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class AuctionServiceTests
{
- [TestClass()]
- public class AuctionServiceTests
- {
- private IRepository<Bid> _repository;
- private IRepository<Product> _productrepository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private AuctionService _auctionService;
- private MemoryCacheBase _cacheBase;
+ private AuctionService _auctionService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Product> _productrepository;
+ private IRepository<Bid> _repository;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
- _repository = new MongoDBRepositoryTest<Bid>();
- _productrepository = new MongoDBRepositoryTest<Product>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _auctionService = new AuctionService(_repository, _productrepository, _cacheBase, _mediatorMock.Object);
- }
+ _repository = new MongoDBRepositoryTest<Bid>();
+ _productrepository = new MongoDBRepositoryTest<Product>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _auctionService = new AuctionService(_repository, _productrepository, _cacheBase, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task GetBidTest()
- {
- //Arrange
- var bid = new Bid {
- Amount = 10
- };
- await _auctionService.InsertBid(bid);
+ [TestMethod]
+ public async Task GetBidTest()
+ {
+ //Arrange
+ var bid = new Bid {
+ Amount = 10
+ };
+ await _auctionService.InsertBid(bid);
- //Act
- var result = await _auctionService.GetBid(bid.Id);
+ //Act
+ var result = await _auctionService.GetBid(bid.Id);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(10, result.Amount);
- }
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(10, result.Amount);
+ }
- [TestMethod()]
- public async Task GetLatestBidTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
- var bid2 = new Bid {
- Amount = 12,
- ProductId = "1",
- Date = DateTime.UtcNow
- };
- await _auctionService.InsertBid(bid2);
+ [TestMethod]
+ public async Task GetLatestBidTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
+ var bid2 = new Bid {
+ Amount = 12,
+ ProductId = "1",
+ Date = DateTime.UtcNow
+ };
+ await _auctionService.InsertBid(bid2);
- //Act
- var result = await _auctionService.GetLatestBid("1");
+ //Act
+ var result = await _auctionService.GetLatestBid("1");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(12, result.Amount);
- }
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(12, result.Amount);
+ }
- [TestMethod()]
- public async Task GetBidsByProductIdTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
- var bid2 = new Bid {
- Amount = 12,
- ProductId = "1",
- Date = DateTime.UtcNow
- };
- await _auctionService.InsertBid(bid2);
+ [TestMethod]
+ public async Task GetBidsByProductIdTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
+ var bid2 = new Bid {
+ Amount = 12,
+ ProductId = "1",
+ Date = DateTime.UtcNow
+ };
+ await _auctionService.InsertBid(bid2);
- //Act
- var result = await _auctionService.GetBidsByProductId("1");
+ //Act
+ var result = await _auctionService.GetBidsByProductId("1");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(2, result.Count);
- }
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2, result.Count);
+ }
- [TestMethod()]
- public async Task GetBidsByCustomerIdTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- CustomerId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
- var bid2 = new Bid {
- Amount = 12,
- ProductId = "1",
- CustomerId = "2",
- Date = DateTime.UtcNow
- };
- await _auctionService.InsertBid(bid2);
+ [TestMethod]
+ public async Task GetBidsByCustomerIdTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ CustomerId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
+ var bid2 = new Bid {
+ Amount = 12,
+ ProductId = "1",
+ CustomerId = "2",
+ Date = DateTime.UtcNow
+ };
+ await _auctionService.InsertBid(bid2);
- //Act
- var result = await _auctionService.GetBidsByCustomerId("1");
+ //Act
+ var result = await _auctionService.GetBidsByCustomerId("1");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.Count);
- }
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.Count);
+ }
- [TestMethod()]
- public async Task InsertBidTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- CustomerId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
+ [TestMethod]
+ public async Task InsertBidTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ CustomerId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.AreEqual(1, _repository.Table.Count());
- }
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.AreEqual(1, _repository.Table.Count());
+ }
- [TestMethod()]
- public async Task UpdateBidTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- CustomerId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
- bid1.Amount = 12;
- //Act
- await _auctionService.UpdateBid(bid1);
- //Assert
- Assert.AreEqual(12, _repository.Table.FirstOrDefault().Amount);
- }
+ [TestMethod]
+ public async Task UpdateBidTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ CustomerId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
+ bid1.Amount = 12;
+ //Act
+ await _auctionService.UpdateBid(bid1);
+ //Assert
+ Assert.AreEqual(12, _repository.Table.FirstOrDefault().Amount);
+ }
- [TestMethod()]
- public async Task DeleteBidTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- CustomerId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
- //Act
- await _auctionService.DeleteBid(bid1);
- //Assert
- Assert.AreEqual(0, _repository.Table.Count());
- }
+ [TestMethod]
+ public async Task DeleteBidTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ CustomerId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
+ //Act
+ await _auctionService.DeleteBid(bid1);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
- [TestMethod()]
- public async Task UpdateHighestBidTest()
- {
- //Arrange
- var product = new Product();
- _productrepository.Insert(product);
+ [TestMethod]
+ public async Task UpdateHighestBidTest()
+ {
+ //Arrange
+ var product = new Product();
+ _productrepository.Insert(product);
- //Act
- await _auctionService.UpdateHighestBid(product, 15, "sample");
+ //Act
+ await _auctionService.UpdateHighestBid(product, 15, "sample");
- //Assert
- Assert.AreEqual(15, _productrepository.Table.FirstOrDefault(x => x.Id == product.Id).HighestBid);
- }
+ //Assert
+ Assert.AreEqual(15, _productrepository.Table.FirstOrDefault(x => x.Id == product.Id).HighestBid);
+ }
- [TestMethod()]
- public async Task GetAuctionsToEndTest()
- {
- //Arrange
- var product1 = new Product {
- ProductTypeId = ProductType.Auction,
- AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1)
- };
- _productrepository.Insert(product1);
- var product2 = new Product {
- ProductTypeId = ProductType.Auction,
- AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(-1)
- };
- _productrepository.Insert(product2);
+ [TestMethod]
+ public async Task GetAuctionsToEndTest()
+ {
+ //Arrange
+ var product1 = new Product {
+ ProductTypeId = ProductType.Auction,
+ AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1)
+ };
+ _productrepository.Insert(product1);
+ var product2 = new Product {
+ ProductTypeId = ProductType.Auction,
+ AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(-1)
+ };
+ _productrepository.Insert(product2);
- //Act
- var result = await _auctionService.GetAuctionsToEnd();
+ //Act
+ var result = await _auctionService.GetAuctionsToEnd();
- //Assert
- Assert.AreEqual(1, result.Count);
- }
+ //Assert
+ Assert.AreEqual(1, result.Count);
+ }
- [TestMethod()]
- public async Task UpdateAuctionEndedTest()
- {
- //Arrange
- var product1 = new Product {
- ProductTypeId = ProductType.Auction,
- AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1)
- };
- _productrepository.Insert(product1);
+ [TestMethod]
+ public async Task UpdateAuctionEndedTest()
+ {
+ //Arrange
+ var product1 = new Product {
+ ProductTypeId = ProductType.Auction,
+ AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1)
+ };
+ _productrepository.Insert(product1);
- //Act
- await _auctionService.UpdateAuctionEnded(product1, true, true);
+ //Act
+ await _auctionService.UpdateAuctionEnded(product1, true, true);
- //Assert
- Assert.AreEqual(true, _productrepository.Table.FirstOrDefault(x => x.Id == product1.Id).AuctionEnded);
- }
+ //Assert
+ Assert.AreEqual(true, _productrepository.Table.FirstOrDefault(x => x.Id == product1.Id).AuctionEnded);
+ }
- [TestMethod()]
- public async Task NewBidTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- CustomerId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
- //Act
- await _auctionService.NewBid(new Customer { Id = "1" }, new Product { Id = "1" }, new Domain.Stores.Store(), new Domain.Localization.Language(), "", 12);
- //Assert
- Assert.AreEqual(12, _repository.Table.Where(x => x.ProductId == "1").Max(x => x.Amount));
- }
+ [TestMethod]
+ public async Task NewBidTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ CustomerId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
+ //Act
+ await _auctionService.NewBid(new Customer { Id = "1" }, new Product { Id = "1" }, new Store(), new Language(),
+ "", 12);
+ //Assert
+ Assert.AreEqual(12, _repository.Table.Where(x => x.ProductId == "1").Max(x => x.Amount));
+ }
- [TestMethod()]
- public async Task CancelBidByOrderTest()
- {
- //Arrange
- var bid1 = new Bid {
- Amount = 10,
- ProductId = "1",
- CustomerId = "1",
- OrderId = "1",
- Date = DateTime.UtcNow.AddDays(-1)
- };
- await _auctionService.InsertBid(bid1);
- //Act
- await _auctionService.CancelBidByOrder("1");
- //Assert
- Assert.AreEqual(0, _repository.Table.Count());
- }
+ [TestMethod]
+ public async Task CancelBidByOrderTest()
+ {
+ //Arrange
+ var bid1 = new Bid {
+ Amount = 10,
+ ProductId = "1",
+ CustomerId = "1",
+ OrderId = "1",
+ Date = DateTime.UtcNow.AddDays(-1)
+ };
+ await _auctionService.InsertBid(bid1);
+ //Act
+ await _auctionService.CancelBidByOrder("1");
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CopyProductServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CopyProductServiceTests.cs
index e40b2f815..c4e37e1dc 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CopyProductServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CopyProductServiceTests.cs
@@ -8,46 +8,47 @@ using Grand.Domain.Seo;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class CopyProductServiceTests
{
- [TestClass()]
- public class CopyProductServiceTests
- {
- private Mock<IProductService> _productServiceMock;
- private Mock<ILanguageService> _langServiceMock;
- private Mock<ISlugService> _slugServiceMock;
- private SeoSettings _settings;
- private CopyProductService _copyProductService;
+ private CopyProductService _copyProductService;
+ private Mock<ILanguageService> _langServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private SeoSettings _settings;
+ private Mock<ISlugService> _slugServiceMock;
- [TestInitialize()]
- public void Init()
- {
- _productServiceMock = new Mock<IProductService>();
- _langServiceMock = new Mock<ILanguageService>();
- _slugServiceMock = new Mock<ISlugService>();
- _settings = new SeoSettings();
- _copyProductService = new CopyProductService(_productServiceMock.Object, _langServiceMock.Object, _slugServiceMock.Object, _settings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _productServiceMock = new Mock<IProductService>();
+ _langServiceMock = new Mock<ILanguageService>();
+ _slugServiceMock = new Mock<ISlugService>();
+ _settings = new SeoSettings();
+ _copyProductService = new CopyProductService(_productServiceMock.Object, _langServiceMock.Object,
+ _slugServiceMock.Object, _settings);
+ }
- [TestMethod()]
- public async Task CopyProduct_InserAndReturnNewProduct()
- {
- _langServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult<IList<Language>>(new List<Language>()));
- var product = new Product {
- Name = "name",
- Price = 49,
- ShortDescription = "Desc"
- };
- var copy = await _copyProductService.CopyProduct(product, "copy-product");
- Assert.AreEqual(copy.Price, product.Price);
- Assert.AreEqual(copy.ShortDescription, product.ShortDescription);
+ [TestMethod]
+ public async Task CopyProduct_InserAndReturnNewProduct()
+ {
+ _langServiceMock.Setup(c => c.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>()))
+ .Returns(Task.FromResult<IList<Language>>(new List<Language>()));
+ var product = new Product {
+ Name = "name",
+ Price = 49,
+ ShortDescription = "Desc"
+ };
+ var copy = await _copyProductService.CopyProduct(product, "copy-product");
+ Assert.AreEqual(copy.Price, product.Price);
+ Assert.AreEqual(copy.ShortDescription, product.ShortDescription);
- Assert.AreNotEqual(copy.SeName, product.SeName);
- Assert.AreNotEqual(copy.Id, product.Id);
- Assert.AreNotEqual(copy.Name, product.Name);
- _productServiceMock.Verify(c => c.InsertProduct(It.IsAny<Product>()), Times.Once);
- }
+ Assert.AreNotEqual(copy.SeName, product.SeName);
+ Assert.AreNotEqual(copy.Id, product.Id);
+ Assert.AreNotEqual(copy.Name, product.Name);
+ _productServiceMock.Verify(c => c.InsertProduct(It.IsAny<Product>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CustomerGroupProductServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CustomerGroupProductServiceTests.cs
index 5401b415f..cf0503e9e 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CustomerGroupProductServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/CustomerGroupProductServiceTests.cs
@@ -1,56 +1,57 @@
using Grand.Business.Catalog.Services.Products;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class CustomerGroupProductServiceTests
{
- [TestClass()]
- public class CustomerGroupProductServiceTests
- {
- private Mock<IRepository<CustomerGroupProduct>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<ICacheBase> _cacheMock;
- private CustomerGroupProductService _custometGroupService;
+ private Mock<ICacheBase> _cacheMock;
+ private CustomerGroupProductService _custometGroupService;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<CustomerGroupProduct>> _repositoryMock;
- [TestInitialize()]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<CustomerGroupProduct>>();
- _mediatorMock = new Mock<IMediator>();
- _cacheMock = new Mock<ICacheBase>();
- _custometGroupService = new CustomerGroupProductService(_repositoryMock.Object, _cacheMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<CustomerGroupProduct>>();
+ _mediatorMock = new Mock<IMediator>();
+ _cacheMock = new Mock<ICacheBase>();
+ _custometGroupService =
+ new CustomerGroupProductService(_repositoryMock.Object, _cacheMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task DeleteCustomerGroupProduct_ValidArguments_InvokeMethods()
- {
- await _custometGroupService.DeleteCustomerGroupProduct(new CustomerGroupProduct());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CustomerGroupProduct>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerGroupProduct>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteCustomerGroupProduct_ValidArguments_InvokeMethods()
+ {
+ await _custometGroupService.DeleteCustomerGroupProduct(new CustomerGroupProduct());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CustomerGroupProduct>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerGroupProduct>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertCustomerGroupProduct_ValidArguments_InvokeMethods()
- {
- await _custometGroupService.InsertCustomerGroupProduct(new CustomerGroupProduct());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CustomerGroupProduct>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerGroupProduct>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertCustomerGroupProduct_ValidArguments_InvokeMethods()
+ {
+ await _custometGroupService.InsertCustomerGroupProduct(new CustomerGroupProduct());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CustomerGroupProduct>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true), Times.Exactly(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerGroupProduct>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task GetCustomerGroupProducts_ValidArguments_InvokeMethods()
- {
- await _custometGroupService.GetCustomerGroupProducts("id");
- //get by cache
- _cacheMock.Verify(c => c.GetAsync<List<CustomerGroupProduct>>(It.IsAny<string>(), It.IsAny<Func<Task<List<CustomerGroupProduct>>>>()), Times.Exactly(1));
- }
+ [TestMethod]
+ public async Task GetCustomerGroupProducts_ValidArguments_InvokeMethods()
+ {
+ await _custometGroupService.GetCustomerGroupProducts("id");
+ //get by cache
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<CustomerGroupProduct>>>>()),
+ Times.Exactly(1));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/InventoryManageServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/InventoryManageServiceTests.cs
index 12e42ec4d..204f05c34 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/InventoryManageServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/InventoryManageServiceTests.cs
@@ -1,10 +1,11 @@
using Grand.Business.Catalog.Services.Products;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Shipping;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -14,144 +15,143 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class InventoryManageServiceTests
{
+ private MemoryCacheBase _cacheBase;
+ private InventoryManageService _inventoryManageService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Product> _repository;
+ private IRepository<InventoryJournal> _repositoryInventoryJournal;
+ private CatalogSettings _settings;
+ private StockQuantityService _stockQuantityService;
+ private Mock<ITranslationService> _translationService;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = "";
+
+ CommonPath.BaseDirectory = "";
+
+ _repository = new MongoDBRepositoryTest<Product>();
+ _repositoryInventoryJournal = new MongoDBRepositoryTest<InventoryJournal>();
+ _workContextMock = new Mock<IWorkContext>();
+ _translationService = new Mock<ITranslationService>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+ _settings = new CatalogSettings();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _stockQuantityService = new StockQuantityService();
+ _inventoryManageService = new InventoryManageService(_repository, _repositoryInventoryJournal,
+ _stockQuantityService, _cacheBase, _mediatorMock.Object, _settings);
+ }
+
+
+ [TestMethod]
+ public async Task AdjustReservedTest_ManageStock_Reserve()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ ReservedQuantity = 5
+ };
+ await _repository.InsertAsync(product);
+ //Act
+ await _inventoryManageService.AdjustReserved(product, -10);
+ product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
+ //Assert
+ Assert.AreEqual(15, product.ReservedQuantity);
+ }
+
+ [TestMethod]
+ public async Task AdjustReservedTest_ManageStock_UnblockReserved()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ ReservedQuantity = 10
+ };
+ await _repository.InsertAsync(product);
+ //Act
+ await _inventoryManageService.AdjustReserved(product, 8);
+ product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
+ //Assert
+ Assert.AreEqual(2, product.ReservedQuantity);
+ }
+
+ [TestMethod]
+ public async Task BookReservedInventoryTest_ManageStock()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ StockQuantity = 10,
+ ReservedQuantity = 10
+ };
+ await _repository.InsertAsync(product);
+
+ var shipment = new Shipment();
+ var shipmentItem = new ShipmentItem { Quantity = 10 };
+
+ //Act
+ await _inventoryManageService.BookReservedInventory(product, shipment, shipmentItem);
+ product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
+ //Assert
+ Assert.AreEqual(0, product.ReservedQuantity);
+ Assert.AreEqual(0, product.StockQuantity);
+ }
+
+ [TestMethod]
+ public async Task ReverseBookedInventoryTest()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ StockQuantity = 10,
+ ReservedQuantity = 10
+ };
+ await _repository.InsertAsync(product);
+
+ var shipment = new Shipment();
+ var shipmentItem = new ShipmentItem { Quantity = 10 };
+ await _inventoryManageService.BookReservedInventory(product, shipment, shipmentItem);
+
+ //Act
+ await _inventoryManageService.ReverseBookedInventory(shipment, shipmentItem);
+
+ product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
+
+ //Assert
+ Assert.AreEqual(10, product.ReservedQuantity);
+ Assert.AreEqual(10, product.StockQuantity);
+ }
- [TestClass()]
- public class InventoryManageServiceTests
+ [TestMethod]
+ public async Task UpdateStockProductTest()
{
- private IRepository<Product> _repository;
- private IRepository<InventoryJournal> _repositoryInventoryJournal;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private CatalogSettings _settings;
- private InventoryManageService _inventoryManageService;
- private MemoryCacheBase _cacheBase;
- private StockQuantityService _stockQuantityService;
- private Mock<ITranslationService> _translationService;
-
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "";
-
- CommonPath.BaseDirectory = "";
-
- _repository = new MongoDBRepositoryTest<Product>();
- _repositoryInventoryJournal = new MongoDBRepositoryTest<InventoryJournal>();
- _workContextMock = new Mock<IWorkContext>();
- _translationService = new Mock<ITranslationService>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
- _settings = new CatalogSettings();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _stockQuantityService = new StockQuantityService();
- _inventoryManageService = new InventoryManageService(_repository, _repositoryInventoryJournal, _stockQuantityService, _cacheBase, _mediatorMock.Object, _settings);
- }
-
-
-
- [TestMethod()]
- public async Task AdjustReservedTest_ManageStock_Reserve()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- ReservedQuantity = 5
- };
- await _repository.InsertAsync(product);
- //Act
- await _inventoryManageService.AdjustReserved(product, -10);
- product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
- //Assert
- Assert.AreEqual(15, product.ReservedQuantity);
- }
-
- [TestMethod()]
- public async Task AdjustReservedTest_ManageStock_UnblockReserved()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- ReservedQuantity = 10
- };
- await _repository.InsertAsync(product);
- //Act
- await _inventoryManageService.AdjustReserved(product, 8);
- product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
- //Assert
- Assert.AreEqual(2, product.ReservedQuantity);
- }
-
- [TestMethod()]
- public async Task BookReservedInventoryTest_ManageStock()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- StockQuantity = 10,
- ReservedQuantity = 10
- };
- await _repository.InsertAsync(product);
-
- var shipment = new Shipment();
- var shipmentItem = new Domain.Shipping.ShipmentItem { Quantity = 10 };
-
- //Act
- await _inventoryManageService.BookReservedInventory(product, shipment, shipmentItem);
- product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
- //Assert
- Assert.AreEqual(0, product.ReservedQuantity);
- Assert.AreEqual(0, product.StockQuantity);
- }
-
- [TestMethod()]
- public async Task ReverseBookedInventoryTest()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- StockQuantity = 10,
- ReservedQuantity = 10
- };
- await _repository.InsertAsync(product);
-
- var shipment = new Shipment();
- var shipmentItem = new Domain.Shipping.ShipmentItem { Quantity = 10 };
- await _inventoryManageService.BookReservedInventory(product, shipment, shipmentItem);
-
- //Act
- await _inventoryManageService.ReverseBookedInventory(shipment, shipmentItem);
-
- product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
-
- //Assert
- Assert.AreEqual(10, product.ReservedQuantity);
- Assert.AreEqual(10, product.StockQuantity);
- }
-
- [TestMethod()]
- public async Task UpdateStockProductTest()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- StockQuantity = 0,
- ReservedQuantity = 0
- };
- await _repository.InsertAsync(product);
-
- //Act
- product.StockQuantity = 10;
- product.ReservedQuantity = 10;
- await _inventoryManageService.UpdateStockProduct(product);
-
- product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
-
- //Assert
- Assert.AreEqual(10, product.ReservedQuantity);
- Assert.AreEqual(10, product.StockQuantity);
- }
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ StockQuantity = 0,
+ ReservedQuantity = 0
+ };
+ await _repository.InsertAsync(product);
+
+ //Act
+ product.StockQuantity = 10;
+ product.ReservedQuantity = 10;
+ await _inventoryManageService.UpdateStockProduct(product);
+
+ product = _repository.Table.FirstOrDefault(x => x.Id == product.Id);
+
+ //Assert
+ Assert.AreEqual(10, product.ReservedQuantity);
+ Assert.AreEqual(10, product.StockQuantity);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/OutOfStockSubscriptionServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/OutOfStockSubscriptionServiceTests.cs
index 9c91202c9..733d6d2b3 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/OutOfStockSubscriptionServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/OutOfStockSubscriptionServiceTests.cs
@@ -1,279 +1,284 @@
using Grand.Business.Catalog.Services.Products;
using Grand.Business.Core.Commands.Catalog;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
-using Grand.Data;
using Grand.SharedKernel.Extensions;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class OutOfStockSubscriptionServiceTests
{
- [TestClass()]
- public class OutOfStockSubscriptionServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private OutOfStockSubscriptionService _outOfStockSubscriptionService;
+ private IRepository<OutOfStockSubscription> _repository;
+
+ [TestInitialize]
+ public void InitializeTests()
{
- private IRepository<OutOfStockSubscription> _repository;
- private Mock<IMediator> _mediatorMock;
- private OutOfStockSubscriptionService _outOfStockSubscriptionService;
+ CommonPath.BaseDirectory = "";
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
+ _repository = new MongoDBRepositoryTest<OutOfStockSubscription>();
+ _mediatorMock = new Mock<IMediator>();
+ _mediatorMock.Setup(x => x.Send(It.IsAny<SendNotificationsToSubscribersCommand>(), default))
+ .Returns(Task.FromResult((IList<OutOfStockSubscription>)new List<OutOfStockSubscription>()));
- _repository = new MongoDBRepositoryTest<OutOfStockSubscription>();
- _mediatorMock = new Mock<IMediator>();
- _mediatorMock.Setup(x => x.Send(It.IsAny<SendNotificationsToSubscribersCommand>(), default))
- .Returns(Task.FromResult((IList<OutOfStockSubscription>)new List<OutOfStockSubscription>()));
+ _outOfStockSubscriptionService = new OutOfStockSubscriptionService(_repository, _mediatorMock.Object);
+ }
- _outOfStockSubscriptionService = new OutOfStockSubscriptionService(_repository, _mediatorMock.Object);
- }
+ [TestMethod]
+ public async Task GetAllSubscriptionsByCustomerIdTest()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1"
+ };
+ var outOfStockSubscription2 = new OutOfStockSubscription {
+ CustomerId = "1"
+ };
+ var outOfStockSubscription3 = new OutOfStockSubscription {
+ CustomerId = "2"
+ };
+ await _repository.InsertAsync(outOfStockSubscription1);
+ await _repository.InsertAsync(outOfStockSubscription2);
+ await _repository.InsertAsync(outOfStockSubscription3);
+ //Act
+ var result = await _outOfStockSubscriptionService.GetAllSubscriptionsByCustomerId("1");
- [TestMethod()]
- public async Task GetAllSubscriptionsByCustomerIdTest()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1"
- };
- var outOfStockSubscription2 = new OutOfStockSubscription {
- CustomerId = "1"
- };
- var outOfStockSubscription3 = new OutOfStockSubscription {
- CustomerId = "2"
- };
- await _repository.InsertAsync(outOfStockSubscription1);
- await _repository.InsertAsync(outOfStockSubscription2);
- await _repository.InsertAsync(outOfStockSubscription3);
- //Act
- var result = await _outOfStockSubscriptionService.GetAllSubscriptionsByCustomerId("1");
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
- //Assert
- Assert.AreEqual(2, result.Count);
- }
+ [TestMethod]
+ public async Task FindSubscriptionTest_IsNotNull()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription2 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "2",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription3 = new OutOfStockSubscription {
+ CustomerId = "2",
+ ProductId = "3",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ await _repository.InsertAsync(outOfStockSubscription1);
+ await _repository.InsertAsync(outOfStockSubscription2);
+ await _repository.InsertAsync(outOfStockSubscription3);
- [TestMethod()]
- public async Task FindSubscriptionTest_IsNotNull()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription2 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "2",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription3 = new OutOfStockSubscription {
- CustomerId = "2",
- ProductId = "3",
- StoreId = "",
- WarehouseId = ""
- };
- await _repository.InsertAsync(outOfStockSubscription1);
- await _repository.InsertAsync(outOfStockSubscription2);
- await _repository.InsertAsync(outOfStockSubscription3);
+ //Act
+ var result =
+ await _outOfStockSubscriptionService.FindSubscription("1", "1", new List<CustomAttribute>(), "", "");
- //Act
- var result = await _outOfStockSubscriptionService.FindSubscription("1", "1", new List<CustomAttribute>(), "", "");
+ //Assert
+ Assert.IsNotNull(result);
+ }
- //Assert
- Assert.IsNotNull(result);
- }
- [TestMethod()]
- public async Task FindSubscriptionTest_IsNull()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription2 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "2",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription3 = new OutOfStockSubscription {
- CustomerId = "2",
- ProductId = "3",
- StoreId = "",
- WarehouseId = ""
- };
- await _repository.InsertAsync(outOfStockSubscription1);
- await _repository.InsertAsync(outOfStockSubscription2);
- await _repository.InsertAsync(outOfStockSubscription3);
+ [TestMethod]
+ public async Task FindSubscriptionTest_IsNull()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription2 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "2",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription3 = new OutOfStockSubscription {
+ CustomerId = "2",
+ ProductId = "3",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ await _repository.InsertAsync(outOfStockSubscription1);
+ await _repository.InsertAsync(outOfStockSubscription2);
+ await _repository.InsertAsync(outOfStockSubscription3);
- //Act
- var result = await _outOfStockSubscriptionService.FindSubscription("1", "1", new List<CustomAttribute>(), "1", "");
+ //Act
+ var result =
+ await _outOfStockSubscriptionService.FindSubscription("1", "1", new List<CustomAttribute>(), "1", "");
- //Assert
- Assert.IsNull(result);
- }
- [TestMethod()]
- public async Task GetSubscriptionByIdTest()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription2 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "2",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription3 = new OutOfStockSubscription {
- CustomerId = "2",
- ProductId = "3",
- StoreId = "",
- WarehouseId = ""
- };
- await _repository.InsertAsync(outOfStockSubscription1);
- await _repository.InsertAsync(outOfStockSubscription2);
- await _repository.InsertAsync(outOfStockSubscription3);
+ //Assert
+ Assert.IsNull(result);
+ }
- //Act
- var result = await _outOfStockSubscriptionService.GetSubscriptionById(outOfStockSubscription1.Id);
+ [TestMethod]
+ public async Task GetSubscriptionByIdTest()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription2 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "2",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription3 = new OutOfStockSubscription {
+ CustomerId = "2",
+ ProductId = "3",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ await _repository.InsertAsync(outOfStockSubscription1);
+ await _repository.InsertAsync(outOfStockSubscription2);
+ await _repository.InsertAsync(outOfStockSubscription3);
- //Assert
- Assert.IsNotNull(result);
+ //Act
+ var result = await _outOfStockSubscriptionService.GetSubscriptionById(outOfStockSubscription1.Id);
- }
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task InsertSubscriptionTest()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- //Act
- await _outOfStockSubscriptionService.InsertSubscription(outOfStockSubscription1);
+ [TestMethod]
+ public async Task InsertSubscriptionTest()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ //Act
+ await _outOfStockSubscriptionService.InsertSubscription(outOfStockSubscription1);
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.IsTrue(_repository.Table.Count() == 1);
- }
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.IsTrue(_repository.Table.Count() == 1);
+ }
- [TestMethod()]
- public async Task UpdateSubscriptionTest()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- await _outOfStockSubscriptionService.InsertSubscription(outOfStockSubscription1);
- outOfStockSubscription1.CustomerId = "2";
- //Act
- await _outOfStockSubscriptionService.UpdateSubscription(outOfStockSubscription1);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault().CustomerId == "2");
- }
+ [TestMethod]
+ public async Task UpdateSubscriptionTest()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ await _outOfStockSubscriptionService.InsertSubscription(outOfStockSubscription1);
+ outOfStockSubscription1.CustomerId = "2";
+ //Act
+ await _outOfStockSubscriptionService.UpdateSubscription(outOfStockSubscription1);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault().CustomerId == "2");
+ }
- [TestMethod()]
- public async Task DeleteSubscriptionTest()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- await _outOfStockSubscriptionService.InsertSubscription(outOfStockSubscription1);
- //Act
- await _outOfStockSubscriptionService.DeleteSubscription(outOfStockSubscription1);
+ [TestMethod]
+ public async Task DeleteSubscriptionTest()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ await _outOfStockSubscriptionService.InsertSubscription(outOfStockSubscription1);
+ //Act
+ await _outOfStockSubscriptionService.DeleteSubscription(outOfStockSubscription1);
- //Assert
- Assert.IsFalse(_repository.Table.Any());
- Assert.IsTrue(_repository.Table.Count() == 0);
- }
+ //Assert
+ Assert.IsFalse(_repository.Table.Any());
+ Assert.IsTrue(_repository.Table.Count() == 0);
+ }
- [TestMethod()]
- public async Task SendNotificationsToSubscribersTest()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription2 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "2",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription3 = new OutOfStockSubscription {
- CustomerId = "2",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
-
- await _repository.InsertAsync(outOfStockSubscription1);
- await _repository.InsertAsync(outOfStockSubscription2);
- await _repository.InsertAsync(outOfStockSubscription3);
+ [TestMethod]
+ public async Task SendNotificationsToSubscribersTest()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription2 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "2",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription3 = new OutOfStockSubscription {
+ CustomerId = "2",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
- //Act
- await _outOfStockSubscriptionService.SendNotificationsToSubscribers(new Product { Id = "1" }, "");
+ await _repository.InsertAsync(outOfStockSubscription1);
+ await _repository.InsertAsync(outOfStockSubscription2);
+ await _repository.InsertAsync(outOfStockSubscription3);
- //Assert
- _mediatorMock.Verify(c => c.Send(It.IsAny<SendNotificationsToSubscribersCommand>(), default), Times.AtLeastOnce);
- }
+ //Act
+ await _outOfStockSubscriptionService.SendNotificationsToSubscribers(new Product { Id = "1" }, "");
- [TestMethod()]
- public async Task SendNotificationsToSubscribersTest1()
- {
- //Arange
- var outOfStockSubscription1 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- outOfStockSubscription1.Attributes.Add(new CustomAttribute { Key = "MyKey", Value = "1" });
+ //Assert
+ _mediatorMock.Verify(c => c.Send(It.IsAny<SendNotificationsToSubscribersCommand>(), default),
+ Times.AtLeastOnce);
+ }
+
+ [TestMethod]
+ public async Task SendNotificationsToSubscribersTest1()
+ {
+ //Arange
+ var outOfStockSubscription1 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ outOfStockSubscription1.Attributes.Add(new CustomAttribute { Key = "MyKey", Value = "1" });
- var outOfStockSubscription2 = new OutOfStockSubscription {
- CustomerId = "1",
- ProductId = "2",
- StoreId = "",
- WarehouseId = ""
- };
- var outOfStockSubscription3 = new OutOfStockSubscription {
- CustomerId = "2",
- ProductId = "1",
- StoreId = "",
- WarehouseId = ""
- };
- await _repository.InsertAsync(outOfStockSubscription1);
- await _repository.InsertAsync(outOfStockSubscription2);
- await _repository.InsertAsync(outOfStockSubscription3);
+ var outOfStockSubscription2 = new OutOfStockSubscription {
+ CustomerId = "1",
+ ProductId = "2",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ var outOfStockSubscription3 = new OutOfStockSubscription {
+ CustomerId = "2",
+ ProductId = "1",
+ StoreId = "",
+ WarehouseId = ""
+ };
+ await _repository.InsertAsync(outOfStockSubscription1);
+ await _repository.InsertAsync(outOfStockSubscription2);
+ await _repository.InsertAsync(outOfStockSubscription3);
- //Act
- await _outOfStockSubscriptionService.SendNotificationsToSubscribers(new Product { Id = "1" }, new CustomAttribute[] { new CustomAttribute { Key = "MyKey", Value = "1" } }, "");
+ //Act
+ await _outOfStockSubscriptionService.SendNotificationsToSubscribers(new Product { Id = "1" },
+ new CustomAttribute[] { new() { Key = "MyKey", Value = "1" } }, "");
- //Assert
- _mediatorMock.Verify(c => c.Send(It.IsAny<SendNotificationsToSubscribersCommand>(), default), Times.AtLeastOnce);
- }
+ //Assert
+ _mediatorMock.Verify(c => c.Send(It.IsAny<SendNotificationsToSubscribersCommand>(), default),
+ Times.AtLeastOnce);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs
index e1db74aa6..85d0d05eb 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeFormatterTests.cs
@@ -8,6 +8,7 @@ using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.SharedKernel.Extensions;
@@ -15,85 +16,91 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductAttributeFormatterTests
{
- [TestClass()]
- public class ProductAttributeFormatterTests
+ private IAclService _aclServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IPriceFormatter> _priceFormatterMock;
+ private Mock<IPricingService> _pricingServiceMock;
+ private ProductAttributeFormatter _productAttributeFormatter;
+ private Mock<IProductAttributeService> _productAttributeServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<ITaxService> _taxServiceMock;
+ private Mock<ITranslationService> _translationServiceMock;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _productAttributeServiceMock = new Mock<IProductAttributeService>();
+ _productAttributeServiceMock.Setup(x => x.GetProductAttributeById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new ProductAttribute { Name = "test" }));
+ _translationServiceMock = new Mock<ITranslationService>();
+ _translationServiceMock.Setup(x => x.GetResource("GiftVoucherAttribute.From.Virtual"))
+ .Returns("Name {0}, Email {1}");
+ _translationServiceMock.Setup(x => x.GetResource("GiftVoucherAttribute.For.Virtual"))
+ .Returns("RecName {0}, RecEmail {1}");
+ _taxServiceMock = new Mock<ITaxService>();
+ _priceFormatterMock = new Mock<IPriceFormatter>();
+ _pricingServiceMock = new Mock<IPricingService>();
+ _productServiceMock = new Mock<IProductService>();
+ _mediatorMock = new Mock<IMediator>();
+ _aclServiceMock = new AclService(new AccessControlConfig());
+ _productAttributeFormatter = new ProductAttributeFormatter(_workContextMock.Object,
+ _productAttributeServiceMock.Object,
+ _taxServiceMock.Object, _priceFormatterMock.Object, _pricingServiceMock.Object, _productServiceMock.Object);
+ }
+
+ [TestMethod]
+ public async Task FormatAttributesTest_EmptyCustomAttribute()
{
- private ProductAttributeFormatter _productAttributeFormatter;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private IAclService _aclServiceMock;
- private Mock<IProductAttributeService> _productAttributeServiceMock;
- private Mock<ITranslationService> _translationServiceMock;
- private Mock<ITaxService> _taxServiceMock;
- private Mock<IPriceFormatter> _priceFormatterMock;
- private Mock<IPricingService> _pricingServiceMock;
- private Mock<IProductService> _productServiceMock;
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
+ //Arrange
+ var product = new Product();
+ //Act
+ var result = await _productAttributeFormatter.FormatAttributes(product, new List<CustomAttribute>());
+ //Assert
+ Assert.AreEqual("", result);
+ }
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _productAttributeServiceMock = new Mock<IProductAttributeService>();
- _productAttributeServiceMock.Setup(x => x.GetProductAttributeById(It.IsAny<string>())).Returns(Task.FromResult(new ProductAttribute { Name = "test" }));
- _translationServiceMock = new Mock<ITranslationService>();
- _translationServiceMock.Setup(x => x.GetResource("GiftVoucherAttribute.From.Virtual")).Returns("Name {0}, Email {1}");
- _translationServiceMock.Setup(x => x.GetResource("GiftVoucherAttribute.For.Virtual")).Returns("RecName {0}, RecEmail {1}");
- _taxServiceMock = new Mock<ITaxService>();
- _priceFormatterMock = new Mock<IPriceFormatter>();
- _pricingServiceMock = new Mock<IPricingService>();
- _productServiceMock = new Mock<IProductService>();
- _mediatorMock = new Mock<IMediator>();
- _aclServiceMock = new AclService(new AccessControlConfig());
- _productAttributeFormatter = new ProductAttributeFormatter(_workContextMock.Object, _productAttributeServiceMock.Object,
- _taxServiceMock.Object, _priceFormatterMock.Object, _pricingServiceMock.Object, _productServiceMock.Object);
- }
+ [TestMethod]
+ public async Task FormatAttributesTest_GiftVoucher()
+ {
+ //Arrange
+ var product = new Product { GiftVoucherTypeId = GiftVoucherType.Virtual, IsGiftVoucher = true };
+ //Act
+ var result = await _productAttributeFormatter.FormatAttributes(product, new List<CustomAttribute> {
+ new() { Key = "RecipientName", Value = "John" },
+ new() { Key = "RecipientEmail", Value = "[email protected]" },
+ new() { Key = "SenderName", Value = "Will" },
+ new() { Key = "SenderEmail", Value = "[email protected]" },
+ new() { Key = "Message", Value = "" }
+ });
+ //Assert
+ Assert.AreEqual("Will &lt;[email protected]&gt;<br />John &lt;[email protected]&gt;", result);
+ }
- [TestMethod()]
- public async Task FormatAttributesTest_EmptyCustomAttribute()
- {
- //Arrange
- var product = new Product();
- //Act
- var result = await _productAttributeFormatter.FormatAttributes(product, new List<CustomAttribute>());
- //Assert
- Assert.AreEqual("", result);
-
- }
- [TestMethod()]
- public async Task FormatAttributesTest_GiftVoucher()
- {
- //Arrange
- var product = new Product { GiftVoucherTypeId = GiftVoucherType.Virtual, IsGiftVoucher = true };
- //Act
- var result = await _productAttributeFormatter.FormatAttributes(product, new List<CustomAttribute> {
- new CustomAttribute { Key = "RecipientName", Value = "John" },
- new CustomAttribute { Key = "RecipientEmail", Value = "[email protected]" },
- new CustomAttribute { Key = "SenderName", Value = "Will" },
- new CustomAttribute { Key = "SenderEmail", Value = "[email protected]" },
- new CustomAttribute { Key = "Message", Value = "" }
- });
- //Assert
- Assert.AreEqual("Will &lt;[email protected]&gt;<br />John &lt;[email protected]&gt;", result);
- }
- [TestMethod()]
- public async Task FormatAttributesTest_CustomAttribute()
- {
- //Arrange
- var product = new Product();
- var productAttributeMapping = new ProductAttributeMapping { Id = "1", AttributeControlTypeId = AttributeControlType.Checkboxes };
- productAttributeMapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "aa" });
- product.ProductAttributeMappings.Add(productAttributeMapping);
- //Act
- var result = await _productAttributeFormatter.FormatAttributes(product, new List<CustomAttribute> {
- new CustomAttribute { Key = "1", Value = "1" }
- });
- //Assert
- Assert.AreEqual("test: aa", result);
- }
+ [TestMethod]
+ public async Task FormatAttributesTest_CustomAttribute()
+ {
+ //Arrange
+ var product = new Product();
+ var productAttributeMapping = new ProductAttributeMapping
+ { Id = "1", AttributeControlTypeId = AttributeControlType.Checkboxes };
+ productAttributeMapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "aa" });
+ product.ProductAttributeMappings.Add(productAttributeMapping);
+ //Act
+ var result = await _productAttributeFormatter.FormatAttributes(product, new List<CustomAttribute> {
+ new() { Key = "1", Value = "1" }
+ });
+ //Assert
+ Assert.AreEqual("test: aa", result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeParserTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeParserTests.cs
index 7a96e0ee1..6b7f3561e 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeParserTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeParserTests.cs
@@ -2,87 +2,87 @@
using Grand.Domain.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductExtensionsAttributeParserTests
{
- [TestClass()]
- public class ProductExtensionsAttributeParserTests
- {
- private List<CustomAttribute> customAtr;
+ private List<CustomAttribute> customAtr;
- [TestInitialize()]
- public void Init()
- {
- customAtr = [
- new CustomAttribute { Key = "key1", Value = "value1" },
- new CustomAttribute { Key = "key2", Value = "value2" },
- new CustomAttribute { Key = "key3", Value = "value3" },
- new CustomAttribute { Key = "key4", Value = "value4" }
- ];
- }
+ [TestInitialize]
+ public void Init()
+ {
+ customAtr = [
+ new CustomAttribute { Key = "key1", Value = "value1" },
+ new CustomAttribute { Key = "key2", Value = "value2" },
+ new CustomAttribute { Key = "key3", Value = "value3" },
+ new CustomAttribute { Key = "key4", Value = "value4" }
+ ];
+ }
- [TestMethod()]
- public void ParseProductAttributeMappings_ReturnExpectedValues()
- {
- var product = new Product();
- product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key1" });
- product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key2" });
- var result = product.ParseProductAttributeMappings(customAtr);
+ [TestMethod]
+ public void ParseProductAttributeMappings_ReturnExpectedValues()
+ {
+ var product = new Product();
+ product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key1" });
+ product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key2" });
+ var result = product.ParseProductAttributeMappings(customAtr);
- Assert.IsTrue(result.Any(c => c.Id.Equals("key1")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("key2")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("key3")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("key4")));
- }
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key1")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key2")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("key3")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("key4")));
+ }
- [TestMethod()]
- public void ParseProductAttributeMappings_ReturnEmptyList()
- {
- var product = new Product();
- product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key10" });
- product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key12" });
- var result = product.ParseProductAttributeMappings(customAtr);
- Assert.IsTrue(result.Count == 0);
- }
+ [TestMethod]
+ public void ParseProductAttributeMappings_ReturnEmptyList()
+ {
+ var product = new Product();
+ product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key10" });
+ product.ProductAttributeMappings.Add(new ProductAttributeMapping { Id = "key12" });
+ var result = product.ParseProductAttributeMappings(customAtr);
+ Assert.IsTrue(result.Count == 0);
+ }
- [TestMethod()]
- public void ParseProductAttributeValues_ReturnExpectedValues()
- {
- var product = new Product();
- var mapping1 = new ProductAttributeMapping { Id = "key1" };
- mapping1.ProductAttributeValues.Add(new ProductAttributeValue { Id = "value1" });
- product.ProductAttributeMappings.Add(mapping1);
- var mapping2 = new ProductAttributeMapping { Id = "key2" };
- mapping2.ProductAttributeValues.Add(new ProductAttributeValue { Id = "value2" });
- product.ProductAttributeMappings.Add(mapping2);
- var result = product.ParseProductAttributeValues(customAtr);
+ [TestMethod]
+ public void ParseProductAttributeValues_ReturnExpectedValues()
+ {
+ var product = new Product();
+ var mapping1 = new ProductAttributeMapping { Id = "key1" };
+ mapping1.ProductAttributeValues.Add(new ProductAttributeValue { Id = "value1" });
+ product.ProductAttributeMappings.Add(mapping1);
+ var mapping2 = new ProductAttributeMapping { Id = "key2" };
+ mapping2.ProductAttributeValues.Add(new ProductAttributeValue { Id = "value2" });
+ product.ProductAttributeMappings.Add(mapping2);
+ var result = product.ParseProductAttributeValues(customAtr);
- Assert.IsTrue(result.Any(c => c.Id.Equals("value1")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("value2")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("value3")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("value4")));
- }
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value1")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value2")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("value3")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("value4")));
+ }
- [TestMethod()]
- public void ParseValues_ReturnExpectedValues()
- {
- var result = ProductExtensions.ParseValues(customAtr, "key1");
- Assert.IsTrue(result.Any(c => c.Equals("value1")));
- }
+ [TestMethod]
+ public void ParseValues_ReturnExpectedValues()
+ {
+ var result = ProductExtensions.ParseValues(customAtr, "key1");
+ Assert.IsTrue(result.Any(c => c.Equals("value1")));
+ }
- [TestMethod()]
- public void AddProductAttribute_ReturnExpectedValues()
- {
- var result = ProductExtensions.AddProductAttribute(customAtr, new ProductAttributeMapping { Id = "key6" }, "value6");
- Assert.IsTrue(result.Count == 5);
- Assert.IsTrue(result.Last().Value.Equals("value6"));
- }
+ [TestMethod]
+ public void AddProductAttribute_ReturnExpectedValues()
+ {
+ var result =
+ ProductExtensions.AddProductAttribute(customAtr, new ProductAttributeMapping { Id = "key6" }, "value6");
+ Assert.IsTrue(result.Count == 5);
+ Assert.IsTrue(result.Last().Value.Equals("value6"));
+ }
- [TestMethod()]
- public void RemoveProductAttribute_ReturnExpectedValues()
- {
- var result = ProductExtensions.RemoveProductAttribute(customAtr, new ProductAttributeMapping { Id = "key1" });
- Assert.IsTrue(result.Count == 3);
- Assert.IsFalse(result.Any(c => c.Key.Equals("key1")));
- }
+ [TestMethod]
+ public void RemoveProductAttribute_ReturnExpectedValues()
+ {
+ var result = ProductExtensions.RemoveProductAttribute(customAtr, new ProductAttributeMapping { Id = "key1" });
+ Assert.IsTrue(result.Count == 3);
+ Assert.IsFalse(result.Any(c => c.Key.Equals("key1")));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeServiceTests.cs
index cd5ab4bbe..be0312181 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductAttributeServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Catalog.Services.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -10,254 +10,264 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductAttributeServiceTests
{
- [TestClass()]
- public class ProductAttributeServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private ProductAttributeService _productAttributeService;
+ private IRepository<Product> _repository;
+ private IRepository<ProductAttribute> _repositoryproductAttribute;
+
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _repository = new MongoDBRepositoryTest<Product>();
+ _repositoryproductAttribute = new MongoDBRepositoryTest<ProductAttribute>();
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _productAttributeService =
+ new ProductAttributeService(_cacheBase, _repositoryproductAttribute, _repository, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetAllProductAttributesTest()
+ {
+ //Arange
+ var pa1 = new ProductAttribute();
+ var pa2 = new ProductAttribute();
+ var pa3 = new ProductAttribute();
+ await _repositoryproductAttribute.InsertAsync(pa1);
+ await _repositoryproductAttribute.InsertAsync(pa2);
+ await _repositoryproductAttribute.InsertAsync(pa3);
+
+ //Act
+ var result = await _productAttributeService.GetAllProductAttributes();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetProductAttributeByIdTest()
+ {
+ //Arange
+ var pa1 = new ProductAttribute();
+ var pa2 = new ProductAttribute();
+ var pa3 = new ProductAttribute();
+ await _repositoryproductAttribute.InsertAsync(pa1);
+ await _repositoryproductAttribute.InsertAsync(pa2);
+ await _repositoryproductAttribute.InsertAsync(pa3);
+
+ //Act
+ var result = await _productAttributeService.GetProductAttributeById(pa1.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task InsertProductAttributeTest()
+ {
+ //Arange
+ var pa1 = new ProductAttribute();
+
+ //Act
+ await _productAttributeService.InsertProductAttribute(pa1);
+
+ //Assert
+ Assert.IsTrue(_repositoryproductAttribute.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateProductAttributeTest()
+ {
+ //Arange
+ var pa1 = new ProductAttribute();
+ await _productAttributeService.InsertProductAttribute(pa1);
+ pa1.Name = "test";
+ //Act
+ await _productAttributeService.UpdateProductAttribute(pa1);
+ //Assert
+ Assert.IsTrue(_repositoryproductAttribute.Table.FirstOrDefault().Name == "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteProductAttributeTest()
+ {
+ //Arange
+ var pa1 = new ProductAttribute();
+ await _productAttributeService.InsertProductAttribute(pa1);
+
+ //Act
+ await _productAttributeService.DeleteProductAttribute(pa1);
+
+ //Assert
+ Assert.IsFalse(_repositoryproductAttribute.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task DeleteProductAttributeMappingTest()
+ {
+ //Arrange
+ var product = new Product();
+ var pm1 = new ProductAttributeMapping();
+ product.ProductAttributeMappings.Add(pm1);
+ var pm2 = new ProductAttributeMapping();
+ product.ProductAttributeMappings.Add(pm2);
+ var pm3 = new ProductAttributeMapping();
+ product.ProductAttributeMappings.Add(pm3);
+ _repository.Insert(product);
+
+ //Act
+ await _productAttributeService.DeleteProductAttributeMapping(pm1, product.Id);
+ //Assert
+ Assert.AreEqual(2, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductAttributeMappingTest()
+ {
+ //Arrange
+ var product = new Product();
+ var pm1 = new ProductAttributeMapping();
+ _repository.Insert(product);
+
+ //Act
+ await _productAttributeService.InsertProductAttributeMapping(pm1, product.Id);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductAttributeMappingTest()
+ {
+ //Arrange
+ var product = new Product();
+ var pm1 = new ProductAttributeMapping();
+ product.ProductAttributeMappings.Add(pm1);
+ _repository.Insert(product);
+ //Act
+ pm1.TextPrompt = "test";
+ await _productAttributeService.UpdateProductAttributeMapping(pm1, product.Id);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings
+ .FirstOrDefault(x => x.Id == pm1.Id).TextPrompt == "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteProductAttributeValueTest()
+ {
+ //Arrange
+ var product = new Product();
+ var pm1 = new ProductAttributeMapping();
+ var pav1 = new ProductAttributeValue();
+ pm1.ProductAttributeValues.Add(pav1);
+ var pav2 = new ProductAttributeValue();
+ pm1.ProductAttributeValues.Add(pav2);
+ product.ProductAttributeMappings.Add(pm1);
+ _repository.Insert(product);
+
+ //Act
+ await _productAttributeService.DeleteProductAttributeValue(pav1, product.Id, pm1.Id);
+ //Assert
+ Assert.AreEqual(1,
+ _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings
+ .FirstOrDefault(x => x.Id == pm1.Id).ProductAttributeValues.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductAttributeValueTest()
+ {
+ //Arrange
+ var product = new Product();
+ var pm1 = new ProductAttributeMapping();
+ var pav1 = new ProductAttributeValue();
+ product.ProductAttributeMappings.Add(pm1);
+ _repository.Insert(product);
+
+ //Act
+ await _productAttributeService.InsertProductAttributeValue(pav1, product.Id, pm1.Id);
+ //Assert
+ Assert.AreEqual(1,
+ _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings
+ .FirstOrDefault(x => x.Id == pm1.Id).ProductAttributeValues.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductAttributeValueTest()
+ {
+ //Arrange
+ var product = new Product();
+ var pm1 = new ProductAttributeMapping();
+ var pav1 = new ProductAttributeValue();
+ pm1.ProductAttributeValues.Add(pav1);
+ product.ProductAttributeMappings.Add(pm1);
+ _repository.Insert(product);
+
+ //Act
+ pav1.Name = "test";
+ await _productAttributeService.UpdateProductAttributeValue(pav1, product.Id, pm1.Id);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings
+ .FirstOrDefault(x => x.Id == pm1.Id).ProductAttributeValues.FirstOrDefault().Name == "test");
+ }
+
+
+ [TestMethod]
+ public async Task DeleteProductAttributeCombinationTest()
+ {
+ //Arrange
+ var product = new Product();
+ var pac1 = new ProductAttributeCombination();
+ product.ProductAttributeCombinations.Add(pac1);
+ var pac2 = new ProductAttributeCombination();
+ product.ProductAttributeCombinations.Add(pac2);
+ var pac3 = new ProductAttributeCombination();
+ product.ProductAttributeCombinations.Add(pac3);
+ _repository.Insert(product);
+
+ //Act
+ await _productAttributeService.DeleteProductAttributeCombination(pac1, product.Id);
+ //Assert
+ Assert.AreEqual(2,
+ _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeCombinations.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductAttributeCombinationTest()
+ {
+ //Arrange
+ var product = new Product();
+ _repository.Insert(product);
+ var pac1 = new ProductAttributeCombination();
+ //Act
+ await _productAttributeService.InsertProductAttributeCombination(pac1, product.Id);
+ //Assert
+ Assert.AreEqual(1,
+ _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeCombinations.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductAttributeCombinationTest()
{
- private IRepository<Product> _repository;
- private IRepository<ProductAttribute> _repositoryproductAttribute;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
- private ProductAttributeService _productAttributeService;
-
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "";
-
- _repository = new MongoDBRepositoryTest<Product>();
- _repositoryproductAttribute = new MongoDBRepositoryTest<ProductAttribute>();
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _productAttributeService = new ProductAttributeService(_cacheBase, _repositoryproductAttribute, _repository, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetAllProductAttributesTest()
- {
- //Arange
- var pa1 = new ProductAttribute();
- var pa2 = new ProductAttribute();
- var pa3 = new ProductAttribute();
- await _repositoryproductAttribute.InsertAsync(pa1);
- await _repositoryproductAttribute.InsertAsync(pa2);
- await _repositoryproductAttribute.InsertAsync(pa3);
-
- //Act
- var result = await _productAttributeService.GetAllProductAttributes();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetProductAttributeByIdTest()
- {
- //Arange
- var pa1 = new ProductAttribute();
- var pa2 = new ProductAttribute();
- var pa3 = new ProductAttribute();
- await _repositoryproductAttribute.InsertAsync(pa1);
- await _repositoryproductAttribute.InsertAsync(pa2);
- await _repositoryproductAttribute.InsertAsync(pa3);
-
- //Act
- var result = await _productAttributeService.GetProductAttributeById(pa1.Id);
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task InsertProductAttributeTest()
- {
- //Arange
- var pa1 = new ProductAttribute();
-
- //Act
- await _productAttributeService.InsertProductAttribute(pa1);
-
- //Assert
- Assert.IsTrue(_repositoryproductAttribute.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateProductAttributeTest()
- {
- //Arange
- var pa1 = new ProductAttribute();
- await _productAttributeService.InsertProductAttribute(pa1);
- pa1.Name = "test";
- //Act
- await _productAttributeService.UpdateProductAttribute(pa1);
- //Assert
- Assert.IsTrue(_repositoryproductAttribute.Table.FirstOrDefault().Name == "test");
- }
-
- [TestMethod()]
- public async Task DeleteProductAttributeTest()
- {
- //Arange
- var pa1 = new ProductAttribute();
- await _productAttributeService.InsertProductAttribute(pa1);
-
- //Act
- await _productAttributeService.DeleteProductAttribute(pa1);
-
- //Assert
- Assert.IsFalse(_repositoryproductAttribute.Table.Any());
- }
-
- [TestMethod()]
- public async Task DeleteProductAttributeMappingTest()
- {
- //Arrange
- var product = new Product();
- var pm1 = new ProductAttributeMapping();
- product.ProductAttributeMappings.Add(pm1);
- var pm2 = new ProductAttributeMapping();
- product.ProductAttributeMappings.Add(pm2);
- var pm3 = new ProductAttributeMapping();
- product.ProductAttributeMappings.Add(pm3);
- _repository.Insert(product);
-
- //Act
- await _productAttributeService.DeleteProductAttributeMapping(pm1, product.Id);
- //Assert
- Assert.AreEqual(2, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductAttributeMappingTest()
- {
- //Arrange
- var product = new Product();
- var pm1 = new ProductAttributeMapping();
- _repository.Insert(product);
-
- //Act
- await _productAttributeService.InsertProductAttributeMapping(pm1, product.Id);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.Count);
- }
-
- [TestMethod()]
- public async Task UpdateProductAttributeMappingTest()
- {
- //Arrange
- var product = new Product();
- var pm1 = new ProductAttributeMapping();
- product.ProductAttributeMappings.Add(pm1);
- _repository.Insert(product);
- //Act
- pm1.TextPrompt = "test";
- await _productAttributeService.UpdateProductAttributeMapping(pm1, product.Id);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.FirstOrDefault(x => x.Id == pm1.Id).TextPrompt == "test");
- }
-
- [TestMethod()]
- public async Task DeleteProductAttributeValueTest()
- {
- //Arrange
- var product = new Product();
- var pm1 = new ProductAttributeMapping();
- var pav1 = new ProductAttributeValue();
- pm1.ProductAttributeValues.Add(pav1);
- var pav2 = new ProductAttributeValue();
- pm1.ProductAttributeValues.Add(pav2);
- product.ProductAttributeMappings.Add(pm1);
- _repository.Insert(product);
-
- //Act
- await _productAttributeService.DeleteProductAttributeValue(pav1, product.Id, pm1.Id);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.FirstOrDefault(x => x.Id == pm1.Id).ProductAttributeValues.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductAttributeValueTest()
- {
- //Arrange
- var product = new Product();
- var pm1 = new ProductAttributeMapping();
- var pav1 = new ProductAttributeValue();
- product.ProductAttributeMappings.Add(pm1);
- _repository.Insert(product);
-
- //Act
- await _productAttributeService.InsertProductAttributeValue(pav1, product.Id, pm1.Id);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.FirstOrDefault(x => x.Id == pm1.Id).ProductAttributeValues.Count);
- }
-
- [TestMethod()]
- public async Task UpdateProductAttributeValueTest()
- {
- //Arrange
- var product = new Product();
- var pm1 = new ProductAttributeMapping();
- var pav1 = new ProductAttributeValue();
- pm1.ProductAttributeValues.Add(pav1);
- product.ProductAttributeMappings.Add(pm1);
- _repository.Insert(product);
-
- //Act
- pav1.Name = "test";
- await _productAttributeService.UpdateProductAttributeValue(pav1, product.Id, pm1.Id);
-
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeMappings.FirstOrDefault(x => x.Id == pm1.Id).ProductAttributeValues.FirstOrDefault().Name == "test");
- }
-
-
- [TestMethod()]
- public async Task DeleteProductAttributeCombinationTest()
- {
- //Arrange
- var product = new Product();
- var pac1 = new ProductAttributeCombination();
- product.ProductAttributeCombinations.Add(pac1);
- var pac2 = new ProductAttributeCombination();
- product.ProductAttributeCombinations.Add(pac2);
- var pac3 = new ProductAttributeCombination();
- product.ProductAttributeCombinations.Add(pac3);
- _repository.Insert(product);
-
- //Act
- await _productAttributeService.DeleteProductAttributeCombination(pac1, product.Id);
- //Assert
- Assert.AreEqual(2, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeCombinations.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductAttributeCombinationTest()
- {
- //Arrange
- var product = new Product();
- _repository.Insert(product);
- var pac1 = new ProductAttributeCombination();
- //Act
- await _productAttributeService.InsertProductAttributeCombination(pac1, product.Id);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeCombinations.Count);
- }
-
- [TestMethod()]
- public async Task UpdateProductAttributeCombinationTest()
- {
- //Arrange
- var product = new Product();
- var pac1 = new ProductAttributeCombination();
- product.ProductAttributeCombinations.Add(pac1);
- _repository.Insert(product);
- //Act
- pac1.Text = "test";
- await _productAttributeService.UpdateProductAttributeCombination(pac1, product.Id);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeCombinations.FirstOrDefault(x => x.Id == pac1.Id).Text == "test");
- }
+ //Arrange
+ var product = new Product();
+ var pac1 = new ProductAttributeCombination();
+ product.ProductAttributeCombinations.Add(pac1);
+ _repository.Insert(product);
+ //Act
+ pac1.Text = "test";
+ await _productAttributeService.UpdateProductAttributeCombination(pac1, product.Id);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == product.Id).ProductAttributeCombinations
+ .FirstOrDefault(x => x.Id == pac1.Id).Text == "test");
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductCourseServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductCourseServiceTests.cs
index 362e191ce..d11ede5a1 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductCourseServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductCourseServiceTests.cs
@@ -1,69 +1,67 @@
using Grand.Business.Catalog.Services.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Courses;
-using Grand.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Services.Products
-{
- [TestClass()]
- public class ProductCourseServiceTests
- {
- private IRepository<Product> _repository;
- private IRepository<Course> _courseRepository;
- private ProductCourseService _courseService;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Product>();
- _courseRepository = new MongoDBRepositoryTest<Course>();
- _courseService = new ProductCourseService(_repository, _courseRepository);
+namespace Grand.Business.Catalog.Tests.Services.Products;
- }
+[TestClass]
+public class ProductCourseServiceTests
+{
+ private IRepository<Course> _courseRepository;
+ private ProductCourseService _courseService;
+ private IRepository<Product> _repository;
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Product>();
+ _courseRepository = new MongoDBRepositoryTest<Course>();
+ _courseService = new ProductCourseService(_repository, _courseRepository);
+ }
- [TestMethod()]
- public async Task GetCourseByProductIdTest()
- {
- //Arrange
- var course1 = new Course { ProductId = "1" };
- await _courseRepository.InsertAsync(course1);
- //Act
- var result = await _courseService.GetCourseByProductId("1");
- //Arrange
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetCourseByProductIdTest()
+ {
+ //Arrange
+ var course1 = new Course { ProductId = "1" };
+ await _courseRepository.InsertAsync(course1);
+ //Act
+ var result = await _courseService.GetCourseByProductId("1");
- [TestMethod()]
- public async Task GetProductByCourseIdTest()
- {
- //Arrange
- var product = new Product { CourseId = "1", Id = "1"};
- await _repository.InsertAsync(product);
- //Act
- var result = await _courseService.GetProductByCourseId("1");
+ //Arrange
+ Assert.IsNotNull(result);
+ }
- //Arrange
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.Id);
+ [TestMethod]
+ public async Task GetProductByCourseIdTest()
+ {
+ //Arrange
+ var product = new Product { CourseId = "1", Id = "1" };
+ await _repository.InsertAsync(product);
+ //Act
+ var result = await _courseService.GetProductByCourseId("1");
- }
+ //Arrange
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.Id);
+ }
- [TestMethod()]
- public async Task UpdateCourseOnProductTest()
- {
- //Arrange
- var product = new Product { CourseId = "1", Id = "1" };
- await _repository.InsertAsync(product);
+ [TestMethod]
+ public async Task UpdateCourseOnProductTest()
+ {
+ //Arrange
+ var product = new Product { CourseId = "1", Id = "1" };
+ await _repository.InsertAsync(product);
- //Act
- await _courseService.UpdateCourseOnProduct("1", "2");
+ //Act
+ await _courseService.UpdateCourseOnProduct("1", "2");
- //Arrange
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x=>x.Id == "1"));
- Assert.AreEqual("2", _repository.Table.FirstOrDefault(x => x.Id== "1").CourseId);
- }
+ //Arrange
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == "1"));
+ Assert.AreEqual("2", _repository.Table.FirstOrDefault(x => x.Id == "1").CourseId);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductLayoutServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductLayoutServiceTests.cs
index 2c4314c12..5f2e5ece3 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductLayoutServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductLayoutServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Catalog.Services.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,104 +9,104 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductLayoutServiceTests
{
- [TestClass()]
- public class ProductLayoutServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private ProductLayoutService _productLayoutService;
+ private IRepository<ProductLayout> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<ProductLayout>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _productLayoutService = new ProductLayoutService(_repository, _cacheBase, _mediatorMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task GetAllProductLayoutsTest()
+ {
+ //Arrange
+ await _productLayoutService.InsertProductLayout(new ProductLayout());
+ await _productLayoutService.InsertProductLayout(new ProductLayout());
+ await _productLayoutService.InsertProductLayout(new ProductLayout());
+
+ //Act
+ var layouts = await _productLayoutService.GetAllProductLayouts();
+
+ //Assert
+ Assert.AreEqual(3, layouts.Count);
+ }
+
+ [TestMethod]
+ public async Task GetProductLayoutByIdTest()
+ {
+ //Arrange
+ var productLayout = new ProductLayout {
+ Name = "test"
+ };
+ await _productLayoutService.InsertProductLayout(productLayout);
+
+ //Act
+ var layout = await _productLayoutService.GetProductLayoutById(productLayout.Id);
+
+ //Assert
+ Assert.IsNotNull(layout);
+ Assert.AreEqual("test", layout.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertProductLayoutTest()
+ {
+ //Act
+ await _productLayoutService.InsertProductLayout(new ProductLayout());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateProductLayoutTest()
+ {
+ //Arrange
+ var categoryLayout = new ProductLayout {
+ Name = "test"
+ };
+ await _productLayoutService.InsertProductLayout(categoryLayout);
+ categoryLayout.Name = "test2";
+
+ //Act
+ await _productLayoutService.UpdateProductLayout(categoryLayout);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
+ }
+
+ [TestMethod]
+ public async Task DeleteProductLayoutTest()
{
- private IRepository<ProductLayout> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private ProductLayoutService _productLayoutService;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<ProductLayout>();
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _productLayoutService = new ProductLayoutService(_repository, _cacheBase, _mediatorMock.Object);
- }
-
-
- [TestMethod()]
- public async Task GetAllProductLayoutsTest()
- {
- //Arrange
- await _productLayoutService.InsertProductLayout(new ProductLayout());
- await _productLayoutService.InsertProductLayout(new ProductLayout());
- await _productLayoutService.InsertProductLayout(new ProductLayout());
-
- //Act
- var layouts = await _productLayoutService.GetAllProductLayouts();
-
- //Assert
- Assert.AreEqual(3, layouts.Count);
- }
-
- [TestMethod()]
- public async Task GetProductLayoutByIdTest()
- {
- //Arrange
- var productLayout = new ProductLayout {
- Name = "test"
- };
- await _productLayoutService.InsertProductLayout(productLayout);
-
- //Act
- var layout = await _productLayoutService.GetProductLayoutById(productLayout.Id);
-
- //Assert
- Assert.IsNotNull(layout);
- Assert.AreEqual("test", layout.Name);
- }
-
- [TestMethod()]
- public async Task InsertProductLayoutTest()
- {
- //Act
- await _productLayoutService.InsertProductLayout(new ProductLayout());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateProductLayoutTest()
- {
- //Arrange
- var categoryLayout = new ProductLayout {
- Name = "test"
- };
- await _productLayoutService.InsertProductLayout(categoryLayout);
- categoryLayout.Name = "test2";
-
- //Act
- await _productLayoutService.UpdateProductLayout(categoryLayout);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
-
- [TestMethod()]
- public async Task DeleteProductLayoutTest()
- {
- //Arrange
- var productLayout1 = new ProductLayout {
- Name = "test1"
- };
- await _productLayoutService.InsertProductLayout(productLayout1);
- var productLayout2 = new ProductLayout {
- Name = "test2"
- };
- await _productLayoutService.InsertProductLayout(productLayout2);
-
- //Act
- await _productLayoutService.DeleteProductLayout(productLayout1);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
- Assert.AreEqual(1, _repository.Table.Count());
- }
+ //Arrange
+ var productLayout1 = new ProductLayout {
+ Name = "test1"
+ };
+ await _productLayoutService.InsertProductLayout(productLayout1);
+ var productLayout2 = new ProductLayout {
+ Name = "test2"
+ };
+ await _productLayoutService.InsertProductLayout(productLayout2);
+
+ //Act
+ await _productLayoutService.DeleteProductLayout(productLayout1);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test1"));
+ Assert.AreEqual(1, _repository.Table.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs
index c365c5efd..0acadd75b 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReservationServiceTests.cs
@@ -1,168 +1,170 @@
using Grand.Business.Catalog.Services.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductReservationServiceTests
{
- [TestClass()]
- public class ProductReservationServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<ProductReservation> _repository;
+ private IRepository<CustomerReservationsHelper> _repositoryCustomerReservationsHelper;
+
+ private ProductReservationService _service;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<ProductReservation>();
+ _repositoryCustomerReservationsHelper = new MongoDBRepositoryTest<CustomerReservationsHelper>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _service = new ProductReservationService(_repository, _repositoryCustomerReservationsHelper,
+ _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetProductReservationsByProductIdTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new ProductReservation { ProductId = "1" });
+ await _repository.InsertAsync(new ProductReservation { ProductId = "1" });
+ await _repository.InsertAsync(new ProductReservation { ProductId = "2" });
+ //Act
+ var result = await _service.GetProductReservationsByProductId("1", null, null);
+
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductReservationTest()
+ {
+ //Arrange
+ var p = new ProductReservation { ProductId = "1" };
+ //Act
+ await _service.InsertProductReservation(p);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task UpdateProductReservationTest()
+ {
+ //Arrange
+ var p = new ProductReservation { ProductId = "1" };
+ await _repository.InsertAsync(p);
+ //Act
+ p.ProductId = "2";
+ await _service.UpdateProductReservation(p);
+
+ Assert.AreEqual("2", _repository.Table.FirstOrDefault().ProductId);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductReservationTest()
+ {
+ //Arrange
+ var p = new ProductReservation { ProductId = "1" };
+ await _repository.InsertAsync(p);
+ //Act
+ await _service.DeleteProductReservation(p);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetProductReservationTest()
+ {
+ //Arrange
+ var p = new ProductReservation { ProductId = "1" };
+ await _repository.InsertAsync(p);
+ //Act
+ var result = await _service.GetProductReservation(p.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.ProductId);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerReservationsHelperTest()
{
+ //Arrange
+ var p = new CustomerReservationsHelper();
+ //Act
+ await _service.InsertCustomerReservationsHelper(p);
+ //Assert
+ Assert.AreEqual(1, _repositoryCustomerReservationsHelper.Table.Count());
+ }
- ProductReservationService _service;
- private IRepository<ProductReservation> _repository;
- private IRepository<CustomerReservationsHelper> _repositoryCustomerReservationsHelper;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<ProductReservation>();
- _repositoryCustomerReservationsHelper = new MongoDBRepositoryTest<CustomerReservationsHelper>();
- _mediatorMock = new Mock<IMediator>();
-
- _service = new ProductReservationService(_repository, _repositoryCustomerReservationsHelper, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetProductReservationsByProductIdTest()
- {
- //Arrange
- await _repository.InsertAsync(new ProductReservation { ProductId = "1" });
- await _repository.InsertAsync(new ProductReservation { ProductId = "1" });
- await _repository.InsertAsync(new ProductReservation { ProductId = "2" });
- //Act
- var result = await _service.GetProductReservationsByProductId("1", null, null);
-
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductReservationTest()
- {
- //Arrange
- var p = new ProductReservation { ProductId = "1" };
- //Act
- await _service.InsertProductReservation(p);
- //Assert
- Assert.AreEqual(1, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task UpdateProductReservationTest()
- {
- //Arrange
- var p = new ProductReservation { ProductId = "1" };
- await _repository.InsertAsync(p);
- //Act
- p.ProductId = "2";
- await _service.UpdateProductReservation(p);
-
- Assert.AreEqual("2", _repository.Table.FirstOrDefault().ProductId);
- }
-
- [TestMethod()]
- public async Task DeleteProductReservationTest()
- {
- //Arrange
- var p = new ProductReservation { ProductId = "1" };
- await _repository.InsertAsync(p);
- //Act
- await _service.DeleteProductReservation(p);
- //Assert
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetProductReservationTest()
- {
- //Arrange
- var p = new ProductReservation { ProductId = "1" };
- await _repository.InsertAsync(p);
- //Act
- var result = await _service.GetProductReservation(p.Id);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.ProductId);
- }
-
- [TestMethod()]
- public async Task InsertCustomerReservationsHelperTest()
- {
- //Arrange
- var p = new CustomerReservationsHelper();
- //Act
- await _service.InsertCustomerReservationsHelper(p);
- //Assert
- Assert.AreEqual(1, _repositoryCustomerReservationsHelper.Table.Count());
- }
-
- [TestMethod()]
- public async Task DeleteCustomerReservationsHelperTest()
- {
- //Arrange
- var p = new CustomerReservationsHelper();
- await _repositoryCustomerReservationsHelper.InsertAsync(p);
- //Act
- await _service.DeleteCustomerReservationsHelper(p);
- //Assert
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task CancelReservationsByOrderIdTest()
- {
- //Arrange
- await _repository.InsertAsync(new ProductReservation { OrderId = "1" });
- await _repository.InsertAsync(new ProductReservation { OrderId = "2" });
- //Act
- await _service.CancelReservationsByOrderId("1");
- //Assert
- Assert.AreEqual(0, _repository.Table.Where(x=>x.OrderId == "1").Count());
- }
-
- [TestMethod()]
- public async Task GetCustomerReservationsHelperByIdTest()
- {
- //Arrange
- var p = new CustomerReservationsHelper { CustomerId = "1" };
- await _repositoryCustomerReservationsHelper.InsertAsync(p);
- //Act
- var result = await _service.GetCustomerReservationsHelperById(p.Id);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.CustomerId);
- }
-
- [TestMethod()]
- public async Task GetCustomerReservationsHelpersTest()
- {
- //Arrange
- await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "1" });
- await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "1" });
- await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "2" });
- //Act
- var result = await _service.GetCustomerReservationsHelpers("1");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task GetCustomerReservationsHelperBySciIdTest()
- {
- //Arrange
- await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { ShoppingCartItemId = "1" });
- await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { ShoppingCartItemId = "1" });
- await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "2" });
- //Act
- var result = await _service.GetCustomerReservationsHelperBySciId("1");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(2, result.Count);
- }
+ [TestMethod]
+ public async Task DeleteCustomerReservationsHelperTest()
+ {
+ //Arrange
+ var p = new CustomerReservationsHelper();
+ await _repositoryCustomerReservationsHelper.InsertAsync(p);
+ //Act
+ await _service.DeleteCustomerReservationsHelper(p);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task CancelReservationsByOrderIdTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new ProductReservation { OrderId = "1" });
+ await _repository.InsertAsync(new ProductReservation { OrderId = "2" });
+ //Act
+ await _service.CancelReservationsByOrderId("1");
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Where(x => x.OrderId == "1").Count());
+ }
+
+ [TestMethod]
+ public async Task GetCustomerReservationsHelperByIdTest()
+ {
+ //Arrange
+ var p = new CustomerReservationsHelper { CustomerId = "1" };
+ await _repositoryCustomerReservationsHelper.InsertAsync(p);
+ //Act
+ var result = await _service.GetCustomerReservationsHelperById(p.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.CustomerId);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerReservationsHelpersTest()
+ {
+ //Arrange
+ await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "1" });
+ await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "1" });
+ await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "2" });
+ //Act
+ var result = await _service.GetCustomerReservationsHelpers("1");
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerReservationsHelperBySciIdTest()
+ {
+ //Arrange
+ await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper
+ { ShoppingCartItemId = "1" });
+ await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper
+ { ShoppingCartItemId = "1" });
+ await _repositoryCustomerReservationsHelper.InsertAsync(new CustomerReservationsHelper { CustomerId = "2" });
+ //Act
+ var result = await _service.GetCustomerReservationsHelperBySciId("1");
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2, result.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReviewServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReviewServiceTests.cs
index ccd54c12c..e6da3d11d 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReviewServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductReviewServiceTests.cs
@@ -1,103 +1,102 @@
using Grand.Business.Catalog.Services.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductReviewServiceTests
{
- [TestClass()]
- public class ProductReviewServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private ProductReviewService _productReviewService;
+ private IRepository<ProductReview> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<ProductReview>();
+ _mediatorMock = new Mock<IMediator>();
+ _productReviewService = new ProductReviewService(_repository, _mediatorMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task GetAllProductReviewsTest()
+ {
+ //Arrange
+
+ await _repository.InsertAsync(new ProductReview { CustomerId = "1" });
+ await _repository.InsertAsync(new ProductReview { CustomerId = "1" });
+ await _repository.InsertAsync(new ProductReview());
+ await _repository.InsertAsync(new ProductReview());
+
+ //Act
+ var result = await _productReviewService.GetAllProductReviews("1", null);
+
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductReviewTest()
{
- private IRepository<ProductReview> _repository;
- private Mock<IMediator> _mediatorMock;
- private ProductReviewService _productReviewService;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<ProductReview>();
- _mediatorMock = new Mock<IMediator>();
- _productReviewService = new ProductReviewService(_repository, _mediatorMock.Object);
- }
-
-
- [TestMethod()]
- public async Task GetAllProductReviewsTest()
- {
- //Arrange
-
- await _repository.InsertAsync(new ProductReview { CustomerId = "1" });
- await _repository.InsertAsync(new ProductReview { CustomerId = "1"});
- await _repository.InsertAsync(new ProductReview { });
- await _repository.InsertAsync(new ProductReview { });
-
- //Act
- var result = await _productReviewService.GetAllProductReviews("1", null);
-
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductReviewTest()
- {
- //Act
- await _productReviewService.InsertProductReview(new ProductReview());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateProductReviewTest()
- {
- //Arrange
- var productReview = new ProductReview {
- ReviewText = "test"
- };
- await _productReviewService.InsertProductReview(productReview);
- productReview.ReviewText = "test2";
-
- //Act
- await _productReviewService.UpdateProductReview(productReview);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.ReviewText == "test2"));
- }
-
- [TestMethod()]
- public async Task DeleteProductReviewTest()
- {
- //Arrange
- var productReview = new ProductReview {
- ReviewText = "test"
- };
- await _productReviewService.InsertProductReview(productReview);
- //Act
- await _productReviewService.DeleteProductReview(productReview);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.ReviewText == "test"));
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetProductReviewByIdTest()
- {
- //Arrange
- var productReview = new ProductReview {
- ReviewText = "test"
- };
- await _productReviewService.InsertProductReview(productReview);
-
- //Act
- var result = await _productReviewService.GetProductReviewById(productReview.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.ReviewText);
- }
+ //Act
+ await _productReviewService.InsertProductReview(new ProductReview());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateProductReviewTest()
+ {
+ //Arrange
+ var productReview = new ProductReview {
+ ReviewText = "test"
+ };
+ await _productReviewService.InsertProductReview(productReview);
+ productReview.ReviewText = "test2";
+
+ //Act
+ await _productReviewService.UpdateProductReview(productReview);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.ReviewText == "test2"));
+ }
+
+ [TestMethod]
+ public async Task DeleteProductReviewTest()
+ {
+ //Arrange
+ var productReview = new ProductReview {
+ ReviewText = "test"
+ };
+ await _productReviewService.InsertProductReview(productReview);
+ //Act
+ await _productReviewService.DeleteProductReview(productReview);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.ReviewText == "test"));
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetProductReviewByIdTest()
+ {
+ //Arrange
+ var productReview = new ProductReview {
+ ReviewText = "test"
+ };
+ await _productReviewService.InsertProductReview(productReview);
+
+ //Act
+ var result = await _productReviewService.GetProductReviewById(productReview.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.ReviewText);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs
index 2655cffb4..4c80992c3 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductServiceTests.cs
@@ -2,11 +2,12 @@
using Grand.Business.Common.Services.Security;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Queries.Catalog;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Orders;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -16,839 +17,852 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductServiceTests
{
- [TestClass()]
- public class ProductServiceTests
- {
- private IRepository<Product> _productRepository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private IAclService _aclServiceMock;
- private MemoryCacheBase _cacheBase;
- private ProductService _productService;
-
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
-
- _productRepository = new MongoDBRepositoryTest<Product>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _mediatorMock = new Mock<IMediator>();
-
- _mediatorMock.Setup(x => x.Send(It.IsAny<GetProductArchByIdQuery>(), default))
- .Returns(Task.FromResult(new Product()));
-
- _aclServiceMock = new AclService(new AccessControlConfig());
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _productService = new ProductService(_cacheBase, _productRepository, _workContextMock.Object, _mediatorMock.Object, _aclServiceMock);
- }
-
- private async Task insertSampleProducts()
- {
- await _productRepository.InsertAsync(new Product { Id = "1", Published = true, VisibleIndividually = true, ShowOnHomePage = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true, ShowOnHomePage = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true, BestSeller = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true, BestSeller = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true, Sku = "test123" });
- await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true, ParentGroupedProductId = "1" });
-
- var product = new Product { Published = true, VisibleIndividually = true };
- product.AppliedDiscounts.Add("1");
- product.ProductCategories.Add(new ProductCategory { CategoryId = "1" });
- product.ProductAttributeMappings.Add(new ProductAttributeMapping { ProductAttributeId = "1" });
- await _productRepository.InsertAsync(product);
-
- }
-
- [TestMethod()]
- public async Task GetAllProductsDisplayedOnHomePageTest()
- {
- //Arrange
- await insertSampleProducts();
-
- //Act
- var result = await _productService.GetAllProductsDisplayedOnHomePage();
-
- //Assert
- Assert.IsTrue(result.Count == 2);
- }
-
- [TestMethod()]
- public async Task GetAllProductsDisplayedOnBestSellerTest()
- {
- //Arrange
- await insertSampleProducts();
-
- //Act
- var result = await _productService.GetAllProductsDisplayedOnBestSeller();
-
- //Assert
- Assert.IsTrue(result.Count == 2);
- }
-
- [TestMethod()]
- public async Task GetProductByIdTest_NotNull()
- {
- //Arrange
- await insertSampleProducts();
-
- //Act
- var result = await _productService.GetProductById("1");
-
- //Assert
- Assert.IsNotNull(result);
- }
- [TestMethod()]
- public async Task GetProductByIdTest_Null()
- {
- //Arrange
- await insertSampleProducts();
-
- //Act
- var result = await _productService.GetProductById("x");
-
- //Assert
- Assert.IsNull(result);
- }
- [TestMethod()]
- public async Task GetProductByIdIncludeArchTest()
- {
- //Act
- var result = await _productService.GetProductByIdIncludeArch("2");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetProductsByIdsTest()
- {
- await insertSampleProducts();
- //Act
- var result = await _productService.GetProductsByIds(["1"]);
-
- //Assert
- Assert.IsTrue(result.Count > 0);
- }
-
- [TestMethod()]
- public async Task GetProductsByDiscountTest()
- {
- //Arrange
- await insertSampleProducts();
-
- //Act
- var result = await _productService.GetProductsByDiscount("1");
-
- //Assert
- Assert.IsTrue(result.Count > 0);
- }
-
- [TestMethod()]
- public async Task InsertProductTest()
- {
- //Arrange
- var product = new Product { Id = "1" };
- await _productService.InsertProduct(product);
-
- //Act
- var result = await _productService.GetProductById("1");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task UpdateProductTest()
- {
- //Arrange
- var product = new Product { Id = "103", Name = "test" };
- await _productService.InsertProduct(product);
-
- //Act
- product.Name = "test2";
- await _productService.UpdateProduct(product);
- var result = await _productService.GetProductById("103");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.IsTrue(result.Name == "test2");
- }
-
- [TestMethod()]
- public async Task DeleteProductTest()
- {
- //Arrange
- var product = new Product { Id = "1" };
- await _productService.InsertProduct(product);
-
- //Act
- await _productService.DeleteProduct(product);
- var result = await _productService.GetProductById("1", true);
-
- //Assert
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task UnPublishProductTest()
- {
- //Arrange
- var product = new Product { Id = "100", Published = true };
- await _productService.InsertProduct(product);
-
- //Act
- await _productService.UnPublishProduct(product);
- var result = await _productService.GetProductById("100");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.IsFalse(result.Published);
- }
-
- [TestMethod()]
- public async Task GetCategoryProductNumberTest()
- {
- //Arrange
- await insertSampleProducts();
- //Act
- var result = _productService.GetCategoryProductNumber(new Customer(), new[] { "1" });
-
- //Assert
- Assert.IsTrue(result == 1);
- }
- [TestMethod()]
- [Ignore]
- public void SearchProductsTest()
- {
- }
-
- [TestMethod()]
- public async Task GetProductsByProductAtributeIdTest()
- {
- //Arrange
- await insertSampleProducts();
- //Act
- var result = await _productService.GetProductsByProductAttributeId("1");
-
- //Assert
- Assert.IsTrue(result.Count > 0);
- }
-
- [TestMethod()]
- public async Task GetAssociatedProductsTest()
- {
- //Arrange
- await insertSampleProducts();
- //Act
- var result = await _productService.GetAssociatedProducts("1");
-
- //Assert
- Assert.IsTrue(result.Count > 0);
- }
-
- [TestMethod()]
- public async Task GetProductBySkuTest()
- {
- //Arrange
- await insertSampleProducts();
- //Act
- var result = await _productService.GetProductBySku("test123");
-
- //Assert
- Assert.IsNotNull(result);
- }
- [TestMethod()]
- public async Task UpdateProductFieldTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- //Act
- await _productService.UpdateProductField(product, x => x.Name, "test");
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task IncrementProductFieldTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- //Act
- await _productService.IncrementProductField(product, x => x.Viewed, 1);
- await _productService.IncrementProductField(product, x => x.Viewed, 1);
- await _productService.IncrementProductField(product, x => x.Viewed, 1);
-
- var result = await _productService.GetProductById(product.Id, true);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(3, result.Viewed);
- }
- [TestMethod()]
- public async Task UpdateAssociatedProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- //Act
- product.ParentGroupedProductId = "2";
- await _productService.UpdateAssociatedProduct(product);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("2", result.ParentGroupedProductId);
- }
-
- [TestMethod()]
- public async Task InsertRelatedProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- //Act
- await _productService.InsertRelatedProduct(new RelatedProduct { ProductId2 = "2" }, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.RelatedProducts.Count);
- }
-
- [TestMethod()]
- public async Task DeleteRelatedProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var relatedproducts = new RelatedProduct { ProductId2 = "2" };
- await _productService.InsertRelatedProduct(relatedproducts, product.Id);
-
- //Act
- await _productService.DeleteRelatedProduct(relatedproducts, product.Id);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.RelatedProducts.Count);
- }
-
- [TestMethod()]
- public async Task UpdateRelatedProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var relatedproducts = new RelatedProduct { ProductId2 = "2" };
- await _productService.InsertRelatedProduct(relatedproducts, product.Id);
-
- //Act
- relatedproducts.DisplayOrder = 10;
- await _productService.UpdateRelatedProduct(relatedproducts, product.Id);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.RelatedProducts.Count);
- Assert.AreEqual(10, result.RelatedProducts.FirstOrDefault().DisplayOrder);
- }
-
- [TestMethod()]
- public async Task InsertSimilarProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- //Act
- await _productService.InsertSimilarProduct(new SimilarProduct {
- ProductId1 = product.Id,
- ProductId2 = "2"
- });
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.SimilarProducts.Count);
- }
-
- [TestMethod()]
- public async Task UpdateSimilarProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var similarProduct = new SimilarProduct { ProductId1 = product.Id, ProductId2 = "2" };
- await _productService.InsertSimilarProduct(similarProduct);
-
- //Act
- similarProduct.DisplayOrder = 10;
- await _productService.UpdateSimilarProduct(similarProduct);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.SimilarProducts.Count);
- Assert.AreEqual(10, result.SimilarProducts.FirstOrDefault().DisplayOrder);
- }
-
- [TestMethod()]
- public async Task DeleteSimilarProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var similarProduct = new SimilarProduct { ProductId1 = product.Id, ProductId2 = "2" };
- await _productService.InsertSimilarProduct(similarProduct);
-
- //Act
- await _productService.DeleteSimilarProduct(similarProduct);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.SimilarProducts.Count);
- }
-
- [TestMethod()]
- public async Task InsertBundleProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- //Act
- await _productService.InsertBundleProduct(new BundleProduct {
- ProductId = "2"
- }, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.BundleProducts.Count);
- }
-
- [TestMethod()]
- public async Task UpdateBundleProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var bundleProduct = new BundleProduct { ProductId = "2" };
- await _productService.InsertBundleProduct(bundleProduct, product.Id);
-
- //Act
- bundleProduct.Quantity = 10;
- await _productService.UpdateBundleProduct(bundleProduct, product.Id);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.BundleProducts.Count);
- Assert.AreEqual(10, result.BundleProducts.FirstOrDefault().Quantity);
- }
-
- [TestMethod()]
- public async Task DeleteBundleProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var bundleProduct = new BundleProduct { ProductId = "2" };
- await _productService.InsertBundleProduct(bundleProduct, product.Id);
-
- //Act
- await _productService.DeleteBundleProduct(bundleProduct, product.Id);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.BundleProducts.Count);
- }
-
- [TestMethod()]
- public async Task InsertCrossSellProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
-
- //Act
- await _productService.InsertCrossSellProduct(new CrossSellProduct {
- ProductId1 = product.Id,
- ProductId2 = "2"
- });
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.CrossSellProduct.Count);
- }
-
- [TestMethod()]
- public async Task DeleteCrossSellProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var crossSellProduct = new CrossSellProduct {
- ProductId1 = product.Id,
- ProductId2 = "2"
- };
- await _productService.InsertCrossSellProduct(crossSellProduct);
-
- //Act
- await _productService.DeleteCrossSellProduct(crossSellProduct);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.CrossSellProduct.Count);
- }
-
- [TestMethod()]
- public async Task GetCrossSellProductsByShoppingCartTest()
- {
- //Arrange
- var product = new Product { Published = true, VisibleIndividually = true };
- await _productService.InsertProduct(product);
- var product2 = new Product { Published = true, VisibleIndividually = true };
- await _productService.InsertProduct(product2);
- var product3 = new Product { Published = true, VisibleIndividually = true };
- await _productService.InsertProduct(product3);
- //Act
- await _productService.InsertCrossSellProduct(new CrossSellProduct {
- ProductId1 = product.Id,
- ProductId2 = product2.Id
- });
- //Act
- await _productService.InsertCrossSellProduct(new CrossSellProduct {
- ProductId1 = product.Id,
- ProductId2 = product3.Id
- });
-
- var result = await _productService.GetCrossSellProductsByShoppingCart(new List<ShoppingCartItem> { new ShoppingCartItem { ProductId = product.Id } }, 2);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task InsertRecommendedProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
-
- //Act
- await _productService.InsertRecommendedProduct(product.Id, "2");
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.RecommendedProduct.Count);
- }
-
- [TestMethod()]
- public async Task DeleteRecommendedProductTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- await _productService.InsertRecommendedProduct(product.Id, "2");
-
- //Act
- await _productService.DeleteRecommendedProduct(product.Id, "2");
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.AreEqual(0, result.RecommendedProduct.Count);
- }
-
- [TestMethod()]
- public async Task InsertTierPriceTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
-
- //Act
- await _productService.InsertTierPrice(new TierPrice { Price = 10, Quantity = 1 }, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.TierPrices.Count);
- }
-
- [TestMethod()]
- public async Task UpdateTierPriceTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var tierprice = new TierPrice { Price = 10, Quantity = 1 };
- await _productService.InsertTierPrice(tierprice, product.Id);
-
- //Act
- tierprice.Quantity = 10;
- await _productService.UpdateTierPrice(tierprice, product.Id);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.TierPrices.Count);
- Assert.AreEqual(10, result.TierPrices.FirstOrDefault().Quantity);
- }
-
- [TestMethod()]
- public async Task DeleteTierPriceTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var tierprice = new TierPrice { Price = 10, Quantity = 1 };
- await _productService.InsertTierPrice(tierprice, product.Id);
-
- //Act
- await _productService.DeleteTierPrice(tierprice, product.Id);
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.TierPrices.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductPriceTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productPrice = new ProductPrice { Price = 10, CurrencyCode = "USD", ProductId = product.Id };
-
- //Act
- await _productService.InsertProductPrice(productPrice);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.ProductPrices.Count);
- }
-
- [TestMethod()]
- public async Task UpdateProductPriceTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productPrice = new ProductPrice { Price = 10, CurrencyCode = "USD", ProductId = product.Id };
- await _productService.InsertProductPrice(productPrice);
-
- //Act
- productPrice.CurrencyCode = "EUR";
- await _productService.UpdateProductPrice(productPrice);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.ProductPrices.Count);
- Assert.AreEqual("EUR", result.ProductPrices.FirstOrDefault().CurrencyCode);
- }
-
- [TestMethod()]
- public async Task DeleteProductPriceTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productPrice = new ProductPrice { Price = 10, CurrencyCode = "USD", ProductId = product.Id };
- await _productService.InsertProductPrice(productPrice);
-
- //Act
- await _productService.DeleteProductPrice(productPrice);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.ProductPrices.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductPictureTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productPicture = new ProductPicture { PictureId = "1" };
-
- //Act
- await _productService.InsertProductPicture(productPicture, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.ProductPictures.Count);
- }
-
- [TestMethod()]
- public async Task UpdateProductPictureTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productPicture = new ProductPicture { PictureId = "1" };
- await _productService.InsertProductPicture(productPicture, product.Id);
-
- //Act
- productPicture.PictureId = "2";
- await _productService.UpdateProductPicture(productPicture, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.ProductPictures.Count);
- Assert.AreEqual("2", result.ProductPictures.FirstOrDefault().PictureId);
- }
-
- [TestMethod()]
- public async Task DeleteProductPictureTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productPicture = new ProductPicture { PictureId = "1" };
- await _productService.InsertProductPicture(productPicture, product.Id);
-
- //Act
- await _productService.DeleteProductPicture(productPicture, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.ProductPictures.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductWarehouseInventoryTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productWarehouseInventory = new ProductWarehouseInventory { WarehouseId = "1" };
-
- //Act
- await _productService.InsertProductWarehouseInventory(productWarehouseInventory, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.ProductWarehouseInventory.Count);
- }
-
- [TestMethod()]
- public async Task UpdateProductWarehouseInventoryTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productWarehouseInventory = new ProductWarehouseInventory { WarehouseId = "1" };
- await _productService.InsertProductWarehouseInventory(productWarehouseInventory, product.Id);
-
- //Act
- productWarehouseInventory.WarehouseId = "2";
- await _productService.UpdateProductWarehouseInventory(productWarehouseInventory, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.ProductWarehouseInventory.Count);
- Assert.AreEqual("2", result.ProductWarehouseInventory.FirstOrDefault().WarehouseId);
- }
-
- [TestMethod()]
- public async Task DeleteProductWarehouseInventoryTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- var productWarehouseInventory = new ProductWarehouseInventory { WarehouseId = "1" };
- await _productService.InsertProductWarehouseInventory(productWarehouseInventory, product.Id);
-
- //Act
- await _productService.DeleteProductWarehouseInventory(productWarehouseInventory, product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.ProductWarehouseInventory.Count);
- }
-
- [TestMethod()]
- public async Task DeleteDiscountTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
- await _productService.InsertDiscount("1", product.Id);
-
- //Act
- await _productService.DeleteDiscount("1", product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(0, result.AppliedDiscounts.Count);
- }
-
- [TestMethod()]
- public async Task InsertDiscountTest()
- {
- //Arrange
- var product = new Product();
- await _productService.InsertProduct(product);
-
- //Act
- await _productService.InsertDiscount("1", product.Id);
-
- var result = await _productService.GetProductById(product.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.AppliedDiscounts.Count);
- }
+ private IAclService _aclServiceMock;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Product> _productRepository;
+ private ProductService _productService;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _productRepository = new MongoDBRepositoryTest<Product>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _mediatorMock = new Mock<IMediator>();
+
+ _mediatorMock.Setup(x => x.Send(It.IsAny<GetProductArchByIdQuery>(), default))
+ .Returns(Task.FromResult(new Product()));
+
+ _aclServiceMock = new AclService(new AccessControlConfig());
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _productService = new ProductService(_cacheBase, _productRepository, _workContextMock.Object,
+ _mediatorMock.Object, _aclServiceMock);
+ }
+
+ private async Task insertSampleProducts()
+ {
+ await _productRepository.InsertAsync(new Product
+ { Id = "1", Published = true, VisibleIndividually = true, ShowOnHomePage = true });
+ await _productRepository.InsertAsync(new Product
+ { Published = true, VisibleIndividually = true, ShowOnHomePage = true });
+ await _productRepository.InsertAsync(new Product
+ { Published = true, VisibleIndividually = true, BestSeller = true });
+ await _productRepository.InsertAsync(new Product
+ { Published = true, VisibleIndividually = true, BestSeller = true });
+ await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
+ await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
+ await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
+ await _productRepository.InsertAsync(new Product { Published = true, VisibleIndividually = true });
+ await _productRepository.InsertAsync(new Product
+ { Published = true, VisibleIndividually = true, Sku = "test123" });
+ await _productRepository.InsertAsync(new Product
+ { Published = true, VisibleIndividually = true, ParentGroupedProductId = "1" });
+
+ var product = new Product { Published = true, VisibleIndividually = true };
+ product.AppliedDiscounts.Add("1");
+ product.ProductCategories.Add(new ProductCategory { CategoryId = "1" });
+ product.ProductAttributeMappings.Add(new ProductAttributeMapping { ProductAttributeId = "1" });
+ await _productRepository.InsertAsync(product);
+ }
+
+ [TestMethod]
+ public async Task GetAllProductsDisplayedOnHomePageTest()
+ {
+ //Arrange
+ await insertSampleProducts();
+
+ //Act
+ var result = await _productService.GetAllProductsDisplayedOnHomePage();
+
+ //Assert
+ Assert.IsTrue(result.Count == 2);
+ }
+
+ [TestMethod]
+ public async Task GetAllProductsDisplayedOnBestSellerTest()
+ {
+ //Arrange
+ await insertSampleProducts();
+
+ //Act
+ var result = await _productService.GetAllProductsDisplayedOnBestSeller();
+
+ //Assert
+ Assert.IsTrue(result.Count == 2);
+ }
+
+ [TestMethod]
+ public async Task GetProductByIdTest_NotNull()
+ {
+ //Arrange
+ await insertSampleProducts();
+
+ //Act
+ var result = await _productService.GetProductById("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetProductByIdTest_Null()
+ {
+ //Arrange
+ await insertSampleProducts();
+
+ //Act
+ var result = await _productService.GetProductById("x");
+
+ //Assert
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetProductByIdIncludeArchTest()
+ {
+ //Act
+ var result = await _productService.GetProductByIdIncludeArch("2");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetProductsByIdsTest()
+ {
+ await insertSampleProducts();
+ //Act
+ var result = await _productService.GetProductsByIds(["1"]);
+
+ //Assert
+ Assert.IsTrue(result.Count > 0);
+ }
+
+ [TestMethod]
+ public async Task GetProductsByDiscountTest()
+ {
+ //Arrange
+ await insertSampleProducts();
+
+ //Act
+ var result = await _productService.GetProductsByDiscount("1");
+
+ //Assert
+ Assert.IsTrue(result.Count > 0);
+ }
+
+ [TestMethod]
+ public async Task InsertProductTest()
+ {
+ //Arrange
+ var product = new Product { Id = "1" };
+ await _productService.InsertProduct(product);
+
+ //Act
+ var result = await _productService.GetProductById("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductTest()
+ {
+ //Arrange
+ var product = new Product { Id = "103", Name = "test" };
+ await _productService.InsertProduct(product);
+
+ //Act
+ product.Name = "test2";
+ await _productService.UpdateProduct(product);
+ var result = await _productService.GetProductById("103");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.IsTrue(result.Name == "test2");
+ }
+
+ [TestMethod]
+ public async Task DeleteProductTest()
+ {
+ //Arrange
+ var product = new Product { Id = "1" };
+ await _productService.InsertProduct(product);
+
+ //Act
+ await _productService.DeleteProduct(product);
+ var result = await _productService.GetProductById("1", true);
+
+ //Assert
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task UnPublishProductTest()
+ {
+ //Arrange
+ var product = new Product { Id = "100", Published = true };
+ await _productService.InsertProduct(product);
+
+ //Act
+ await _productService.UnPublishProduct(product);
+ var result = await _productService.GetProductById("100");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.IsFalse(result.Published);
+ }
+
+ [TestMethod]
+ public async Task GetCategoryProductNumberTest()
+ {
+ //Arrange
+ await insertSampleProducts();
+ //Act
+ var result = _productService.GetCategoryProductNumber(new Customer(), new[] { "1" });
+
+ //Assert
+ Assert.IsTrue(result == 1);
+ }
+
+ [TestMethod]
+ [Ignore]
+ public void SearchProductsTest()
+ {
+ }
+
+ [TestMethod]
+ public async Task GetProductsByProductAtributeIdTest()
+ {
+ //Arrange
+ await insertSampleProducts();
+ //Act
+ var result = await _productService.GetProductsByProductAttributeId("1");
+
+ //Assert
+ Assert.IsTrue(result.Count > 0);
+ }
+
+ [TestMethod]
+ public async Task GetAssociatedProductsTest()
+ {
+ //Arrange
+ await insertSampleProducts();
+ //Act
+ var result = await _productService.GetAssociatedProducts("1");
+
+ //Assert
+ Assert.IsTrue(result.Count > 0);
+ }
+
+ [TestMethod]
+ public async Task GetProductBySkuTest()
+ {
+ //Arrange
+ await insertSampleProducts();
+ //Act
+ var result = await _productService.GetProductBySku("test123");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductFieldTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ //Act
+ await _productService.UpdateProductField(product, x => x.Name, "test");
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task IncrementProductFieldTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ //Act
+ await _productService.IncrementProductField(product, x => x.Viewed, 1);
+ await _productService.IncrementProductField(product, x => x.Viewed, 1);
+ await _productService.IncrementProductField(product, x => x.Viewed, 1);
+
+ var result = await _productService.GetProductById(product.Id, true);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(3, result.Viewed);
+ }
+
+ [TestMethod]
+ public async Task UpdateAssociatedProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ //Act
+ product.ParentGroupedProductId = "2";
+ await _productService.UpdateAssociatedProduct(product);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("2", result.ParentGroupedProductId);
+ }
+
+ [TestMethod]
+ public async Task InsertRelatedProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ //Act
+ await _productService.InsertRelatedProduct(new RelatedProduct { ProductId2 = "2" }, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.RelatedProducts.Count);
+ }
+
+ [TestMethod]
+ public async Task DeleteRelatedProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var relatedproducts = new RelatedProduct { ProductId2 = "2" };
+ await _productService.InsertRelatedProduct(relatedproducts, product.Id);
+
+ //Act
+ await _productService.DeleteRelatedProduct(relatedproducts, product.Id);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.RelatedProducts.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateRelatedProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var relatedproducts = new RelatedProduct { ProductId2 = "2" };
+ await _productService.InsertRelatedProduct(relatedproducts, product.Id);
+
+ //Act
+ relatedproducts.DisplayOrder = 10;
+ await _productService.UpdateRelatedProduct(relatedproducts, product.Id);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.RelatedProducts.Count);
+ Assert.AreEqual(10, result.RelatedProducts.FirstOrDefault().DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task InsertSimilarProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ //Act
+ await _productService.InsertSimilarProduct(new SimilarProduct {
+ ProductId1 = product.Id,
+ ProductId2 = "2"
+ });
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.SimilarProducts.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateSimilarProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var similarProduct = new SimilarProduct { ProductId1 = product.Id, ProductId2 = "2" };
+ await _productService.InsertSimilarProduct(similarProduct);
+
+ //Act
+ similarProduct.DisplayOrder = 10;
+ await _productService.UpdateSimilarProduct(similarProduct);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.SimilarProducts.Count);
+ Assert.AreEqual(10, result.SimilarProducts.FirstOrDefault().DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task DeleteSimilarProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var similarProduct = new SimilarProduct { ProductId1 = product.Id, ProductId2 = "2" };
+ await _productService.InsertSimilarProduct(similarProduct);
+
+ //Act
+ await _productService.DeleteSimilarProduct(similarProduct);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.SimilarProducts.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertBundleProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ //Act
+ await _productService.InsertBundleProduct(new BundleProduct {
+ ProductId = "2"
+ }, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.BundleProducts.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateBundleProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var bundleProduct = new BundleProduct { ProductId = "2" };
+ await _productService.InsertBundleProduct(bundleProduct, product.Id);
+
+ //Act
+ bundleProduct.Quantity = 10;
+ await _productService.UpdateBundleProduct(bundleProduct, product.Id);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.BundleProducts.Count);
+ Assert.AreEqual(10, result.BundleProducts.FirstOrDefault().Quantity);
+ }
+
+ [TestMethod]
+ public async Task DeleteBundleProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var bundleProduct = new BundleProduct { ProductId = "2" };
+ await _productService.InsertBundleProduct(bundleProduct, product.Id);
+
+ //Act
+ await _productService.DeleteBundleProduct(bundleProduct, product.Id);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.BundleProducts.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertCrossSellProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+
+ //Act
+ await _productService.InsertCrossSellProduct(new CrossSellProduct {
+ ProductId1 = product.Id,
+ ProductId2 = "2"
+ });
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.CrossSellProduct.Count);
+ }
+
+ [TestMethod]
+ public async Task DeleteCrossSellProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var crossSellProduct = new CrossSellProduct {
+ ProductId1 = product.Id,
+ ProductId2 = "2"
+ };
+ await _productService.InsertCrossSellProduct(crossSellProduct);
+
+ //Act
+ await _productService.DeleteCrossSellProduct(crossSellProduct);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.CrossSellProduct.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCrossSellProductsByShoppingCartTest()
+ {
+ //Arrange
+ var product = new Product { Published = true, VisibleIndividually = true };
+ await _productService.InsertProduct(product);
+ var product2 = new Product { Published = true, VisibleIndividually = true };
+ await _productService.InsertProduct(product2);
+ var product3 = new Product { Published = true, VisibleIndividually = true };
+ await _productService.InsertProduct(product3);
+ //Act
+ await _productService.InsertCrossSellProduct(new CrossSellProduct {
+ ProductId1 = product.Id,
+ ProductId2 = product2.Id
+ });
+ //Act
+ await _productService.InsertCrossSellProduct(new CrossSellProduct {
+ ProductId1 = product.Id,
+ ProductId2 = product3.Id
+ });
+
+ var result =
+ await _productService.GetCrossSellProductsByShoppingCart(
+ new List<ShoppingCartItem> { new() { ProductId = product.Id } }, 2);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertRecommendedProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+
+ //Act
+ await _productService.InsertRecommendedProduct(product.Id, "2");
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.RecommendedProduct.Count);
+ }
+
+ [TestMethod]
+ public async Task DeleteRecommendedProductTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ await _productService.InsertRecommendedProduct(product.Id, "2");
+
+ //Act
+ await _productService.DeleteRecommendedProduct(product.Id, "2");
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.AreEqual(0, result.RecommendedProduct.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertTierPriceTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+
+ //Act
+ await _productService.InsertTierPrice(new TierPrice { Price = 10, Quantity = 1 }, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.TierPrices.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateTierPriceTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var tierprice = new TierPrice { Price = 10, Quantity = 1 };
+ await _productService.InsertTierPrice(tierprice, product.Id);
+
+ //Act
+ tierprice.Quantity = 10;
+ await _productService.UpdateTierPrice(tierprice, product.Id);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.TierPrices.Count);
+ Assert.AreEqual(10, result.TierPrices.FirstOrDefault().Quantity);
+ }
+
+ [TestMethod]
+ public async Task DeleteTierPriceTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var tierprice = new TierPrice { Price = 10, Quantity = 1 };
+ await _productService.InsertTierPrice(tierprice, product.Id);
+
+ //Act
+ await _productService.DeleteTierPrice(tierprice, product.Id);
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.TierPrices.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductPriceTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productPrice = new ProductPrice { Price = 10, CurrencyCode = "USD", ProductId = product.Id };
+
+ //Act
+ await _productService.InsertProductPrice(productPrice);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.ProductPrices.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductPriceTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productPrice = new ProductPrice { Price = 10, CurrencyCode = "USD", ProductId = product.Id };
+ await _productService.InsertProductPrice(productPrice);
+
+ //Act
+ productPrice.CurrencyCode = "EUR";
+ await _productService.UpdateProductPrice(productPrice);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.ProductPrices.Count);
+ Assert.AreEqual("EUR", result.ProductPrices.FirstOrDefault().CurrencyCode);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductPriceTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productPrice = new ProductPrice { Price = 10, CurrencyCode = "USD", ProductId = product.Id };
+ await _productService.InsertProductPrice(productPrice);
+
+ //Act
+ await _productService.DeleteProductPrice(productPrice);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.ProductPrices.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductPictureTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productPicture = new ProductPicture { PictureId = "1" };
+
+ //Act
+ await _productService.InsertProductPicture(productPicture, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.ProductPictures.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductPictureTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productPicture = new ProductPicture { PictureId = "1" };
+ await _productService.InsertProductPicture(productPicture, product.Id);
+
+ //Act
+ productPicture.PictureId = "2";
+ await _productService.UpdateProductPicture(productPicture, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.ProductPictures.Count);
+ Assert.AreEqual("2", result.ProductPictures.FirstOrDefault().PictureId);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductPictureTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productPicture = new ProductPicture { PictureId = "1" };
+ await _productService.InsertProductPicture(productPicture, product.Id);
+
+ //Act
+ await _productService.DeleteProductPicture(productPicture, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.ProductPictures.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductWarehouseInventoryTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productWarehouseInventory = new ProductWarehouseInventory { WarehouseId = "1" };
+
+ //Act
+ await _productService.InsertProductWarehouseInventory(productWarehouseInventory, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.ProductWarehouseInventory.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductWarehouseInventoryTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productWarehouseInventory = new ProductWarehouseInventory { WarehouseId = "1" };
+ await _productService.InsertProductWarehouseInventory(productWarehouseInventory, product.Id);
+
+ //Act
+ productWarehouseInventory.WarehouseId = "2";
+ await _productService.UpdateProductWarehouseInventory(productWarehouseInventory, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.ProductWarehouseInventory.Count);
+ Assert.AreEqual("2", result.ProductWarehouseInventory.FirstOrDefault().WarehouseId);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductWarehouseInventoryTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ var productWarehouseInventory = new ProductWarehouseInventory { WarehouseId = "1" };
+ await _productService.InsertProductWarehouseInventory(productWarehouseInventory, product.Id);
+
+ //Act
+ await _productService.DeleteProductWarehouseInventory(productWarehouseInventory, product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.ProductWarehouseInventory.Count);
+ }
+
+ [TestMethod]
+ public async Task DeleteDiscountTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+ await _productService.InsertDiscount("1", product.Id);
+
+ //Act
+ await _productService.DeleteDiscount("1", product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(0, result.AppliedDiscounts.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertDiscountTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _productService.InsertProduct(product);
+
+ //Act
+ await _productService.InsertDiscount("1", product.Id);
+
+ var result = await _productService.GetProductById(product.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.AppliedDiscounts.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductTagServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductTagServiceTests.cs
index 773daacb9..56fecd1e1 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductTagServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/ProductTagServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Catalog.Services.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -10,197 +10,197 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class ProductTagServiceTests
{
- [TestClass()]
- public class ProductTagServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Product> _productRepository;
+ private ProductTagService _productTagService;
+ private IRepository<ProductTag> _repositoryProductTag;
+
+ [TestInitialize]
+ public void InitializeTests()
+ {
+ CommonPath.BaseDirectory = "";
+
+ _repositoryProductTag = new MongoDBRepositoryTest<ProductTag>();
+ _productRepository = new MongoDBRepositoryTest<Product>();
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _productTagService =
+ new ProductTagService(_repositoryProductTag, _productRepository, _cacheBase, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetAllProductTagsTest()
+ {
+ //Arrange
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+
+ //Act
+ var result = await _productTagService.GetAllProductTags();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetProductTagByIdTest()
+ {
+ //Arrange
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+ await _repositoryProductTag.InsertAsync(new ProductTag { Id = "1", Name = "test" });
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+
+ //Act
+ var result = await _productTagService.GetProductTagById("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task GetProductTagByNameTest()
+ {
+ //Arrange
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+ await _repositoryProductTag.InsertAsync(new ProductTag { Id = "1", Name = "test" });
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+
+ //Act
+ var result = await _productTagService.GetProductTagByName("test");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.Id);
+ }
+
+ [TestMethod]
+ public async Task GetProductTagBySeNameTest()
+ {
+ //Arrange
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+ await _repositoryProductTag.InsertAsync(new ProductTag { Id = "1", Name = "test", SeName = "test" });
+ await _repositoryProductTag.InsertAsync(new ProductTag());
+
+ //Act
+ var result = await _productTagService.GetProductTagBySeName("test");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.Id);
+ }
+
+ [TestMethod]
+ public async Task InsertProductTagTest()
+ {
+ //Arrange
+ var productTag = new ProductTag {
+ Name = "test"
+ };
+ //Act
+ await _productTagService.InsertProductTag(productTag);
+ var result = await _productTagService.GetProductTagById(productTag.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductTagTest()
+ {
+ //Arrange
+ var productTag = new ProductTag {
+ Name = "test"
+ };
+ await _productTagService.InsertProductTag(productTag);
+ //Act
+ productTag.Name = "test2";
+ await _productTagService.UpdateProductTag(productTag);
+ var result = await _productTagService.GetProductTagById(productTag.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test2", result.Name);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductTagTest()
+ {
+ //Arrange
+ var productTag = new ProductTag {
+ Name = "test"
+ };
+ await _productTagService.InsertProductTag(productTag);
+
+ //Act
+ await _productTagService.DeleteProductTag(productTag);
+ var result = await _productTagService.GetProductTagById(productTag.Id);
+
+ //Assert
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task AttachProductTagTest()
+ {
+ //Arrange
+ var productTag = new ProductTag {
+ Name = "test"
+ };
+ await _productTagService.InsertProductTag(productTag);
+ var product = new Product();
+ await _productRepository.InsertAsync(product);
+
+ //Act
+ await _productTagService.AttachProductTag(productTag, product.Id);
+ var result = _productRepository.Table.FirstOrDefault(x => x.Id == product.Id);
+
+ //Assert
+ Assert.IsTrue(result.ProductTags.Any());
+ Assert.IsNotNull(result.ProductTags.FirstOrDefault(x => x == "test"));
+ }
+
+ [TestMethod]
+ public async Task DetachProductTagTest()
+ {
+ //Arrange
+ var productTag = new ProductTag {
+ Name = "test"
+ };
+ await _productTagService.InsertProductTag(productTag);
+ var product = new Product();
+ await _productRepository.InsertAsync(product);
+ await _productTagService.AttachProductTag(productTag, product.Id);
+
+ //Act
+ await _productTagService.DetachProductTag(productTag, product.Id);
+ var result = _productRepository.Table.FirstOrDefault(x => x.Id == product.Id);
+
+ //Assert
+ Assert.IsFalse(result.ProductTags.Any());
+ Assert.IsNull(result.ProductTags.FirstOrDefault(x => x == "test"));
+ }
+
+ [TestMethod]
+ public async Task GetProductCountTest()
{
- private IRepository<ProductTag> _repositoryProductTag;
- private IRepository<Product> _productRepository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
- private ProductTagService _productTagService;
-
- [TestInitialize()]
- public void InitializeTests()
- {
- CommonPath.BaseDirectory = "";
-
- _repositoryProductTag = new MongoDBRepositoryTest<ProductTag>();
- _productRepository = new MongoDBRepositoryTest<Product>();
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _productTagService = new ProductTagService(_repositoryProductTag, _productRepository, _cacheBase, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetAllProductTagsTest()
- {
- //Arrange
- await _repositoryProductTag.InsertAsync(new ProductTag());
- await _repositoryProductTag.InsertAsync(new ProductTag());
- await _repositoryProductTag.InsertAsync(new ProductTag());
-
- //Act
- var result = await _productTagService.GetAllProductTags();
-
- //Assert
- Assert.AreEqual(3, result.Count);
-
- }
-
- [TestMethod()]
- public async Task GetProductTagByIdTest()
- {
- //Arrange
- await _repositoryProductTag.InsertAsync(new ProductTag());
- await _repositoryProductTag.InsertAsync(new ProductTag { Id = "1", Name = "test" });
- await _repositoryProductTag.InsertAsync(new ProductTag());
-
- //Act
- var result = await _productTagService.GetProductTagById("1");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task GetProductTagByNameTest()
- {
- //Arrange
- await _repositoryProductTag.InsertAsync(new ProductTag());
- await _repositoryProductTag.InsertAsync(new ProductTag { Id = "1", Name = "test" });
- await _repositoryProductTag.InsertAsync(new ProductTag());
-
- //Act
- var result = await _productTagService.GetProductTagByName("test");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.Id);
- }
-
- [TestMethod()]
- public async Task GetProductTagBySeNameTest()
- {
- //Arrange
- await _repositoryProductTag.InsertAsync(new ProductTag());
- await _repositoryProductTag.InsertAsync(new ProductTag { Id = "1", Name = "test", SeName = "test" });
- await _repositoryProductTag.InsertAsync(new ProductTag());
-
- //Act
- var result = await _productTagService.GetProductTagBySeName("test");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.Id);
- }
-
- [TestMethod()]
- public async Task InsertProductTagTest()
- {
- //Arrange
- var productTag = new ProductTag {
- Name = "test"
- };
- //Act
- await _productTagService.InsertProductTag(productTag);
- var result = await _productTagService.GetProductTagById(productTag.Id);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task UpdateProductTagTest()
- {
- //Arrange
- var productTag = new ProductTag {
- Name = "test"
- };
- await _productTagService.InsertProductTag(productTag);
- //Act
- productTag.Name = "test2";
- await _productTagService.UpdateProductTag(productTag);
- var result = await _productTagService.GetProductTagById(productTag.Id);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test2", result.Name);
- }
-
- [TestMethod()]
- public async Task DeleteProductTagTest()
- {
- //Arrange
- var productTag = new ProductTag {
- Name = "test"
- };
- await _productTagService.InsertProductTag(productTag);
-
- //Act
- await _productTagService.DeleteProductTag(productTag);
- var result = await _productTagService.GetProductTagById(productTag.Id);
-
- //Assert
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task AttachProductTagTest()
- {
- //Arrange
- var productTag = new ProductTag {
- Name = "test"
- };
- await _productTagService.InsertProductTag(productTag);
- var product = new Product();
- await _productRepository.InsertAsync(product);
-
- //Act
- await _productTagService.AttachProductTag(productTag, product.Id);
- var result = _productRepository.Table.FirstOrDefault(x => x.Id == product.Id);
-
- //Assert
- Assert.IsTrue(result.ProductTags.Any());
- Assert.IsNotNull(result.ProductTags.FirstOrDefault(x => x == "test"));
- }
-
- [TestMethod()]
- public async Task DetachProductTagTest()
- {
- //Arrange
- var productTag = new ProductTag {
- Name = "test"
- };
- await _productTagService.InsertProductTag(productTag);
- var product = new Product();
- await _productRepository.InsertAsync(product);
- await _productTagService.AttachProductTag(productTag, product.Id);
-
- //Act
- await _productTagService.DetachProductTag(productTag, product.Id);
- var result = _productRepository.Table.FirstOrDefault(x => x.Id == product.Id);
-
- //Assert
- Assert.IsFalse(result.ProductTags.Any());
- Assert.IsNull(result.ProductTags.FirstOrDefault(x => x == "test"));
- }
-
- [TestMethod()]
- public async Task GetProductCountTest()
- {
- //Arrange
- var productTag = new ProductTag {
- Name = "test",
- Count = 10
- };
- await _productTagService.InsertProductTag(productTag);
- //Act
- var result = await _productTagService.GetProductCount(productTag.Id);
-
- //Assert
- Assert.AreEqual(10, result);
- }
+ //Arrange
+ var productTag = new ProductTag {
+ Name = "test",
+ Count = 10
+ };
+ await _productTagService.InsertProductTag(productTag);
+ //Act
+ var result = await _productTagService.GetProductCount(productTag.Id);
+
+ //Assert
+ Assert.AreEqual(10, result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/RecentlyViewedProductsServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/RecentlyViewedProductsServiceTests.cs
index c3a838643..67d3442d2 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/RecentlyViewedProductsServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/RecentlyViewedProductsServiceTests.cs
@@ -1,8 +1,8 @@
using Grand.Business.Catalog.Services.Products;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -10,57 +10,63 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class RecentlyViewedProductsServiceTests
{
- [TestClass()]
- public class RecentlyViewedProductsServiceTests
- {
- private IRepository<RecentlyViewedProduct> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private Mock<IProductService> _productServiceMock;
- RecentlyViewedProductsService _service;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IProductService> _productServiceMock;
+ private IRepository<RecentlyViewedProduct> _repository;
+ private RecentlyViewedProductsService _service;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<RecentlyViewedProduct>();
- _mediatorMock = new Mock<IMediator>();
- _productServiceMock = new Mock<IProductService>();
- _productServiceMock.Setup(a => a.GetProductsByIds(It.IsAny<string[]>(), false)).Returns(() => Task.FromResult((IList<Product>)new List<Product> { new Product { Id = "1", Published = true }, new Product { Id = "2", Published = true }, new Product { Id = "3", Published = true } }));
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _service = new RecentlyViewedProductsService(_productServiceMock.Object, _cacheBase, new CatalogSettings { RecentlyViewedProductsEnabled = true, RecentlyViewedProductsNumber = 10 }, _repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<RecentlyViewedProduct>();
+ _mediatorMock = new Mock<IMediator>();
+ _productServiceMock = new Mock<IProductService>();
+ _productServiceMock.Setup(a => a.GetProductsByIds(It.IsAny<string[]>(), false)).Returns(() =>
+ Task.FromResult((IList<Product>)new List<Product> {
+ new() { Id = "1", Published = true }, new() { Id = "2", Published = true },
+ new() { Id = "3", Published = true }
+ }));
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _service = new RecentlyViewedProductsService(_productServiceMock.Object, _cacheBase,
+ new CatalogSettings { RecentlyViewedProductsEnabled = true, RecentlyViewedProductsNumber = 10 },
+ _repository);
+ }
- [TestMethod()]
- public async Task GetRecentlyViewedProductsTest()
- {
- //Arrange
- await _service.AddProductToRecentlyViewedList("1", "1");
- await _service.AddProductToRecentlyViewedList("1", "2");
- await _service.AddProductToRecentlyViewedList("1", "3");
- await _service.AddProductToRecentlyViewedList("2", "1");
+ [TestMethod]
+ public async Task GetRecentlyViewedProductsTest()
+ {
+ //Arrange
+ await _service.AddProductToRecentlyViewedList("1", "1");
+ await _service.AddProductToRecentlyViewedList("1", "2");
+ await _service.AddProductToRecentlyViewedList("1", "3");
+ await _service.AddProductToRecentlyViewedList("2", "1");
- //Act
- var result = await _service.GetRecentlyViewedProducts("1", 10);
+ //Act
+ var result = await _service.GetRecentlyViewedProducts("1", 10);
- //Assert
- Assert.AreEqual(3, result.Count);
- }
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
- [TestMethod()]
- public async Task AddProductToRecentlyViewedListTest()
- {
- //Act
- await _service.AddProductToRecentlyViewedList("1", "1");
- await _service.AddProductToRecentlyViewedList("1", "2");
- await _service.AddProductToRecentlyViewedList("1", "3");
- await _service.AddProductToRecentlyViewedList("2", "1");
+ [TestMethod]
+ public async Task AddProductToRecentlyViewedListTest()
+ {
+ //Act
+ await _service.AddProductToRecentlyViewedList("1", "1");
+ await _service.AddProductToRecentlyViewedList("1", "2");
+ await _service.AddProductToRecentlyViewedList("1", "3");
+ await _service.AddProductToRecentlyViewedList("2", "1");
- //Assert
- Assert.AreEqual(4, _repository.Table.Count());
- }
+ //Assert
+ Assert.AreEqual(4, _repository.Table.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/SpecificationAttributeServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/SpecificationAttributeServiceTests.cs
index 8425e31ed..ceb434dc3 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/SpecificationAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/SpecificationAttributeServiceTests.cs
@@ -1,8 +1,8 @@
using Grand.Business.Catalog.Services.Products;
using Grand.Business.Core.Interfaces.Catalog.Products;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -10,239 +10,248 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class SpecificationAttributeServiceTests
{
- [TestClass()]
- public class SpecificationAttributeServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IProductService> _productServiceMock;
+ private IRepository<SpecificationAttribute> _repository;
+ private IRepository<Product> _repositoryProduct;
+
+ private SpecificationAttributeService service;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<SpecificationAttribute>();
+ _repositoryProduct = new MongoDBRepositoryTest<Product>();
+ _mediatorMock = new Mock<IMediator>();
+ _productServiceMock = new Mock<IProductService>();
+ _productServiceMock.Setup(a => a.GetProductsByIds(It.IsAny<string[]>(), false)).Returns(() =>
+ Task.FromResult((IList<Product>)new List<Product> {
+ new() { Id = "1", Published = true }, new() { Id = "2", Published = true },
+ new() { Id = "3", Published = true }
+ }));
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ service = new SpecificationAttributeService(_cacheBase, _repository, _repositoryProduct, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetSpecificationAttributeByIdTest()
+ {
+ //Arrange
+ var specificationAttribute = new SpecificationAttribute {
+ Name = "test"
+ };
+ await service.InsertSpecificationAttribute(specificationAttribute);
+
+ //Act
+ var result = await service.GetSpecificationAttributeById(specificationAttribute.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task GetSpecificationAttributeBySeNameTest()
+ {
+ //Arrange
+ var specificationAttribute = new SpecificationAttribute {
+ Name = "test",
+ SeName = "test"
+ };
+ await service.InsertSpecificationAttribute(specificationAttribute);
+
+ //Act
+ var result = await service.GetSpecificationAttributeBySeName("test");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task GetSpecificationAttributesTest()
+ {
+ //Arrange
+ await service.InsertSpecificationAttribute(new SpecificationAttribute());
+ await service.InsertSpecificationAttribute(new SpecificationAttribute());
+ await service.InsertSpecificationAttribute(new SpecificationAttribute());
+
+ //Act
+ var result = await service.GetSpecificationAttributes();
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertSpecificationAttributeTest()
+ {
+ //Arrange
+ var specificationAttribute = new SpecificationAttribute {
+ Name = "test",
+ SeName = "test"
+ };
+
+ //Act
+ await service.InsertSpecificationAttribute(specificationAttribute);
+
+ //Assert
+ Assert.AreEqual(1, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task UpdateSpecificationAttributeTest()
+ {
+ //Arrange
+ var specificationAttribute = new SpecificationAttribute {
+ Name = "test",
+ SeName = "test"
+ };
+ await service.InsertSpecificationAttribute(specificationAttribute);
+
+ //Act
+ specificationAttribute.Name = "test2";
+ await service.UpdateSpecificationAttribute(specificationAttribute);
+
+ //Assert
+ Assert.AreEqual("test2", _repository.Table.FirstOrDefault(x => x.Id == specificationAttribute.Id).Name);
+ }
+
+ [TestMethod]
+ public async Task DeleteSpecificationAttributeTest()
+ {
+ //Arrange
+ var specificationAttribute = new SpecificationAttribute {
+ Name = "test",
+ SeName = "test"
+ };
+ await service.InsertSpecificationAttribute(specificationAttribute);
+
+ //Act
+ await service.DeleteSpecificationAttribute(specificationAttribute);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == specificationAttribute.Id));
+ }
+
+ [TestMethod]
+ public async Task GetSpecificationAttributeByOptionIdTest()
+ {
+ //Arrange
+ var specificationAttribute = new SpecificationAttribute {
+ Name = "test",
+ SeName = "test"
+ };
+ var attr = new SpecificationAttributeOption();
+ specificationAttribute.SpecificationAttributeOptions.Add(attr);
+
+ await service.InsertSpecificationAttribute(specificationAttribute);
+
+ //Act
+ var result = await service.GetSpecificationAttributeByOptionId(attr.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task DeleteSpecificationAttributeOptionTest()
+ {
+ //Arrange
+ var specificationAttribute = new SpecificationAttribute {
+ Name = "test",
+ SeName = "test"
+ };
+ var attr = new SpecificationAttributeOption();
+ specificationAttribute.SpecificationAttributeOptions.Add(attr);
+
+ await service.InsertSpecificationAttribute(specificationAttribute);
+
+ //Act
+ await service.DeleteSpecificationAttributeOption(attr);
+
+ //Assert
+ Assert.AreEqual(0,
+ _repository.Table.FirstOrDefault(x => x.Id == specificationAttribute.Id).SpecificationAttributeOptions
+ .Count);
+ }
+
+ [TestMethod]
+ public async Task InsertProductSpecificationAttributeTest()
+ {
+ //Arrange
+ var product = new Product();
+
+ await _repositoryProduct.InsertAsync(product);
+
+ //Act
+ var attr = new ProductSpecificationAttribute();
+ await service.InsertProductSpecificationAttribute(attr, product.Id);
+
+ //Assert
+ Assert.AreEqual(1,
+ _repositoryProduct.Table.FirstOrDefault(x => x.Id == product.Id).ProductSpecificationAttributes.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateProductSpecificationAttributeTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _repositoryProduct.InsertAsync(product);
+ var attr = new ProductSpecificationAttribute();
+ await service.InsertProductSpecificationAttribute(attr, product.Id);
+
+ //Act
+ attr.CustomName = "test";
+ await service.UpdateProductSpecificationAttribute(attr, product.Id);
+
+ //Assert
+ Assert.AreEqual("test",
+ _repositoryProduct.Table.FirstOrDefault(x => x.Id == product.Id).ProductSpecificationAttributes
+ .FirstOrDefault(x => x.Id == attr.Id).CustomName);
+ }
+
+ [TestMethod]
+ public async Task DeleteProductSpecificationAttributeTest()
+ {
+ //Arrange
+ var product = new Product();
+ await _repositoryProduct.InsertAsync(product);
+
+ var attr = new ProductSpecificationAttribute();
+ await service.InsertProductSpecificationAttribute(attr, product.Id);
+
+ //Act
+ await service.DeleteProductSpecificationAttribute(attr, product.Id);
+
+ //Assert
+ Assert.AreEqual(0,
+ _repositoryProduct.Table.FirstOrDefault(x => x.Id == product.Id).ProductSpecificationAttributes.Count);
+ }
+
+ [TestMethod]
+ public async Task GetProductSpecificationAttributeCountTest()
{
+ //Arrange
+ var product = new Product();
+ await _repositoryProduct.InsertAsync(product);
+
+ var attr = new ProductSpecificationAttribute();
+ await service.InsertProductSpecificationAttribute(attr, product.Id);
+
+ //Act
+ var result = service.GetProductSpecificationAttributeCount();
- SpecificationAttributeService service;
- private IRepository<SpecificationAttribute> _repository;
- private IRepository<Product> _repositoryProduct;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private Mock<IProductService> _productServiceMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<SpecificationAttribute>();
- _repositoryProduct = new MongoDBRepositoryTest<Product>();
- _mediatorMock = new Mock<IMediator>();
- _productServiceMock = new Mock<IProductService>();
- _productServiceMock.Setup(a => a.GetProductsByIds(It.IsAny<string[]>(), false)).Returns(() => Task.FromResult((IList<Product>)new List<Product> { new Product { Id = "1", Published = true }, new Product { Id = "2", Published = true }, new Product { Id = "3", Published = true } }));
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- service = new SpecificationAttributeService(_cacheBase, _repository, _repositoryProduct, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetSpecificationAttributeByIdTest()
- {
- //Arrange
- var specificationAttribute = new SpecificationAttribute {
- Name = "test"
- };
- await service.InsertSpecificationAttribute(specificationAttribute);
-
- //Act
- var result = await service.GetSpecificationAttributeById(specificationAttribute.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task GetSpecificationAttributeBySeNameTest()
- {
- //Arrange
- var specificationAttribute = new SpecificationAttribute {
- Name = "test",
- SeName = "test"
- };
- await service.InsertSpecificationAttribute(specificationAttribute);
-
- //Act
- var result = await service.GetSpecificationAttributeBySeName("test");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task GetSpecificationAttributesTest()
- {
- //Arrange
- await service.InsertSpecificationAttribute(new SpecificationAttribute());
- await service.InsertSpecificationAttribute(new SpecificationAttribute());
- await service.InsertSpecificationAttribute(new SpecificationAttribute());
-
- //Act
- var result = await service.GetSpecificationAttributes();
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task InsertSpecificationAttributeTest()
- {
- //Arrange
- var specificationAttribute = new SpecificationAttribute {
- Name = "test",
- SeName = "test"
- };
-
- //Act
- await service.InsertSpecificationAttribute(specificationAttribute);
-
- //Assert
- Assert.AreEqual(1, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task UpdateSpecificationAttributeTest()
- {
- //Arrange
- var specificationAttribute = new SpecificationAttribute {
- Name = "test",
- SeName = "test"
- };
- await service.InsertSpecificationAttribute(specificationAttribute);
-
- //Act
- specificationAttribute.Name = "test2";
- await service.UpdateSpecificationAttribute(specificationAttribute);
-
- //Assert
- Assert.AreEqual("test2", _repository.Table.FirstOrDefault(x=>x.Id == specificationAttribute.Id).Name);
- }
-
- [TestMethod()]
- public async Task DeleteSpecificationAttributeTest()
- {
- //Arrange
- var specificationAttribute = new SpecificationAttribute {
- Name = "test",
- SeName = "test"
- };
- await service.InsertSpecificationAttribute(specificationAttribute);
-
- //Act
- await service.DeleteSpecificationAttribute(specificationAttribute);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == specificationAttribute.Id));
- }
-
- [TestMethod()]
- public async Task GetSpecificationAttributeByOptionIdTest()
- {
- //Arrange
- var specificationAttribute = new SpecificationAttribute {
- Name = "test",
- SeName = "test"
- };
- var attr = new SpecificationAttributeOption();
- specificationAttribute.SpecificationAttributeOptions.Add(attr);
-
- await service.InsertSpecificationAttribute(specificationAttribute);
-
- //Act
- var result = await service.GetSpecificationAttributeByOptionId(attr.Id);
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task DeleteSpecificationAttributeOptionTest()
- {
- //Arrange
- var specificationAttribute = new SpecificationAttribute {
- Name = "test",
- SeName = "test"
- };
- var attr = new SpecificationAttributeOption();
- specificationAttribute.SpecificationAttributeOptions.Add(attr);
-
- await service.InsertSpecificationAttribute(specificationAttribute);
-
- //Act
- await service.DeleteSpecificationAttributeOption(attr);
-
- //Assert
- Assert.AreEqual(0, _repository.Table.FirstOrDefault(x=>x.Id == specificationAttribute.Id).SpecificationAttributeOptions.Count);
- }
-
- [TestMethod()]
- public async Task InsertProductSpecificationAttributeTest()
- {
- //Arrange
- var product = new Product();
-
- await _repositoryProduct.InsertAsync(product);
-
- //Act
- var attr = new ProductSpecificationAttribute();
- await service.InsertProductSpecificationAttribute(attr, product.Id);
-
- //Assert
- Assert.AreEqual(1, _repositoryProduct.Table.FirstOrDefault(x => x.Id == product.Id).ProductSpecificationAttributes.Count);
- }
-
- [TestMethod()]
- public async Task UpdateProductSpecificationAttributeTest()
- {
- //Arrange
- var product = new Product();
- await _repositoryProduct.InsertAsync(product);
- var attr = new ProductSpecificationAttribute();
- await service.InsertProductSpecificationAttribute(attr, product.Id);
-
- //Act
- attr.CustomName = "test";
- await service.UpdateProductSpecificationAttribute(attr, product.Id);
-
- //Assert
- Assert.AreEqual("test", _repositoryProduct.Table.FirstOrDefault(x => x.Id == product.Id).ProductSpecificationAttributes.FirstOrDefault(x=>x.Id == attr.Id).CustomName);
- }
-
- [TestMethod()]
- public async Task DeleteProductSpecificationAttributeTest()
- {
- //Arrange
- var product = new Product();
- await _repositoryProduct.InsertAsync(product);
-
- var attr = new ProductSpecificationAttribute();
- await service.InsertProductSpecificationAttribute(attr, product.Id);
-
- //Act
- await service.DeleteProductSpecificationAttribute(attr, product.Id);
-
- //Assert
- Assert.AreEqual(0, _repositoryProduct.Table.FirstOrDefault(x => x.Id == product.Id).ProductSpecificationAttributes.Count);
-
- }
-
- [TestMethod()]
- public async Task GetProductSpecificationAttributeCountTest()
- {
- //Arrange
- var product = new Product();
- await _repositoryProduct.InsertAsync(product);
-
- var attr = new ProductSpecificationAttribute();
- await service.InsertProductSpecificationAttribute(attr, product.Id);
-
- //Act
- var result = service.GetProductSpecificationAttributeCount();
-
- //Assert
- Assert.AreEqual(1,result);
- }
+ //Assert
+ Assert.AreEqual(1, result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/StockQuantityServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/StockQuantityServiceTests.cs
index e14d444e3..2dd66f38e 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Products/StockQuantityServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Products/StockQuantityServiceTests.cs
@@ -4,176 +4,180 @@ using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Services.Products
+namespace Grand.Business.Catalog.Tests.Services.Products;
+
+[TestClass]
+public class StockQuantityServiceTests
{
- [TestClass()]
- public class StockQuantityServiceTests
- {
- private IStockQuantityService _stockQuantityService;
+ private IStockQuantityService _stockQuantityService;
- [TestInitialize()]
- public void Init()
+ [TestInitialize]
+ public void Init()
+ {
+ /*
+ var tempLocalizationService = new Mock<ITranslationService>();
{
- /*
- var tempLocalizationService = new Mock<ITranslationService>();
- {
- tempLocalizationService.Setup(x => x.GetResource("Products.Availability.InStockWithQuantity")).Returns("{0}");
- tempLocalizationService.Setup(x => x.GetResource("Products.ExclTaxSuffix")).Returns("InStock");
- _translationService = tempLocalizationService.Object;
- }
- */
- _stockQuantityService = new StockQuantityService();
+ tempLocalizationService.Setup(x => x.GetResource("Products.Availability.InStockWithQuantity")).Returns("{0}");
+ tempLocalizationService.Setup(x => x.GetResource("Products.ExclTaxSuffix")).Returns("InStock");
+ _translationService = tempLocalizationService.Object;
}
+ */
+ _stockQuantityService = new StockQuantityService();
+ }
- [TestMethod()]
- public void GetTotalStockQuantity_multiple_warehouses()
- {
- //if UseMultipleWarehouses is set to false, it will ignore StockQuantity of attached Warhouses
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- UseMultipleWarehouses = false,
- StockQuantity = 8765
- };
-
- product.ProductWarehouseInventory.Add(new ProductWarehouseInventory { WarehouseId = "101", StockQuantity = 7 });
- product.ProductWarehouseInventory.Add(new ProductWarehouseInventory { WarehouseId = "111", StockQuantity = 8 });
- product.ProductWarehouseInventory.Add(new ProductWarehouseInventory { WarehouseId = "121", StockQuantity = -2 });
-
- Assert.AreEqual(8765, _stockQuantityService.GetTotalStockQuantity(product, true));
- }
+ [TestMethod]
+ public void GetTotalStockQuantity_multiple_warehouses()
+ {
+ //if UseMultipleWarehouses is set to false, it will ignore StockQuantity of attached Warhouses
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ UseMultipleWarehouses = false,
+ StockQuantity = 8765
+ };
- [TestMethod()]
- public void GetTotalStockQuantity_multiple_warehouses_with_reserved()
- {
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- UseMultipleWarehouses = true, //UseMultipleWarehouse is set to true, so it will show only values of Warehouses
- StockQuantity = 333334765 //and totally ignores this
- };
-
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "1", StockQuantity = 4, ReservedQuantity = 444 });
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "2", StockQuantity = 4, ReservedQuantity = 444 });
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "3", StockQuantity = 4, ReservedQuantity = 444 });
-
- var stock = _stockQuantityService.GetTotalStockQuantity(product, useReservedQuantity: true, total: true);
- //argument is true, so it will consider borh StockQuantity and ReservedQuantity
- //equation:
- //available quantity = StockQuantity - ReservedQuantity
- //-1320 = 12 - 1332
- //looks like our Warehouse is lacking of stuff in number -1320
- Assert.AreEqual(-1320, stock);
- }
+ product.ProductWarehouseInventory.Add(new ProductWarehouseInventory { WarehouseId = "101", StockQuantity = 7 });
+ product.ProductWarehouseInventory.Add(new ProductWarehouseInventory { WarehouseId = "111", StockQuantity = 8 });
+ product.ProductWarehouseInventory.Add(new ProductWarehouseInventory
+ { WarehouseId = "121", StockQuantity = -2 });
- [TestMethod()]
- public void GetTotalStockQuantity_multiple_warehouses_without_reserved()
- {
- //if UseMultipleWarehouses is set to true, it will show StockQuantity of attached Warhouses
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- UseMultipleWarehouses = true, //so ignore this Product's StockQuantity
- StockQuantity = 8765
- };
-
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "1", StockQuantity = 4, ReservedQuantity = 444 });
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "2", StockQuantity = 4, ReservedQuantity = 222 });
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "3", StockQuantity = 4, ReservedQuantity = 111 });
- var stock = _stockQuantityService.GetTotalStockQuantity(product, useReservedQuantity: false, total: true);
- //it will ignore ReservedQuantity.. it is important to sell stuff, not having stuff
- Assert.AreEqual(12, stock);
- }
+ Assert.AreEqual(8765, _stockQuantityService.GetTotalStockQuantity(product));
+ }
- [TestMethod()]
- public void GetTotalStockQuantity_multiple_warehouses_with_warehouse_specified()
- {
- //show only specified Warehouse (by WarehouseID)
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- UseMultipleWarehouses = true,
- StockQuantity = 8765
- };
-
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "321", StockQuantity = 0, ReservedQuantity = 0 });
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "654", StockQuantity = 1500, ReservedQuantity = 1501 });
- product.ProductWarehouseInventory.Add(
- new ProductWarehouseInventory { WarehouseId = "987", StockQuantity = 0, ReservedQuantity = 0 });
-
- var stock = _stockQuantityService.GetTotalStockQuantity(product, true, "654");
- //only warehouse with ID = 654,
- //-1 = 1500-1501
- Assert.AreEqual(-1, stock);
- }
- [TestMethod()]
- public void GetTotalStockQuantityTest()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- StockAvailability = true,
- StockQuantity = 10,
- ReservedQuantity = 7,
- DisplayStockQuantity = true
- };
- //Act
- var result = _stockQuantityService.GetTotalStockQuantity(product);
- //Assert
- Assert.AreEqual(3, result);
- }
+ [TestMethod]
+ public void GetTotalStockQuantity_multiple_warehouses_with_reserved()
+ {
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ UseMultipleWarehouses =
+ true, //UseMultipleWarehouse is set to true, so it will show only values of Warehouses
+ StockQuantity = 333334765 //and totally ignores this
+ };
- [TestMethod()]
- public void GetTotalStockQuantityForCombinationTest()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStockByAttributes,
- StockAvailability = true,
- DisplayStockQuantity = true
- };
- //Act
- var result = _stockQuantityService.GetTotalStockQuantityForCombination(product, new ProductAttributeCombination { StockQuantity = 10 });
- //Assert
- Assert.AreEqual(10, result);
- }
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "1", StockQuantity = 4, ReservedQuantity = 444 });
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "2", StockQuantity = 4, ReservedQuantity = 444 });
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "3", StockQuantity = 4, ReservedQuantity = 444 });
- [TestMethod()]
- public void FormatStockMessageTest_ManageStock_StockAvailability_DisplayStockQuantity_InStockWithQuantity()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- StockQuantity = 8765,
- StockAvailability = true,
- DisplayStockQuantity = true
- };
- //Act
- var result = _stockQuantityService.FormatStockMessage(product, "", new List<CustomAttribute>());
- //Assert
- Assert.AreEqual(product.StockQuantity, result.arg0);
- Assert.AreEqual("Products.Availability.InStockWithQuantity", result.resource);
- }
-
- [TestMethod()]
- public void FormatStockMessageTest_ManageStock_StockAvailability_InStock()
- {
- //Arrange
- var product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- StockQuantity = 8765,
- StockAvailability = true,
- DisplayStockQuantity = false
- };
- //Act
- var result = _stockQuantityService.FormatStockMessage(product, "", new List<CustomAttribute>());
- //Assert
- Assert.AreEqual(null, result.arg0);
- Assert.AreEqual("Products.Availability.InStock", result.resource);
- }
+ var stock = _stockQuantityService.GetTotalStockQuantity(product, total: true);
+ //argument is true, so it will consider borh StockQuantity and ReservedQuantity
+ //equation:
+ //available quantity = StockQuantity - ReservedQuantity
+ //-1320 = 12 - 1332
+ //looks like our Warehouse is lacking of stuff in number -1320
+ Assert.AreEqual(-1320, stock);
+ }
+
+ [TestMethod]
+ public void GetTotalStockQuantity_multiple_warehouses_without_reserved()
+ {
+ //if UseMultipleWarehouses is set to true, it will show StockQuantity of attached Warhouses
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ UseMultipleWarehouses = true, //so ignore this Product's StockQuantity
+ StockQuantity = 8765
+ };
+
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "1", StockQuantity = 4, ReservedQuantity = 444 });
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "2", StockQuantity = 4, ReservedQuantity = 222 });
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "3", StockQuantity = 4, ReservedQuantity = 111 });
+ var stock = _stockQuantityService.GetTotalStockQuantity(product, false, total: true);
+ //it will ignore ReservedQuantity.. it is important to sell stuff, not having stuff
+ Assert.AreEqual(12, stock);
+ }
+
+ [TestMethod]
+ public void GetTotalStockQuantity_multiple_warehouses_with_warehouse_specified()
+ {
+ //show only specified Warehouse (by WarehouseID)
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ UseMultipleWarehouses = true,
+ StockQuantity = 8765
+ };
+
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "321", StockQuantity = 0, ReservedQuantity = 0 });
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "654", StockQuantity = 1500, ReservedQuantity = 1501 });
+ product.ProductWarehouseInventory.Add(
+ new ProductWarehouseInventory { WarehouseId = "987", StockQuantity = 0, ReservedQuantity = 0 });
+
+ var stock = _stockQuantityService.GetTotalStockQuantity(product, true, "654");
+ //only warehouse with ID = 654,
+ //-1 = 1500-1501
+ Assert.AreEqual(-1, stock);
+ }
+
+ [TestMethod]
+ public void GetTotalStockQuantityTest()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ StockAvailability = true,
+ StockQuantity = 10,
+ ReservedQuantity = 7,
+ DisplayStockQuantity = true
+ };
+ //Act
+ var result = _stockQuantityService.GetTotalStockQuantity(product);
+ //Assert
+ Assert.AreEqual(3, result);
+ }
+
+ [TestMethod]
+ public void GetTotalStockQuantityForCombinationTest()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStockByAttributes,
+ StockAvailability = true,
+ DisplayStockQuantity = true
+ };
+ //Act
+ var result =
+ _stockQuantityService.GetTotalStockQuantityForCombination(product,
+ new ProductAttributeCombination { StockQuantity = 10 });
+ //Assert
+ Assert.AreEqual(10, result);
+ }
+
+ [TestMethod]
+ public void FormatStockMessageTest_ManageStock_StockAvailability_DisplayStockQuantity_InStockWithQuantity()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ StockQuantity = 8765,
+ StockAvailability = true,
+ DisplayStockQuantity = true
+ };
+ //Act
+ var result = _stockQuantityService.FormatStockMessage(product, "", new List<CustomAttribute>());
+ //Assert
+ Assert.AreEqual(product.StockQuantity, result.arg0);
+ Assert.AreEqual("Products.Availability.InStockWithQuantity", result.resource);
+ }
+
+ [TestMethod]
+ public void FormatStockMessageTest_ManageStock_StockAvailability_InStock()
+ {
+ //Arrange
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ StockQuantity = 8765,
+ StockAvailability = true,
+ DisplayStockQuantity = false
+ };
+ //Act
+ var result = _stockQuantityService.FormatStockMessage(product, "", new List<CustomAttribute>());
+ //Assert
+ Assert.AreEqual(null, result.arg0);
+ Assert.AreEqual("Products.Availability.InStock", result.resource);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/FixedRateTestTaxProvider.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/FixedRateTestTaxProvider.cs
index 78fb4c2da..c7b9fb61c 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/FixedRateTestTaxProvider.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/FixedRateTestTaxProvider.cs
@@ -3,56 +3,56 @@ using Grand.Business.Core.Utilities.Catalog;
using Grand.Infrastructure.Plugins;
using Microsoft.AspNetCore.Routing;
-namespace Grand.Business.Catalog.Tests.Services.Tax
+namespace Grand.Business.Catalog.Tests.Services.Tax;
+
+public class FixedRateTestTaxProvider : BasePlugin, ITaxProvider
{
- public class FixedRateTestTaxProvider : BasePlugin, ITaxProvider
+ string IProvider.ConfigurationUrl => "";
+
+ public string SystemName => "test-provider";
+
+ public string FriendlyName => "tax provider";
+
+ public int Priority => 100;
+
+ public IList<string> LimitedToStores => new List<string>();
+
+ public IList<string> LimitedToGroups => new List<string>();
+
+ public Task<TaxResult> GetTaxRate(TaxRequest calculateTaxRequest)
+ {
+ var result = new TaxResult {
+ TaxRate = GetTaxRate(calculateTaxRequest.TaxCategoryId)
+ };
+ return Task.FromResult(result);
+ }
+
+
+ /// <summary>
+ /// Gets a tax rate
+ /// </summary>
+ /// <param name="taxCategoryId">The tax category identifier</param>
+ /// <returns>Tax rate</returns>
+ protected double GetTaxRate(string taxCategoryId)
+ {
+ if (string.IsNullOrEmpty(taxCategoryId))
+ return 0;
+
+ double rate = 10;
+ return rate;
+ }
+
+ /// <summary>
+ /// Gets a route for provider configuration
+ /// </summary>
+ /// <param name="actionName">Action name</param>
+ /// <param name="controllerName">Controller name</param>
+ /// <param name="routeValues">Route values</param>
+ public void GetConfigurationRoute(out string actionName, out string controllerName,
+ out RouteValueDictionary routeValues)
{
- string IProvider.ConfigurationUrl => "";
-
- public string SystemName => "test-provider";
-
- public string FriendlyName => "tax provider";
-
- public int Priority => 100;
-
- public IList<string> LimitedToStores => new List<string>();
-
- public IList<string> LimitedToGroups => new List<string>();
-
-
- /// <summary>
- /// Gets a tax rate
- /// </summary>
- /// <param name="taxCategoryId">The tax category identifier</param>
- /// <returns>Tax rate</returns>
- protected double GetTaxRate(string taxCategoryId)
- {
- if (string.IsNullOrEmpty(taxCategoryId))
- return 0;
-
- double rate = 10;
- return rate;
- }
-
- /// <summary>
- /// Gets a route for provider configuration
- /// </summary>
- /// <param name="actionName">Action name</param>
- /// <param name="controllerName">Controller name</param>
- /// <param name="routeValues">Route values</param>
- public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
- {
- actionName = null;
- controllerName = null;
- routeValues = null;
- }
-
- public Task<TaxResult> GetTaxRate(TaxRequest calculateTaxRequest)
- {
- var result = new TaxResult {
- TaxRate = GetTaxRate(calculateTaxRequest.TaxCategoryId)
- };
- return Task.FromResult(result);
- }
+ actionName = null;
+ controllerName = null;
+ routeValues = null;
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxCategoryServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxCategoryServiceTests.cs
index 4733436b9..e30af4467 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxCategoryServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxCategoryServiceTests.cs
@@ -1,6 +1,6 @@
using Grand.Business.Catalog.Services.Tax;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Tax;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -9,105 +9,99 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Tax
+namespace Grand.Business.Catalog.Tests.Services.Tax;
+
+[TestClass]
+public class TaxCategoryServiceTests
{
- [TestClass()]
- public class TaxCategoryServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<TaxCategory> _repository;
+ private TaxCategoryService _taxCategoryService;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<TaxCategory>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _taxCategoryService = new TaxCategoryService(_cacheBase, _repository, _mediatorMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task GetAllTaxCategoriesTest()
+ {
+ //Arrange
+ await _taxCategoryService.InsertTaxCategory(new TaxCategory());
+ await _taxCategoryService.InsertTaxCategory(new TaxCategory());
+ await _taxCategoryService.InsertTaxCategory(new TaxCategory());
+
+ //Act
+ var result = await _taxCategoryService.GetAllTaxCategories();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetTaxCategoryByIdTest()
+ {
+ //Arrange
+ var taxCategory = new TaxCategory {
+ Name = "test1"
+ };
+ await _repository.InsertAsync(taxCategory);
+ //Assert
+ var result = await _taxCategoryService.GetTaxCategoryById(taxCategory.Id);
+
+ //Act
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test1", result.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertTaxCategoryTest()
+ {
+ //Act
+ await _taxCategoryService.InsertTaxCategory(new TaxCategory());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateTaxCategoryTest()
+ {
+ //Arrange
+ var tax = new TaxCategory {
+ Name = "test"
+ };
+ await _taxCategoryService.InsertTaxCategory(tax);
+ tax.Name = "test2";
+
+ //Act
+ await _taxCategoryService.UpdateTaxCategory(tax);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
+ }
+
+ [TestMethod]
+ public async Task DeleteTaxCategoryTest()
{
- private IRepository<TaxCategory> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private TaxCategoryService _taxCategoryService;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<TaxCategory>();
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _taxCategoryService = new TaxCategoryService(_cacheBase, _repository, _mediatorMock.Object);
- }
-
-
- [TestMethod()]
- public async Task GetAllTaxCategoriesTest()
- {
- //Arrange
- await _taxCategoryService.InsertTaxCategory(new TaxCategory());
- await _taxCategoryService.InsertTaxCategory(new TaxCategory());
- await _taxCategoryService.InsertTaxCategory(new TaxCategory());
-
- //Act
- var result = await _taxCategoryService.GetAllTaxCategories();
-
- //Assert
- Assert.AreEqual(3, result.Count);
-
- }
-
- [TestMethod()]
- public async Task GetTaxCategoryByIdTest()
- {
- //Arrange
- var taxCategory = new TaxCategory {
- Name = "test1"
- };
- await _repository.InsertAsync(taxCategory);
- //Assert
- var result = await _taxCategoryService.GetTaxCategoryById(taxCategory.Id);
-
- //Act
- Assert.IsNotNull(result);
- Assert.AreEqual("test1", result.Name);
-
- }
-
- [TestMethod()]
- public async Task InsertTaxCategoryTest()
- {
- //Act
- await _taxCategoryService.InsertTaxCategory(new TaxCategory());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
-
- }
-
- [TestMethod()]
- public async Task UpdateTaxCategoryTest()
- {
- //Arrange
- var tax = new TaxCategory {
- Name = "test"
- };
- await _taxCategoryService.InsertTaxCategory(tax);
- tax.Name = "test2";
-
- //Act
- await _taxCategoryService.UpdateTaxCategory(tax);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
-
- }
-
- [TestMethod()]
- public async Task DeleteTaxCategoryTest()
- {
- //Arrange
- var tax = new TaxCategory {
- Name = "test"
- };
- await _taxCategoryService.InsertTaxCategory(tax);
- await _taxCategoryService.InsertTaxCategory(new TaxCategory());
- //Act
- await _taxCategoryService.DeleteTaxCategory(tax);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
- Assert.AreEqual(1, _repository.Table.Count());
-
-
- }
+ //Arrange
+ var tax = new TaxCategory {
+ Name = "test"
+ };
+ await _taxCategoryService.InsertTaxCategory(tax);
+ await _taxCategoryService.InsertTaxCategory(new TaxCategory());
+ //Act
+ await _taxCategoryService.DeleteTaxCategory(tax);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
+ Assert.AreEqual(1, _repository.Table.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
index 149ce31b0..7b718585a 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/TaxServiceTests.cs
@@ -12,271 +12,321 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Catalog.Tests.Services.Tax
+namespace Grand.Business.Catalog.Tests.Services.Tax;
+
+[TestClass]
+public class TaxServiceTests
{
- [TestClass()]
- public class TaxServiceTests
+ private AddressSettings _addressSettings;
+ private ICountryService _countryService;
+ private CustomerSettings _customerSettings;
+ private IGeoLookupService _geoLookupService;
+ private Mock<IGroupService> _groupServiceMock;
+ private Mock<ILogger<TaxService>> _loggerMock;
+
+ private IServiceProvider _serviceProvider;
+ private TaxProviderSettings _taxProviderSettings;
+ private ITaxService _taxService;
+ private TaxSettings _taxSettings;
+ private IVatService _vatService;
+
+ private IWorkContext _workContext;
+
+ [TestInitialize]
+ public void TestInitialize()
{
+ CommonPath.BaseDirectory = "";
+
+ var serviceProvider = new Mock<IServiceProvider>();
+ serviceProvider.Setup(x => x.GetService(typeof(FixedRateTestTaxProvider)))
+ .Returns(new FixedRateTestTaxProvider());
+ _serviceProvider = serviceProvider.Object;
+
+ _taxProviderSettings = new TaxProviderSettings {
+ ActiveTaxProviderSystemName = "test-provider"
+ };
+
+ _taxSettings = new TaxSettings();
+ _workContext = null;
+ _geoLookupService = new Mock<IGeoLookupService>().Object;
+ _countryService = new Mock<ICountryService>().Object;
+ _customerSettings = new CustomerSettings();
+ _addressSettings = new AddressSettings();
+ _groupServiceMock = new Mock<IGroupService>();
+ _loggerMock = new Mock<ILogger<TaxService>>();
+ var providers = new List<ITaxProvider>();
+ providers.Add(new FixedRateTestTaxProvider());
+ _taxService = new TaxService(_workContext, _groupServiceMock.Object,
+ _geoLookupService, _countryService, providers, _loggerMock.Object,
+ _taxSettings, _taxProviderSettings, _customerSettings, _addressSettings);
+
+ _vatService = new VatService(_taxSettings);
+ }
- private IWorkContext _workContext;
- private TaxSettings _taxSettings;
- private TaxProviderSettings _taxProviderSettings;
- private ITaxService _taxService;
- private IVatService _vatService;
- private IGeoLookupService _geoLookupService;
- private ICountryService _countryService;
- private CustomerSettings _customerSettings;
- private AddressSettings _addressSettings;
- private Mock<IGroupService> _groupServiceMock;
- private Mock<ILogger<TaxService>> _loggerMock;
-
- private IServiceProvider _serviceProvider;
- [TestInitialize()]
- public void TestInitialize()
- {
- CommonPath.BaseDirectory = "";
-
- var serviceProvider = new Mock<IServiceProvider>();
- serviceProvider.Setup(x => x.GetService(typeof(FixedRateTestTaxProvider))).Returns(new FixedRateTestTaxProvider());
- _serviceProvider = serviceProvider.Object;
-
- _taxProviderSettings = new TaxProviderSettings {
- ActiveTaxProviderSystemName = "test-provider"
- };
-
- _taxSettings = new TaxSettings();
- _workContext = null;
- _geoLookupService = new Mock<IGeoLookupService>().Object;
- _countryService = new Mock<ICountryService>().Object;
- _customerSettings = new CustomerSettings();
- _addressSettings = new AddressSettings();
- _groupServiceMock = new Mock<IGroupService>();
- _loggerMock = new Mock<ILogger<TaxService>>();
- var providers = new List<ITaxProvider>();
- providers.Add(new FixedRateTestTaxProvider());
- _taxService = new TaxService( _workContext,_groupServiceMock.Object,
- _geoLookupService, _countryService,providers ,_loggerMock.Object,
- _taxSettings, _taxProviderSettings, _customerSettings, _addressSettings);
-
- _vatService = new VatService(_taxSettings);
- }
-
- [TestMethod()]
- public async Task Can_check_taxExempt_product()
- {
+ [TestMethod]
+ public async Task Can_check_taxExempt_product()
+ {
+ var product = new Product {
+ IsTaxExempt = true
+ };
+ Assert.IsTrue(await _taxService.IsTaxExempt(product, null));
+ product.IsTaxExempt = false;
+ Assert.IsFalse(await _taxService.IsTaxExempt(product, null));
+ }
+
+ [TestMethod]
+ public async Task Can_check_taxExempt_customer()
+ {
+ var customer = new Customer();
+ customer.Groups.Add("group sample id");
+ customer.IsTaxExempt = true;
+ Assert.IsTrue(await _taxService.IsTaxExempt(null, customer));
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
+ customer.IsTaxExempt = false;
+ Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
+ }
- var product = new Product {
- IsTaxExempt = true
- };
- Assert.IsTrue(await _taxService.IsTaxExempt(product, null));
- product.IsTaxExempt = false;
- Assert.IsFalse(await _taxService.IsTaxExempt(product, null));
- }
+ /*
+ [TestMethod()]
+ public async Task Can_check_taxExempt_customer_in_taxExemptCustomerRole()
+ {
+ var customer = new Customer();
+ customer.IsTaxExempt = false;
+ Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
- [TestMethod()]
- public async Task Can_check_taxExempt_customer()
+ var customerRole = new CustomerRole
{
+ TaxExempt = true,
+ Active = true
+ };
+ customer.CustomerRoles.Add(customerRole);
+ Assert.IsTrue(await _taxService.IsTaxExempt(null, customer));
+ customerRole.TaxExempt = false;
+ Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
+
+ customerRole.Active = false;
+ Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
+ }
+ */
+ [TestMethod]
+ public async Task Can_get_productPrice_priceIncludesTax_includingTax_taxable()
+ {
+ var customer = new Customer();
+ var product = new Product();
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
+ var pp = await _taxService.GetProductPrice(product, "0", 1000, true, customer, true);
+ var price = pp.productprice;
+ Assert.AreEqual(1000, price);
+ }
- var customer = new Customer();
- customer.Groups.Add("group sample id");
- customer.IsTaxExempt = true;
- Assert.IsTrue(await _taxService.IsTaxExempt(null, customer));
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>())).Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
- customer.IsTaxExempt = false;
- Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
- }
- /*
- [TestMethod()]
- public async Task Can_check_taxExempt_customer_in_taxExemptCustomerRole()
- {
- var customer = new Customer();
- customer.IsTaxExempt = false;
- Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
-
- var customerRole = new CustomerRole
- {
- TaxExempt = true,
- Active = true
- };
- customer.CustomerRoles.Add(customerRole);
- Assert.IsTrue(await _taxService.IsTaxExempt(null, customer));
- customerRole.TaxExempt = false;
- Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
-
- customerRole.Active = false;
- Assert.IsFalse(await _taxService.IsTaxExempt(null, customer));
- }
- */
- [TestMethod()]
- public async Task Can_get_productPrice_priceIncludesTax_includingTax_taxable()
- {
- var customer = new Customer();
- var product = new Product();
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>())).Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
- var pp = await _taxService.GetProductPrice(product, "0", 1000, true, customer, true);
- var price = pp.productprice;
- Assert.AreEqual(1000, price);
- }
-
- [TestMethod()]
- public async Task Can_get_productPrice_priceIncludesTax_includingTax_non_taxable()
- {
+ [TestMethod]
+ public async Task Can_get_productPrice_priceIncludesTax_includingTax_non_taxable()
+ {
+ var customer = new Customer { IsTaxExempt = true }; //not taxable
+ var product = new Product();
+
+ Assert.AreEqual(Math.Round(909.0909090, 2),
+ (await _taxService.GetProductPrice(product, "0", 1000, true, customer, true)).productprice);
+ Assert.AreEqual(1000,
+ (await _taxService.GetProductPrice(product, "0", 1000, true, customer, false)).productprice);
+ Assert.AreEqual(Math.Round(909.0909090, 2),
+ (await _taxService.GetProductPrice(product, "0", 1000, false, customer, true)).productprice);
+ Assert.AreEqual(1000,
+ (await _taxService.GetProductPrice(product, "0", 1000, false, customer, false)).productprice);
+ }
- var customer = new Customer { IsTaxExempt = true }; //not taxable
- var product = new Product();
+ [TestMethod]
+ public async Task Should_assume_valid_VAT_number_if_EuVatAssumeValid_setting_is_true()
+ {
+ _taxSettings.EuVatAssumeValid = true;
+ var vatNumberStatus = (await _vatService.GetVatNumberStatus("GB", "000 0000 00")).status;
+ Assert.AreEqual(VatNumberStatus.Valid, vatNumberStatus);
+ }
- Assert.AreEqual(Math.Round(909.0909090, 2), (await _taxService.GetProductPrice(product, "0", 1000, true, customer, true)).productprice);
- Assert.AreEqual(1000, (await _taxService.GetProductPrice(product, "0", 1000, true, customer, false)).productprice);
- Assert.AreEqual(Math.Round(909.0909090, 2), (await _taxService.GetProductPrice(product, "0", 1000, false, customer, true)).productprice);
- Assert.AreEqual(1000, (await _taxService.GetProductPrice(product, "0", 1000, false, customer, false)).productprice);
- }
+ [TestMethod]
+ public async Task GetProductPriceQuickly_NonTaxExemptAndPriceIncludingTax_ShouldReturnTheSameValues()
+ {
+ var product = new Product {
+ IsTaxExempt = false
+ };
+ var customer = new Customer {
+ IsTaxExempt = false
+ };
+
+ var taxCategoryId = ""; //as in code
+ var scUnitPriceWithoutDiscount = 1000.00;
+ var scUnitPrice = 1000.00;
+ var scSubTotal = 5000.00;
+ var discountAmount = 7000.00;
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
+ //these 6 methods..
+ var scUnitPriceInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, true)).productprice;
+ var scUnitPriceExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, true))
+ .productprice;
+ var scSubTotalInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, true)).productprice;
+ var scSubTotalExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, true)).productprice;
+ var discountAmountInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, true))
+ .productprice;
+ var discountAmountExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, true))
+ .productprice;
+ //..should return the same value as this one method's properties are having
+ var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,
+ 1, scSubTotal, discountAmount, true);
+
+ Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
+ Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
+ Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
+ Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
+ }
- [TestMethod()]
- public async Task Should_assume_valid_VAT_number_if_EuVatAssumeValid_setting_is_true()
- {
- _taxSettings.EuVatAssumeValid = true;
- VatNumberStatus vatNumberStatus = (await _vatService.GetVatNumberStatus("GB", "000 0000 00")).status;
- Assert.AreEqual(VatNumberStatus.Valid, vatNumberStatus);
- }
+ [TestMethod]
+ public async Task GetProductPriceQuickly_NonTaxExemptAndPriceExcludingTax_ShouldReturnTheSameValues()
+ {
+ var product = new Product {
+ TaxCategoryId = "",
+ IsTele = false,
+ IsTaxExempt = false
+ };
+ var customer = new Customer {
+ IsTaxExempt = false
+ };
+ var taxCategoryId = ""; //as in code
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
+ var scUnitPriceWithoutDiscount = 1000.00;
+ var scUnitPrice = 1000.00;
+ var scSubTotal = 5000.00;
+ var discountAmount = 7000.00;
+
+ var scUnitPriceInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, false))
+ .productprice;
+ var scUnitPriceExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, false))
+ .productprice;
+ var scSubTotalInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, false)).productprice;
+ var scSubTotalExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, false))
+ .productprice;
+ var discountAmountInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, false))
+ .productprice;
+ var discountAmountExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, false))
+ .productprice;
+
+ var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,
+ 1, scSubTotal, discountAmount, false);
+
+ Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
+ Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
+ Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
+ Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
+ }
- [TestMethod()]
- public async Task GetProductPriceQuickly_NonTaxExemptAndPriceIncludingTax_ShouldReturnTheSameValues()
- {
- var product = new Product {
- IsTaxExempt = false
- };
- var customer = new Customer {
- IsTaxExempt = false
- };
-
- var taxCategoryId = ""; //as in code
- var scUnitPriceWithoutDiscount = 1000.00;
- var scUnitPrice = 1000.00;
- var scSubTotal = 5000.00;
- var discountAmount = 7000.00;
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>())).Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
- //these 6 methods..
- var scUnitPriceInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, true)).productprice;
- var scUnitPriceExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, true)).productprice;
- var scSubTotalInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, true)).productprice;
- var scSubTotalExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, true)).productprice;
- var discountAmountInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, true)).productprice;
- var discountAmountExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, true)).productprice;
- //..should return the same value as this one method's properties are having
- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount, 1, scSubTotal, discountAmount, true);
-
- Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
- Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
- Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
- Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
- Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
- Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
- }
-
- [TestMethod()]
- public async Task GetProductPriceQuickly_NonTaxExemptAndPriceExcludingTax_ShouldReturnTheSameValues()
- {
- var product = new Product {
- TaxCategoryId = "",
- IsTele = false,
- IsTaxExempt = false
- };
- var customer = new Customer {
- IsTaxExempt = false
- };
- var taxCategoryId = ""; //as in code
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>())).Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup>()));
- var scUnitPriceWithoutDiscount = 1000.00;
- var scUnitPrice = 1000.00;
- var scSubTotal = 5000.00;
- var discountAmount = 7000.00;
-
- var scUnitPriceInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, false)).productprice;
- var scUnitPriceExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, false)).productprice;
- var scSubTotalInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, false)).productprice;
- var scSubTotalExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, false)).productprice;
- var discountAmountInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, false)).productprice;
- var discountAmountExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, false)).productprice;
-
- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount, 1, scSubTotal, discountAmount, false);
-
- Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
- Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
- Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
- Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
- Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
- Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
- }
-
- [TestMethod()]
- public async Task GetProductPriceQuickly_TaxExemptAndPriceIncludingTax_ShouldReturnTheSameValues()
- {
- var product = new Product {
- TaxCategoryId = "57516fc81b0dc92b20fdd2ef",
- IsTele = false,
- IsTaxExempt = true
- };
- var customer = new Customer {
- IsTaxExempt = true
- };
- var taxCategoryId = "";
-
- var scUnitPriceWithoutDiscount = 1000.00;
- var scUnitPrice = 1000.00;
- var scSubTotal = 5000.00;
- var discountAmount = 7000.00;
-
- var scUnitPriceInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, true)).productprice;
- var scUnitPriceExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, true)).productprice;
- var scSubTotalInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, true)).productprice;
- var scSubTotalExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, true)).productprice;
- var discountAmountInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, true)).productprice;
- var discountAmountExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, true)).productprice;
-
- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount, 1, scSubTotal, discountAmount, true);
-
- Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
- Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
- Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
- Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
- Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
- Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
- }
-
- [TestMethod()]
- public async Task GetProductPriceQuickly_TaxExemptAndPriceExcludingTax_ShouldReturnTheSameValues()
- {
- var product = new Product {
- TaxCategoryId = "57516fc81b0dc92b20fdd2ef",
- IsTele = false,
- IsTaxExempt = true
- };
- var customer = new Customer {
- IsTaxExempt = true
- };
- var taxCategoryId = "";
-
- var scUnitPriceWithoutDiscount = 1000.00;
- var scUnitPrice = 1000.00;
- var scSubTotal = 5000.00;
- var discountAmount = 7000.00;
-
- var scUnitPriceInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, false)).productprice;
- var scUnitPriceExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, false)).productprice;
- var scSubTotalInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, false)).productprice;
- var scSubTotalExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, false)).productprice;
- var discountAmountInclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, false)).productprice;
- var discountAmountExclTax = (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, false)).productprice;
-
- var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount, 1, scSubTotal, discountAmount, false);
-
- Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
- Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
- Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
- Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
- Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
- Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
- }
+ [TestMethod]
+ public async Task GetProductPriceQuickly_TaxExemptAndPriceIncludingTax_ShouldReturnTheSameValues()
+ {
+ var product = new Product {
+ TaxCategoryId = "57516fc81b0dc92b20fdd2ef",
+ IsTele = false,
+ IsTaxExempt = true
+ };
+ var customer = new Customer {
+ IsTaxExempt = true
+ };
+ var taxCategoryId = "";
+
+ var scUnitPriceWithoutDiscount = 1000.00;
+ var scUnitPrice = 1000.00;
+ var scSubTotal = 5000.00;
+ var discountAmount = 7000.00;
+
+ var scUnitPriceInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, true)).productprice;
+ var scUnitPriceExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, true))
+ .productprice;
+ var scSubTotalInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, true)).productprice;
+ var scSubTotalExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, true)).productprice;
+ var discountAmountInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, true))
+ .productprice;
+ var discountAmountExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, true))
+ .productprice;
+
+ var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,
+ 1, scSubTotal, discountAmount, true);
+
+ Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
+ Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
+ Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
+ Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
+ }
+ [TestMethod]
+ public async Task GetProductPriceQuickly_TaxExemptAndPriceExcludingTax_ShouldReturnTheSameValues()
+ {
+ var product = new Product {
+ TaxCategoryId = "57516fc81b0dc92b20fdd2ef",
+ IsTele = false,
+ IsTaxExempt = true
+ };
+ var customer = new Customer {
+ IsTaxExempt = true
+ };
+ var taxCategoryId = "";
+
+ var scUnitPriceWithoutDiscount = 1000.00;
+ var scUnitPrice = 1000.00;
+ var scSubTotal = 5000.00;
+ var discountAmount = 7000.00;
+
+ var scUnitPriceInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, true, customer, false))
+ .productprice;
+ var scUnitPriceExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scUnitPrice, false, customer, false))
+ .productprice;
+ var scSubTotalInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, true, customer, false)).productprice;
+ var scSubTotalExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, scSubTotal, false, customer, false))
+ .productprice;
+ var discountAmountInclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, true, customer, false))
+ .productprice;
+ var discountAmountExclTax =
+ (await _taxService.GetProductPrice(product, taxCategoryId, discountAmount, false, customer, false))
+ .productprice;
+
+ var result02 = await _taxService.GetTaxProductPrice(product, customer, scUnitPrice, scUnitPriceWithoutDiscount,
+ 1, scSubTotal, discountAmount, false);
+
+ Assert.AreEqual(scUnitPriceInclTax, result02.UnitPriceInclTax, "unit price including tax");
+ Assert.AreEqual(scUnitPriceExclTax, result02.UnitPriceExclTax, "unit price excluding tax");
+ Assert.AreEqual(scSubTotalInclTax, result02.SubTotalInclTax, "sub total including tax");
+ Assert.AreEqual(scSubTotalExclTax, result02.SubTotalExclTax, "sub total excluding tax");
+ Assert.AreEqual(discountAmountInclTax, result02.DiscountAmountInclTax, "discount including tax");
+ Assert.AreEqual(discountAmountExclTax, result02.DiscountAmountExclTax, "discount excluding tax");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/VatServiceTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/VatServiceTests.cs
index 4cb73f54a..77dd958f4 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/VatServiceTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Services/Tax/VatServiceTests.cs
@@ -1,64 +1,67 @@
using Grand.Business.Catalog.Services.Tax;
+using Grand.Business.Core.Utilities.Catalog;
using Grand.Domain.Tax;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Services.Tax
+namespace Grand.Business.Catalog.Tests.Services.Tax;
+
+[TestClass]
+public class VatServiceTests
{
- [TestClass()]
- public class VatServiceTests
+ private TaxSettings _taxSettings;
+ private VatService _vatService;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _taxSettings = new TaxSettings { EuVatAssumeValid = true, EuVatUseWebService = false };
+ _vatService = new VatService(_taxSettings);
+ }
+
+ [DataRow("PL1111111111")]
+ [DataRow("1111111111")]
+ [TestMethod]
+ public async Task GetVatNumberStatusTest(string vat)
+ {
+ //Act
+ var result = await _vatService.GetVatNumberStatus(vat);
+ //Assert
+ Assert.AreEqual(VatNumberStatus.Valid, result.status);
+ }
+
+ [TestMethod]
+ public async Task GetVatNumberStatusTest_Valid()
{
- private VatService _vatService;
- private TaxSettings _taxSettings;
+ //Act
+ var result = await _vatService.GetVatNumberStatus("PL", "1111111111");
+ //Assert
+ Assert.AreEqual(VatNumberStatus.Valid, result.status);
+ }
- [TestInitialize()]
- public void Init()
- {
- _taxSettings = new TaxSettings { EuVatAssumeValid = true, EuVatUseWebService = false };
- _vatService = new VatService(_taxSettings);
- }
+ [TestMethod]
+ public async Task GetVatNumberStatusTest_InValid()
+ {
+ //Act
+ var result = await _vatService.GetVatNumberStatus("PL", "");
+ //Assert
+ Assert.AreEqual(VatNumberStatus.Empty, result.status);
+ }
- [DataRow("PL1111111111")]
- [DataRow("1111111111")]
- [TestMethod()]
- public async Task GetVatNumberStatusTest(string vat)
- {
- //Act
- var result = await _vatService.GetVatNumberStatus(vat);
- //Assert
- Assert.AreEqual(VatNumberStatus.Valid, result.status);
- }
- [TestMethod()]
- public async Task GetVatNumberStatusTest_Valid()
- {
- //Act
- var result = await _vatService.GetVatNumberStatus("PL", "1111111111");
- //Assert
- Assert.AreEqual(VatNumberStatus.Valid, result.status);
- }
- [TestMethod()]
- public async Task GetVatNumberStatusTest_InValid()
- {
- //Act
- var result = await _vatService.GetVatNumberStatus("PL", "");
- //Assert
- Assert.AreEqual(VatNumberStatus.Empty, result.status);
- }
- [TestMethod()]
- public async Task DoVatCheckTest()
- {
- //Act
- var result = await _vatService.DoVatCheck("PL", "1111111111");
- //Assert
- Assert.AreEqual(VatNumberStatus.Invalid, result.status);
- }
+ [TestMethod]
+ public async Task DoVatCheckTest()
+ {
+ //Act
+ var result = await _vatService.DoVatCheck("PL", "1111111111");
+ //Assert
+ Assert.AreEqual(VatNumberStatus.Invalid, result.status);
+ }
- [TestMethod()]
- public async Task CheckVatRequestTest()
- {
- //Act
- var result = await _vatService.CheckVatRequest(new Core.Utilities.Catalog.VatRequest());
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task CheckVatRequestTest()
+ {
+ //Act
+ var result = await _vatService.CheckVatRequest(new VatRequest());
+ //Assert
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Catalog.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Startup/StartupApplicationTests.cs
index 932bcbd63..22fb681d7 100644
--- a/src/Tests/Grand.Business.Catalog.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Catalog.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Catalog.Tests.Startup
+namespace Grand.Business.Catalog.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ActivatedValueForPurchasedGiftVouchersCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ActivatedValueForPurchasedGiftVouchersCommandHandlerTests.cs
index 6ec8414c2..023790ce7 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ActivatedValueForPurchasedGiftVouchersCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ActivatedValueForPurchasedGiftVouchersCommandHandlerTests.cs
@@ -9,62 +9,64 @@ using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class ActivatedValueForPurchasedGiftVouchersCommandHandlerTests
{
- [TestClass]
- public class ActivatedValueForPurchasedGiftVouchersCommandHandlerTests
- {
- private Mock<IGiftVoucherService> _giftVoucherMock;
- private Mock<ILanguageService> _langService;
- private Mock<IMessageProviderService> _messageProviderMock;
- private ActivatedValueForPurchasedGiftVouchersCommandHandler _handler;
+ private Mock<IGiftVoucherService> _giftVoucherMock;
+ private ActivatedValueForPurchasedGiftVouchersCommandHandler _handler;
+ private Mock<ILanguageService> _langService;
+ private Mock<IMessageProviderService> _messageProviderMock;
- [TestInitialize]
- public void Init()
- {
- _giftVoucherMock = new Mock<IGiftVoucherService>();
- _langService = new Mock<ILanguageService>();
- _messageProviderMock = new Mock<IMessageProviderService>();
- _handler = new ActivatedValueForPurchasedGiftVouchersCommandHandler(_giftVoucherMock.Object, _langService.Object, _messageProviderMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _giftVoucherMock = new Mock<IGiftVoucherService>();
+ _langService = new Mock<ILanguageService>();
+ _messageProviderMock = new Mock<IMessageProviderService>();
+ _handler = new ActivatedValueForPurchasedGiftVouchersCommandHandler(_giftVoucherMock.Object,
+ _langService.Object, _messageProviderMock.Object);
+ }
- [TestMethod]
- public async Task Handle_InvokeExpectedMethods()
- {
- var command = new ActivatedValueForPurchasedGiftVouchersCommand {
- Order = new Order()
- };
- var gift = new GiftVoucher { RecipientEmail = "fdsf", SenderEmail = "aaa", IsGiftVoucherActivated = false };
- command.Activate = true;
- command.Order.OrderItems.Add(new OrderItem { });
- _langService.Setup(c => c.GetLanguageById(It.IsAny<string>())).ReturnsAsync(new Language());
- _giftVoucherMock.Setup(c => c.GetAllGiftVouchers(It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
+ [TestMethod]
+ public async Task Handle_InvokeExpectedMethods()
+ {
+ var command = new ActivatedValueForPurchasedGiftVouchersCommand {
+ Order = new Order()
+ };
+ var gift = new GiftVoucher { RecipientEmail = "fdsf", SenderEmail = "aaa", IsGiftVoucherActivated = false };
+ command.Activate = true;
+ command.Order.OrderItems.Add(new OrderItem());
+ _langService.Setup(c => c.GetLanguageById(It.IsAny<string>())).ReturnsAsync(new Language());
+ _giftVoucherMock.Setup(c => c.GetAllGiftVouchers(It.IsAny<string>(), It.IsAny<DateTime?>(),
+ It.IsAny<DateTime?>(),
It.IsAny<bool?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
- .ReturnsAsync(new PagedList<GiftVoucher> { gift });
+ .ReturnsAsync(new PagedList<GiftVoucher> { gift });
- await _handler.Handle(command, default);
- Assert.IsTrue(gift.IsGiftVoucherActivated);
- _messageProviderMock.Verify(c => c.SendGiftVoucherMessage(gift, command.Order, It.IsAny<string>()), Times.Once);
- _giftVoucherMock.Verify(c => c.UpdateGiftVoucher(gift));
- }
+ await _handler.Handle(command, default);
+ Assert.IsTrue(gift.IsGiftVoucherActivated);
+ _messageProviderMock.Verify(c => c.SendGiftVoucherMessage(gift, command.Order, It.IsAny<string>()), Times.Once);
+ _giftVoucherMock.Verify(c => c.UpdateGiftVoucher(gift));
+ }
- [TestMethod]
- public async Task Handle_Deactivate()
- {
- var command = new ActivatedValueForPurchasedGiftVouchersCommand {
- Order = new Order()
- };
- var gift = new GiftVoucher { RecipientEmail = "fdsf", SenderEmail = "aaa", IsGiftVoucherActivated = true };
- command.Activate = false;
- command.Order.OrderItems.Add(new OrderItem { });
- _langService.Setup(c => c.GetLanguageById(It.IsAny<string>())).ReturnsAsync(new Language());
- _giftVoucherMock.Setup(c => c.GetAllGiftVouchers(It.IsAny<string>(), It.IsAny<DateTime?>(), It.IsAny<DateTime?>(),
+ [TestMethod]
+ public async Task Handle_Deactivate()
+ {
+ var command = new ActivatedValueForPurchasedGiftVouchersCommand {
+ Order = new Order()
+ };
+ var gift = new GiftVoucher { RecipientEmail = "fdsf", SenderEmail = "aaa", IsGiftVoucherActivated = true };
+ command.Activate = false;
+ command.Order.OrderItems.Add(new OrderItem());
+ _langService.Setup(c => c.GetLanguageById(It.IsAny<string>())).ReturnsAsync(new Language());
+ _giftVoucherMock.Setup(c => c.GetAllGiftVouchers(It.IsAny<string>(), It.IsAny<DateTime?>(),
+ It.IsAny<DateTime?>(),
It.IsAny<bool?>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
- .ReturnsAsync(new PagedList<GiftVoucher> { gift });
+ .ReturnsAsync(new PagedList<GiftVoucher> { gift });
- await _handler.Handle(command, default);
- Assert.IsFalse(gift.IsGiftVoucherActivated);
- _giftVoucherMock.Verify(c => c.UpdateGiftVoucher(gift));
- }
+ await _handler.Handle(command, default);
+ Assert.IsFalse(gift.IsGiftVoucherActivated);
+ _giftVoucherMock.Verify(c => c.UpdateGiftVoucher(gift));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddCustomerReservationCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddCustomerReservationCommandHandlerTests.cs
index e5a9cc988..a8c32dd70 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddCustomerReservationCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddCustomerReservationCommandHandlerTests.cs
@@ -1,55 +1,62 @@
using Grand.Business.Checkout.Commands.Handlers.Orders;
+using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Domain;
using Grand.Domain.Catalog;
+using Grand.Domain.Customers;
+using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class AddCustomerReservationCommandHandlerTests
{
- [TestClass()]
- public class AddCustomerReservationCommandHandlerTests
+ private AddCustomerReservationCommandHandler _handler;
+ private Mock<IProductReservationService> _productReservationServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private AddCustomerReservationCommandHandler _handler;
- private Mock<IProductReservationService> _productReservationServiceMock;
-
- [TestInitialize]
- public void Init()
- {
- _productReservationServiceMock = new Mock<IProductReservationService>();
- _handler = new AddCustomerReservationCommandHandler(_productReservationServiceMock.Object);
- }
+ _productReservationServiceMock = new Mock<IProductReservationService>();
+ _handler = new AddCustomerReservationCommandHandler(_productReservationServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new Core.Commands.Checkout.Orders.AddCustomerReservationCommand {
- Customer = new Domain.Customers.Customer(),
- RentalStartDate = DateTime.UtcNow.AddDays(1).Date,
- RentalEndDate = DateTime.UtcNow.AddDays(2).Date,
- Product = new Domain.Catalog.Product {
- IncBothDate = true,
- IntervalUnitId = IntervalUnit.Day
- },
- ShoppingCartItem = new Domain.Orders.ShoppingCartItem { }
- };
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new AddCustomerReservationCommand {
+ Customer = new Customer(),
+ RentalStartDate = DateTime.UtcNow.AddDays(1).Date,
+ RentalEndDate = DateTime.UtcNow.AddDays(2).Date,
+ Product = new Product {
+ IncBothDate = true,
+ IntervalUnitId = IntervalUnit.Day
+ },
+ ShoppingCartItem = new ShoppingCartItem()
+ };
- _productReservationServiceMock.Setup(c => c.GetProductReservationsByProductId(It.IsAny<string>(), true, null, 0, int.MaxValue)).Returns(() => Task.FromResult((IPagedList<ProductReservation>)
- new PagedList<ProductReservation> {
- new ProductReservation { Date = DateTime.UtcNow.AddDays(4).Date, Resource = "" },
- new ProductReservation { Date = DateTime.UtcNow.AddDays(3).Date, Resource = "" },
- new ProductReservation { Date = DateTime.UtcNow.AddDays(2).Date, Resource = "" },
- new ProductReservation { Date = DateTime.UtcNow.AddDays(1).Date, Resource = "" },
- new ProductReservation { Date = DateTime.UtcNow.Date, Resource = "" } }
+ _productReservationServiceMock
+ .Setup(c => c.GetProductReservationsByProductId(It.IsAny<string>(), true, null, 0, int.MaxValue)).Returns(
+ () => Task.FromResult((IPagedList<ProductReservation>)
+ new PagedList<ProductReservation> {
+ new() { Date = DateTime.UtcNow.AddDays(4).Date, Resource = "" },
+ new() { Date = DateTime.UtcNow.AddDays(3).Date, Resource = "" },
+ new() { Date = DateTime.UtcNow.AddDays(2).Date, Resource = "" },
+ new() { Date = DateTime.UtcNow.AddDays(1).Date, Resource = "" },
+ new() { Date = DateTime.UtcNow.Date, Resource = "" }
+ }
));
- _productReservationServiceMock.Setup(c => c.GetCustomerReservationsHelpers(It.IsAny<string>())).ReturnsAsync(new List<CustomerReservationsHelper> { });
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
+ _productReservationServiceMock.Setup(c => c.GetCustomerReservationsHelpers(It.IsAny<string>()))
+ .ReturnsAsync(new List<CustomerReservationsHelper>());
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _productReservationServiceMock.Verify(c => c.InsertCustomerReservationsHelper(It.IsAny<CustomerReservationsHelper>()));
- }
+ //Assert
+ _productReservationServiceMock.Verify(c =>
+ c.InsertCustomerReservationsHelper(It.IsAny<CustomerReservationsHelper>()));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs
index cd2c40e3d..148483d7b 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs
@@ -1,4 +1,5 @@
using Grand.Business.Checkout.Commands.Handlers.Orders;
+using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Utilities.Checkout;
@@ -8,46 +9,51 @@ using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
-{
- [TestClass()]
- public class AddRequiredProductsCommandHandlerTests
- {
- private AddRequiredProductsCommandHandler _handler;
- private Mock<IShoppingCartService> _shoppingCartServiceMock;
- private ShoppingCartSettings _shoppingCartSettings;
- private Mock<IProductService> _productServiceMock;
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
- [TestInitialize]
- public void Init()
- {
- _shoppingCartServiceMock = new Mock<IShoppingCartService>();
- _shoppingCartSettings = new ShoppingCartSettings();
- _productServiceMock = new Mock<IProductService>();
- _handler = new AddRequiredProductsCommandHandler(_shoppingCartServiceMock.Object, _shoppingCartSettings, _productServiceMock.Object);
+[TestClass]
+public class AddRequiredProductsCommandHandlerTests
+{
+ private AddRequiredProductsCommandHandler _handler;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IShoppingCartService> _shoppingCartServiceMock;
+ private ShoppingCartSettings _shoppingCartSettings;
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _shoppingCartServiceMock = new Mock<IShoppingCartService>();
+ _shoppingCartSettings = new ShoppingCartSettings();
+ _productServiceMock = new Mock<IProductService>();
+ _handler = new AddRequiredProductsCommandHandler(_shoppingCartServiceMock.Object, _shoppingCartSettings,
+ _productServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new Core.Commands.Checkout.Orders.AddRequiredProductsCommand {
- Customer = new Domain.Customers.Customer()
- };
- command.Customer.ShoppingCartItems.Add(new ShoppingCartItem { ProductId = "1", ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "" });
- command.Product = new Domain.Catalog.Product { Id = "1", RequireOtherProducts = true, RequiredProductIds = "2,3", AutoAddRequiredProducts = true };
- command.ShoppingCartType = ShoppingCartType.ShoppingCart;
- command.StoreId = "";
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new AddRequiredProductsCommand {
+ Customer = new Customer()
+ };
+ command.Customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { ProductId = "1", ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "" });
+ command.Product = new Product
+ { Id = "1", RequireOtherProducts = true, RequiredProductIds = "2,3", AutoAddRequiredProducts = true };
+ command.ShoppingCartType = ShoppingCartType.ShoppingCart;
+ command.StoreId = "";
- _productServiceMock.Setup(a => a.GetProductById("2", false)).Returns(() => Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
- _productServiceMock.Setup(a => a.GetProductById("3", false)).Returns(() => Task.FromResult(new Product { Id = "3", Published = true, Price = 10 }));
+ _productServiceMock.Setup(a => a.GetProductById("2", false)).Returns(() =>
+ Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
+ _productServiceMock.Setup(a => a.GetProductById("3", false)).Returns(() =>
+ Task.FromResult(new Product { Id = "3", Published = true, Price = 10 }));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _shoppingCartServiceMock.Verify(c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), ShoppingCartType.ShoppingCart, "", null, null,null, null, null, 1, false, "", "", "", It.IsAny<ShoppingCartValidatorOptions>()), Times.AtLeastOnce);
- }
+ //Assert
+ _shoppingCartServiceMock.Verify(
+ c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), ShoppingCartType.ShoppingCart, "", null, null,
+ null, null, null, 1, false, "", "", "", It.IsAny<ShoppingCartValidatorOptions>()), Times.AtLeastOnce);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandlerTests.cs
index f360afb5c..055bdb310 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandlerTests.cs
@@ -6,57 +6,65 @@ using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Customers;
using Grand.Domain.Directory;
+using Grand.Domain.Orders;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class AwardLoyaltyPointsCommandHandlerTests
{
- [TestClass()]
- public class AwardLoyaltyPointsCommandHandlerTests
+ private Mock<ICurrencyService> _currencyServiceMock;
+ private Mock<ICustomerService> _customerServiceMock;
+ private AwardLoyaltyPointsCommandHandler _handler;
+ private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<ITranslationService> _translationServiceMock;
+
+
+ [TestInitialize]
+ public void Init()
+ {
+ _customerServiceMock = new Mock<ICustomerService>();
+ _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
+ _mediatorMock = new Mock<IMediator>();
+ _currencyServiceMock = new Mock<ICurrencyService>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+
+ _handler = new AwardLoyaltyPointsCommandHandler(_customerServiceMock.Object, _loyaltyPointsServiceMock.Object,
+ _mediatorMock.Object, _orderServiceMock.Object, _translationServiceMock.Object,
+ _currencyServiceMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task HandleTest()
{
- private AwardLoyaltyPointsCommandHandler _handler;
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<ITranslationService> _translationServiceMock;
- private Mock<ICurrencyService> _currencyServiceMock;
-
-
- [TestInitialize]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
- _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
- _mediatorMock = new Mock<IMediator>();
- _currencyServiceMock = new Mock<ICurrencyService>();
- _orderServiceMock = new Mock<IOrderService>();
- _translationServiceMock = new Mock<ITranslationService>();
-
- _handler = new AwardLoyaltyPointsCommandHandler(_customerServiceMock.Object, _loyaltyPointsServiceMock.Object, _mediatorMock.Object, _orderServiceMock.Object, _translationServiceMock.Object, _currencyServiceMock.Object);
- }
-
-
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new AwardLoyaltyPointsCommand {
- Order = new Domain.Orders.Order { StoreId = "", OrderNumber = 1 }
- };
- var expectedCustomer = new Customer { Username = "John", Active = true };
- _customerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>())).Returns(() => Task.FromResult(expectedCustomer));
- _currencyServiceMock.Setup(c => c.GetCurrencyByCode(It.IsAny<string>())).Returns(() => Task.FromResult(new Domain.Directory.Currency()));
- _currencyServiceMock.Setup(c => c.ConvertToPrimaryStoreCurrency(100, It.IsAny<Currency>())).Returns(() => Task.FromResult((double)100));
- _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
- _mediatorMock.Setup(x => x.Send(It.IsAny<CalculateLoyaltyPointsCommand>(), default)).Returns(Task.FromResult(100));
-
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
-
- //Assert
- _loyaltyPointsServiceMock.Verify(c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Once);
- }
+ //Arrange
+ var command = new AwardLoyaltyPointsCommand {
+ Order = new Order { StoreId = "", OrderNumber = 1 }
+ };
+ var expectedCustomer = new Customer { Username = "John", Active = true };
+ _customerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(expectedCustomer));
+ _currencyServiceMock.Setup(c => c.GetCurrencyByCode(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Currency()));
+ _currencyServiceMock.Setup(c => c.ConvertToPrimaryStoreCurrency(100, It.IsAny<Currency>()))
+ .Returns(() => Task.FromResult((double)100));
+ _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CalculateLoyaltyPointsCommand>(), default))
+ .Returns(Task.FromResult(100));
+
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+
+ //Assert
+ _loyaltyPointsServiceMock.Verify(
+ c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<double>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandlerTests.cs
index d4a4ecf1a..42a737129 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CalculateLoyaltyPointsCommandHandlerTests.cs
@@ -1,63 +1,63 @@
using Grand.Business.Checkout.Commands.Handlers.Orders;
using Grand.Business.Core.Commands.Checkout.Orders;
+using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class CalculateLoyaltyPointsCommandHandlerTests
{
- [TestClass]
- public class CalculateLoyaltyPointsCommandHandlerTests
- {
- private LoyaltyPointsSettings _settings;
- private CalculateLoyaltyPointsCommandHandler _handler;
+ private CalculateLoyaltyPointsCommandHandler _handler;
+ private LoyaltyPointsSettings _settings;
- [TestInitialize]
- public void Init()
- {
- _settings = new LoyaltyPointsSettings();
- _handler = new CalculateLoyaltyPointsCommandHandler(_settings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _settings = new LoyaltyPointsSettings();
+ _handler = new CalculateLoyaltyPointsCommandHandler(_settings);
+ }
- [TestMethod]
- public async Task Handle_NullCustomer_ReturnZero()
- {
- _settings.Enabled = true;
- _settings.PointsForPurchases_Amount = 20;
- var command = new CalculateLoyaltyPointsCommand {
- Customer = null
- };
- var result = await _handler.Handle(command, default);
- Assert.AreEqual(0, result);
- }
+ [TestMethod]
+ public async Task Handle_NullCustomer_ReturnZero()
+ {
+ _settings.Enabled = true;
+ _settings.PointsForPurchases_Amount = 20;
+ var command = new CalculateLoyaltyPointsCommand {
+ Customer = null
+ };
+ var result = await _handler.Handle(command, default);
+ Assert.AreEqual(0, result);
+ }
- [TestMethod]
- public async Task Handle_NotEnable_ReturnZero()
- {
- _settings.Enabled = false;
- _settings.PointsForPurchases_Amount = 20;
- var command = new CalculateLoyaltyPointsCommand {
- Customer = new Domain.Customers.Customer()
- };
- var result = await _handler.Handle(command, default);
- Assert.AreEqual(0, result);
- }
+ [TestMethod]
+ public async Task Handle_NotEnable_ReturnZero()
+ {
+ _settings.Enabled = false;
+ _settings.PointsForPurchases_Amount = 20;
+ var command = new CalculateLoyaltyPointsCommand {
+ Customer = new Customer()
+ };
+ var result = await _handler.Handle(command, default);
+ Assert.AreEqual(0, result);
+ }
- [TestMethod]
- public async Task Handle_ReturnExpectedValue()
- {
- _settings.Enabled = true;
- _settings.PointsForPurchases_Amount = 10;
- _settings.PointsForPurchases_Points = 2;
- var command = new CalculateLoyaltyPointsCommand {
- Customer = new Domain.Customers.Customer(),
- Amount = 100
- };
+ [TestMethod]
+ public async Task Handle_ReturnExpectedValue()
+ {
+ _settings.Enabled = true;
+ _settings.PointsForPurchases_Amount = 10;
+ _settings.PointsForPurchases_Points = 2;
+ var command = new CalculateLoyaltyPointsCommand {
+ Customer = new Customer(),
+ Amount = 100
+ };
- Assert.AreEqual(20, await _handler.Handle(command, default));
- command.Amount = 200;
- Assert.AreEqual(40, await _handler.Handle(command, default));
- command.Amount = 375;
- Assert.AreEqual(75, await _handler.Handle(command, default));
- }
+ Assert.AreEqual(20, await _handler.Handle(command, default));
+ command.Amount = 200;
+ Assert.AreEqual(40, await _handler.Handle(command, default));
+ command.Amount = 375;
+ Assert.AreEqual(75, await _handler.Handle(command, default));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderCommandHandlerTests.cs
index 50d24ffea..4126236ae 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderCommandHandlerTests.cs
@@ -1,8 +1,8 @@
-using Grand.Business.Core.Interfaces.Catalog.Discounts;
-using Grand.Business.Core.Interfaces.Catalog.Products;
-using Grand.Business.Checkout.Commands.Handlers.Orders;
+using Grand.Business.Checkout.Commands.Handlers.Orders;
using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Events.Checkout.Orders;
+using Grand.Business.Core.Interfaces.Catalog.Discounts;
+using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Checkout.Shipping;
@@ -12,73 +12,74 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class CancelOrderCommandHandlerTests
{
- [TestClass]
- public class CancelOrderCommandHandlerTests
- {
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IInventoryManageService> _inventoryMock;
- private Mock<IProductReservationService> _productReservationMock;
- private Mock<IAuctionService> _auctionMock;
- private Mock<IDiscountService> _discountServiceMock;
- private Mock<IPaymentService> _paymentService;
- private Mock<IPaymentTransactionService> _paymentTransactionService;
- private CancelOrderCommandHandler _handler;
+ private Mock<IAuctionService> _auctionMock;
+ private Mock<IDiscountService> _discountServiceMock;
+ private CancelOrderCommandHandler _handler;
+ private Mock<IInventoryManageService> _inventoryMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IPaymentService> _paymentService;
+ private Mock<IPaymentTransactionService> _paymentTransactionService;
+ private Mock<IProductReservationService> _productReservationMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _productServiceMock = new Mock<IProductService>();
- _inventoryMock = new Mock<IInventoryManageService>();
- _productReservationMock = new Mock<IProductReservationService>();
- _auctionMock = new Mock<IAuctionService>();
- _discountServiceMock = new Mock<IDiscountService>();
- _paymentService = new Mock<IPaymentService>();
- _paymentTransactionService = new Mock<IPaymentTransactionService>();
- _handler = new CancelOrderCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _shipmentServiceMock.Object,
- _productServiceMock.Object, _inventoryMock.Object, _productReservationMock.Object, _auctionMock.Object, _discountServiceMock.Object, _paymentService.Object, _paymentTransactionService.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _productServiceMock = new Mock<IProductService>();
+ _inventoryMock = new Mock<IInventoryManageService>();
+ _productReservationMock = new Mock<IProductReservationService>();
+ _auctionMock = new Mock<IAuctionService>();
+ _discountServiceMock = new Mock<IDiscountService>();
+ _paymentService = new Mock<IPaymentService>();
+ _paymentTransactionService = new Mock<IPaymentTransactionService>();
+ _handler = new CancelOrderCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _shipmentServiceMock.Object,
+ _productServiceMock.Object, _inventoryMock.Object, _productReservationMock.Object, _auctionMock.Object,
+ _discountServiceMock.Object, _paymentService.Object, _paymentTransactionService.Object);
+ }
- [TestMethod]
- public void Handle_OrderNull_ThrowException()
- {
- var command = new CancelOrderCommand {
- Order = null
- };
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _handler.Handle(command, default));
- }
+ [TestMethod]
+ public void Handle_OrderNull_ThrowException()
+ {
+ var command = new CancelOrderCommand {
+ Order = null
+ };
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _handler.Handle(command, default));
+ }
- [TestMethod]
- public void Handle_AlreadyCancelled_ThrowException()
- {
- var command = new CancelOrderCommand {
- Order = new Order { OrderStatusId = (int)OrderStatusSystem.Cancelled }
- };
- Assert.ThrowsExceptionAsync<Exception>(async () => await _handler.Handle(command, default));
- }
+ [TestMethod]
+ public void Handle_AlreadyCancelled_ThrowException()
+ {
+ var command = new CancelOrderCommand {
+ Order = new Order { OrderStatusId = (int)OrderStatusSystem.Cancelled }
+ };
+ Assert.ThrowsExceptionAsync<Exception>(async () => await _handler.Handle(command, default));
+ }
- [TestMethod]
- public async Task Handle_InvokeExpectedMethods()
- {
- var command = new CancelOrderCommand {
- Order = new Order {
- Id = "id"
- }
- };
- _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder("id")).ReturnsAsync(new List<Shipment>());
- await _handler.Handle(command, default);
+ [TestMethod]
+ public async Task Handle_InvokeExpectedMethods()
+ {
+ var command = new CancelOrderCommand {
+ Order = new Order {
+ Id = "id"
+ }
+ };
+ _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder("id")).ReturnsAsync(new List<Shipment>());
+ await _handler.Handle(command, default);
- _productReservationMock.Verify(c => c.CancelReservationsByOrderId("id"), Times.Once);
- _auctionMock.Verify(c => c.CancelBidByOrder("id"), Times.Once);
- _discountServiceMock.Verify(c => c.CancelDiscount("id"), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<OrderCancelledEvent>(), default));
- }
+ _productReservationMock.Verify(c => c.CancelReservationsByOrderId("id"), Times.Once);
+ _auctionMock.Verify(c => c.CancelBidByOrder("id"), Times.Once);
+ _discountServiceMock.Verify(c => c.CancelDiscount("id"), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<OrderCancelledEvent>(), default));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderItemCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderItemCommandHandlerTests.cs
index 96f6a95ca..3af844ed9 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderItemCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CancelOrderItemCommandHandlerTests.cs
@@ -11,46 +11,50 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class CancelOrderItemCommandHandlerTests
{
- [TestClass()]
- public class CancelOrderItemCommandHandlerTests
+ private CancelOrderItemCommandHandler _handler;
+ private Mock<IInventoryManageService> _inventoryMock;
+
+
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _productServiceMock = new Mock<IProductService>();
+ _inventoryMock = new Mock<IInventoryManageService>();
+ _handler = new CancelOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _shipmentServiceMock.Object,
+ _productServiceMock.Object, _inventoryMock.Object);
+ }
+
+ [TestMethod]
+ public async Task HandleTest()
{
+ var command = new CancelOrderItemCommand {
+ Order = new Order {
+ Id = "id"
+ },
+ OrderItem = new OrderItem { OpenQty = 1, Status = OrderItemStatus.Open }
+ };
+ _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
+ await _handler.Handle(command, default);
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IInventoryManageService> _inventoryMock;
- private CancelOrderItemCommandHandler _handler;
-
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _productServiceMock = new Mock<IProductService>();
- _inventoryMock = new Mock<IInventoryManageService>();
- _handler = new CancelOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _shipmentServiceMock.Object,
- _productServiceMock.Object, _inventoryMock.Object);
- }
- [TestMethod()]
- public async Task HandleTest()
- {
- var command = new CancelOrderItemCommand {
- Order = new Order {
- Id = "id"
- },
- OrderItem = new OrderItem { OpenQty = 1, Status = OrderItemStatus.Open }
- };
-
- _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
- await _handler.Handle(command, default);
-
- _inventoryMock.Verify(c => c.AdjustReserved(It.IsAny<Product>(), It.IsAny<int>(), It.IsAny<IList<CustomAttribute>>(), It.IsAny<string>()), Times.Once);
- }
+ _inventoryMock.Verify(
+ c => c.AdjustReserved(It.IsAny<Product>(), It.IsAny<int>(), It.IsAny<IList<CustomAttribute>>(),
+ It.IsAny<string>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs
index c22a71dfd..812d6516e 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CaptureCommandHandlerTests.cs
@@ -9,43 +9,43 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class CaptureCommandHandlerTests
{
- [TestClass()]
- public class CaptureCommandHandlerTests
+ private CaptureCommandHandler _handler;
+ private Mock<ILogger<CaptureCommandHandler>> _loggerMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+
+ private Mock<IPaymentService> _paymentServiceMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
+
+ [TestInitialize]
+ public void Init()
{
- private CaptureCommandHandler _handler;
-
- private Mock<IPaymentService> _paymentServiceMock;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<ILogger<CaptureCommandHandler>> _loggerMock;
-
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _loggerMock = new Mock<ILogger<CaptureCommandHandler>>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentServiceMock = new Mock<IPaymentService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
-
- _handler = new CaptureCommandHandler(_paymentServiceMock.Object, _paymentTransactionMock.Object, _mediatorMock.Object, _orderServiceMock.Object, _loggerMock.Object);
- }
-
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new CaptureCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanCaptureQuery>(), default))
- .Returns(Task.FromResult(true));
-
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
-
- _paymentServiceMock.Verify(c => c.Capture(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ _mediatorMock = new Mock<IMediator>();
+ _loggerMock = new Mock<ILogger<CaptureCommandHandler>>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentServiceMock = new Mock<IPaymentService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+
+ _handler = new CaptureCommandHandler(_paymentServiceMock.Object, _paymentTransactionMock.Object,
+ _mediatorMock.Object, _orderServiceMock.Object, _loggerMock.Object);
+ }
+
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new CaptureCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanCaptureQuery>(), default))
+ .Returns(Task.FromResult(true));
+
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+
+ _paymentServiceMock.Verify(c => c.Capture(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CheckOrderStatusCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CheckOrderStatusCommandHandlerTests.cs
index 55da5a466..4b958ea58 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CheckOrderStatusCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/CheckOrderStatusCommandHandlerTests.cs
@@ -7,40 +7,39 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class CheckOrderStatusCommandHandlerTests
{
- [TestClass]
- public class CheckOrderStatusCommandHandlerTests
- {
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderSerivce;
- private OrderSettings _settings;
- private CheckOrderStatusCommandHandler _handler;
+ private CheckOrderStatusCommandHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderSerivce;
+ private OrderSettings _settings;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderSerivce = new Mock<IOrderService>();
- _settings = new OrderSettings();
- _handler = new CheckOrderStatusCommandHandler(_mediatorMock.Object, _orderSerivce.Object, _settings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderSerivce = new Mock<IOrderService>();
+ _settings = new OrderSettings();
+ _handler = new CheckOrderStatusCommandHandler(_mediatorMock.Object, _orderSerivce.Object, _settings);
+ }
- [TestMethod]
- public async Task Handle_InvokeExpectedMethods()
- {
- var request = new CheckOrderStatusCommand {
- Order = new Order {
- PaymentStatusId = PaymentStatus.Paid,
- PaidDateUtc = null,
- OrderStatusId = (int)OrderStatusSystem.Pending
- }
- };
+ [TestMethod]
+ public async Task Handle_InvokeExpectedMethods()
+ {
+ var request = new CheckOrderStatusCommand {
+ Order = new Order {
+ PaymentStatusId = PaymentStatus.Paid,
+ PaidDateUtc = null,
+ OrderStatusId = (int)OrderStatusSystem.Pending
+ }
+ };
- await _handler.Handle(request, default);
- _orderSerivce.Verify(c => c.UpdateOrder(request.Order), Times.Once);
- _mediatorMock.Verify(c => c.Send(It.IsAny<SetOrderStatusCommand>(), default), Times.AtLeastOnce);
- }
+ await _handler.Handle(request, default);
+ _orderSerivce.Verify(c => c.UpdateOrder(request.Order), Times.Once);
+ _mediatorMock.Verify(c => c.Send(It.IsAny<SetOrderStatusCommand>(), default), Times.AtLeastOnce);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderCommandHandlerTests.cs
index 3ddfed3b1..af890174c 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderCommandHandlerTests.cs
@@ -10,49 +10,51 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class DeleteOrderCommandHandlerTests
{
- [TestClass()]
- public class DeleteOrderCommandHandlerTests
+ private Mock<IAuctionService> _auctionServiceMock;
+ private Mock<IDiscountService> _discountServiceMock;
+ private DeleteOrderCommandHandler _handler;
+ private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private OrderSettings _orderSettings;
+ private Mock<IProductReservationService> _productReservationServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private DeleteOrderCommandHandler _handler;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IInventoryManageService> _inventoryManageServiceMock;
- private Mock<IProductReservationService> _productReservationServiceMock;
- private Mock<IAuctionService> _auctionServiceMock;
- private Mock<IDiscountService> _discountServiceMock;
- private OrderSettings _orderSettings;
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _productServiceMock = new Mock<IProductService>();
+ _inventoryManageServiceMock = new Mock<IInventoryManageService>();
+ _productReservationServiceMock = new Mock<IProductReservationService>();
+ _auctionServiceMock = new Mock<IAuctionService>();
+ _discountServiceMock = new Mock<IDiscountService>();
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _productServiceMock = new Mock<IProductService>();
- _inventoryManageServiceMock = new Mock<IInventoryManageService>();
- _productReservationServiceMock = new Mock<IProductReservationService>();
- _auctionServiceMock = new Mock<IAuctionService>();
- _discountServiceMock = new Mock<IDiscountService>();
+ _orderSettings = new OrderSettings();
- _orderSettings = new OrderSettings();
+ _handler = new DeleteOrderCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _shipmentServiceMock.Object, _productServiceMock.Object, _inventoryManageServiceMock.Object,
+ _productReservationServiceMock.Object,
+ _auctionServiceMock.Object, _discountServiceMock.Object, _orderSettings);
+ }
- _handler = new DeleteOrderCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _shipmentServiceMock.Object, _productServiceMock.Object, _inventoryManageServiceMock.Object, _productReservationServiceMock.Object,
- _auctionServiceMock.Object, _discountServiceMock.Object, _orderSettings);
- }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new DeleteOrderCommand { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending } };
- _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new DeleteOrderCommand { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending } };
+ _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderItemCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderItemCommandHandlerTests.cs
index b13c91538..b5d2ec362 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderItemCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/DeleteOrderItemCommandHandlerTests.cs
@@ -11,44 +11,50 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class DeleteOrderItemCommandHandlerTests
{
- [TestClass()]
- public class DeleteOrderItemCommandHandlerTests
+ private Mock<IGiftVoucherService> _giftVoucherServiceMock;
+ private DeleteOrderItemCommandHandler _handler;
+ private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private DeleteOrderItemCommandHandler _handler;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IInventoryManageService> _inventoryManageServiceMock;
- private Mock<IGiftVoucherService> _giftVoucherServiceMock;
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _productServiceMock = new Mock<IProductService>();
+ _inventoryManageServiceMock = new Mock<IInventoryManageService>();
+ _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _productServiceMock = new Mock<IProductService>();
- _inventoryManageServiceMock = new Mock<IInventoryManageService>();
- _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
+ _handler = new DeleteOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _shipmentServiceMock.Object, _productServiceMock.Object,
+ _giftVoucherServiceMock.Object, _inventoryManageServiceMock.Object);
+ }
- _handler = new DeleteOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _shipmentServiceMock.Object, _productServiceMock.Object,
- _giftVoucherServiceMock.Object, _inventoryManageServiceMock.Object);
- }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new DeleteOrderItemCommand { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending }, OrderItem = new OrderItem { Quantity = 1, OpenQty = 1, Status = OrderItemStatus.Open } };
- _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
- _giftVoucherServiceMock.Setup(c => c.GetGiftVouchersByPurchasedWithOrderItemId(It.IsAny<string>())).ReturnsAsync(new List<GiftVoucher>());
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new DeleteOrderItemCommand {
+ Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending },
+ OrderItem = new OrderItem { Quantity = 1, OpenQty = 1, Status = OrderItemStatus.Open }
+ };
+ _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
+ _giftVoucherServiceMock.Setup(c => c.GetGiftVouchersByPurchasedWithOrderItemId(It.IsAny<string>()))
+ .ReturnsAsync(new List<GiftVoucher>());
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/InsertOrderItemCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/InsertOrderItemCommandHandlerTests.cs
index e6a10625e..cdbd26666 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/InsertOrderItemCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/InsertOrderItemCommandHandlerTests.cs
@@ -10,42 +10,47 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class InsertOrderItemCommandHandlerTests
{
- [TestClass()]
- public class InsertOrderItemCommandHandlerTests
+ private Mock<IGiftVoucherService> _giftVoucherServiceMock;
+ private InsertOrderItemCommandHandler _handler;
+ private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private InsertOrderItemCommandHandler _handler;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IInventoryManageService> _inventoryManageServiceMock;
- private Mock<IGiftVoucherService> _giftVoucherServiceMock;
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _productServiceMock = new Mock<IProductService>();
+ _inventoryManageServiceMock = new Mock<IInventoryManageService>();
+ _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _productServiceMock = new Mock<IProductService>();
- _inventoryManageServiceMock = new Mock<IInventoryManageService>();
- _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
+ _handler = new InsertOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _giftVoucherServiceMock.Object, _inventoryManageServiceMock.Object);
+ }
- _handler = new InsertOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
- _giftVoucherServiceMock.Object, _inventoryManageServiceMock.Object);
- }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new InsertOrderItemCommand { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending }, OrderItem = new OrderItem { Quantity = 1, OpenQty = 1, Status = OrderItemStatus.Open }, Product = new Product() };
- _giftVoucherServiceMock.Setup(c => c.GetGiftVouchersByPurchasedWithOrderItemId(It.IsAny<string>())).ReturnsAsync(new List<GiftVoucher>());
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new InsertOrderItemCommand {
+ Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending },
+ OrderItem = new OrderItem { Quantity = 1, OpenQty = 1, Status = OrderItemStatus.Open },
+ Product = new Product()
+ };
+ _giftVoucherServiceMock.Setup(c => c.GetGiftVouchersByPurchasedWithOrderItemId(It.IsAny<string>()))
+ .ReturnsAsync(new List<GiftVoucher>());
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandlerTests.cs
index b579591b2..f8a71c2d2 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandlerTests.cs
@@ -9,40 +9,40 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class MarkAsAuthorizedCommandHandlerTests
{
- [TestClass()]
- public class MarkAsAuthorizedCommandHandlerTests
- {
- private MarkAsAuthorizedCommandHandler _handler;
+ private MarkAsAuthorizedCommandHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
- _handler = new MarkAsAuthorizedCommandHandler(_orderServiceMock.Object, _paymentTransactionMock.Object, _mediatorMock.Object);
- }
+ _handler = new MarkAsAuthorizedCommandHandler(_orderServiceMock.Object, _paymentTransactionMock.Object,
+ _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new MarkAsAuthorizedCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanCaptureQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new MarkAsAuthorizedCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanCaptureQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsPaidCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsPaidCommandHandlerTests.cs
index ca552448d..f258fde11 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsPaidCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MarkAsPaidCommandHandlerTests.cs
@@ -9,43 +9,43 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class MarkAsPaidCommandHandlerTests
{
- [TestClass()]
- public class MarkAsPaidCommandHandlerTests
+ private MarkAsPaidCommandHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
+
+ [TestInitialize]
+ public void Init()
{
- private MarkAsPaidCommandHandler _handler;
-
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
-
- _handler = new MarkAsPaidCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _paymentTransactionMock.Object);
- }
-
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new MarkAsPaidCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanCaptureQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanMarkPaymentTransactionAsPaidQuery>(), default))
- .Returns(Task.FromResult(true));
-
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
-
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+
+ _handler = new MarkAsPaidCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _paymentTransactionMock.Object);
+ }
+
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new MarkAsPaidCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanCaptureQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanMarkPaymentTransactionAsPaidQuery>(), default))
+ .Returns(Task.FromResult(true));
+
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MaxOrderNumberCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MaxOrderNumberCommandHandlerTests.cs
index ba53ebaa5..0236efb2c 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MaxOrderNumberCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/MaxOrderNumberCommandHandlerTests.cs
@@ -1,31 +1,32 @@
using Grand.Business.Checkout.Commands.Handlers.Orders;
-using Grand.Data.Tests.MongoDb;
+using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class MaxOrderNumberCommandHandlerTests
{
- [TestClass()]
- public class MaxOrderNumberCommandHandlerTests
+ private MaxOrderNumberCommandHandler _handler;
+ private IRepository<Order> _repository;
+
+ [TestInitialize]
+ public void Init()
{
- private MaxOrderNumberCommandHandler _handler;
- private IRepository<Order> _repository;
- [TestInitialize]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Order>();
+ _repository = new MongoDBRepositoryTest<Order>();
- _handler = new MaxOrderNumberCommandHandler(_repository);
- }
+ _handler = new MaxOrderNumberCommandHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Act
- var result = await _handler.Handle(new Core.Commands.Checkout.Orders.MaxOrderNumberCommand { OrderNumber = 10 }, CancellationToken.None);
- //Assert
- Assert.AreEqual(10, result);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Act
+ var result = await _handler.Handle(new MaxOrderNumberCommand { OrderNumber = 10 }, CancellationToken.None);
+ //Assert
+ Assert.AreEqual(10, result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/OrderStatusCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/OrderStatusCommandHandlerTests.cs
index 04813f210..e120951bd 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/OrderStatusCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/OrderStatusCommandHandlerTests.cs
@@ -9,44 +9,47 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class OrderStatusCommandHandlerTests
{
- [TestClass()]
- public class OrderStatusCommandHandlerTests
+ private Mock<ICustomerService> _customerServiceMock;
+ private OrderStatusCommandHandler _handler;
+ private LoyaltyPointsSettings _loyaltyPointsSettings;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private OrderSettings _orderSettings;
+ private Mock<IPdfService> _pdfServiceMock;
+ private Mock<IVendorService> _vendorServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private OrderStatusCommandHandler _handler;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<IPdfService> _pdfServiceMock;
- private Mock<IMessageProviderService> _messageProviderServiceMock;
- private Mock<IVendorService> _vendorServiceMock;
- private LoyaltyPointsSettings _loyaltyPointsSettings;
- private OrderSettings _orderSettings;
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _customerServiceMock = new Mock<ICustomerService>();
+ _pdfServiceMock = new Mock<IPdfService>();
+ _messageProviderServiceMock = new Mock<IMessageProviderService>();
+ _vendorServiceMock = new Mock<IVendorService>();
+ _loyaltyPointsSettings = new LoyaltyPointsSettings();
+ _orderSettings = new OrderSettings();
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _customerServiceMock = new Mock<ICustomerService>();
- _pdfServiceMock = new Mock<IPdfService>();
- _messageProviderServiceMock = new Mock<IMessageProviderService>();
- _vendorServiceMock = new Mock<IVendorService>();
- _loyaltyPointsSettings = new LoyaltyPointsSettings();
- _orderSettings = new OrderSettings();
+ _handler = new OrderStatusCommandHandler(_orderServiceMock.Object, _customerServiceMock.Object,
+ _pdfServiceMock.Object, _messageProviderServiceMock.Object, _vendorServiceMock.Object, _mediatorMock.Object,
+ _orderSettings, _loyaltyPointsSettings);
+ }
- _handler = new OrderStatusCommandHandler(_orderServiceMock.Object, _customerServiceMock.Object, _pdfServiceMock.Object, _messageProviderServiceMock.Object, _vendorServiceMock.Object, _mediatorMock.Object, _orderSettings, _loyaltyPointsSettings);
- }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new SetOrderStatusCommand { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending }, Os = OrderStatusSystem.Complete };
- //Act
- await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new SetOrderStatusCommand
+ { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending }, Os = OrderStatusSystem.Complete };
+ //Act
+ await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandlerTests.cs
index 3a622ad24..9e1dad389 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandlerTests.cs
@@ -9,40 +9,40 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class PartiallyPaidOfflineCommandHandlerTests
{
- [TestClass()]
- public class PartiallyPaidOfflineCommandHandlerTests
- {
- private PartiallyPaidOfflineCommandHandler _handler;
+ private PartiallyPaidOfflineCommandHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
- _handler = new PartiallyPaidOfflineCommandHandler(_orderServiceMock.Object, _paymentTransactionMock.Object, _mediatorMock.Object);
- }
+ _handler = new PartiallyPaidOfflineCommandHandler(_orderServiceMock.Object, _paymentTransactionMock.Object,
+ _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new PartiallyPaidOfflineCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyPaidOfflineQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new PartiallyPaidOfflineCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyPaidOfflineQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs
index 708d38b65..86d9b5b27 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundCommandHandlerTests.cs
@@ -5,6 +5,7 @@ using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Business.Core.Utilities.Checkout;
+using Grand.Domain.Localization;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
@@ -12,47 +13,50 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class PartiallyRefundCommandHandlerTests
{
- [TestClass()]
- public class PartiallyRefundCommandHandlerTests
- {
- private PartiallyRefundCommandHandler _handler;
- private Mock<IPaymentService> _paymentServiceMock;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IMessageProviderService> _messageProviderServiceMock;
- private Mock<ILogger<PartiallyRefundCommandHandler>> _loggerMock;
+ private PartiallyRefundCommandHandler _handler;
+ private Mock<ILogger<PartiallyRefundCommandHandler>> _loggerMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IPaymentService> _paymentServiceMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
- _messageProviderServiceMock = new Mock<IMessageProviderService>();
- _paymentServiceMock = new Mock<IPaymentService>();
- _loggerMock = new Mock<ILogger<PartiallyRefundCommandHandler>>();
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+ _messageProviderServiceMock = new Mock<IMessageProviderService>();
+ _paymentServiceMock = new Mock<IPaymentService>();
+ _loggerMock = new Mock<ILogger<PartiallyRefundCommandHandler>>();
- _handler = new PartiallyRefundCommandHandler(_paymentServiceMock.Object, _paymentTransactionMock.Object, _mediatorMock.Object, _messageProviderServiceMock.Object, _loggerMock.Object, _orderServiceMock.Object, new Domain.Localization.LanguageSettings());
- }
+ _handler = new PartiallyRefundCommandHandler(_paymentServiceMock.Object, _paymentTransactionMock.Object,
+ _mediatorMock.Object, _messageProviderServiceMock.Object, _loggerMock.Object, _orderServiceMock.Object,
+ new LanguageSettings());
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new PartiallyRefundCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyRefundQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- _paymentServiceMock.Setup(x => x.Refund(It.IsAny<RefundPaymentRequest>())).Returns(Task.FromResult(new RefundPaymentResult { NewTransactionStatus = TransactionStatus.Refunded }));
- _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>())).Returns(Task.FromResult(new PaymentTransaction()));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new PartiallyRefundCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyRefundQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ _paymentServiceMock.Setup(x => x.Refund(It.IsAny<RefundPaymentRequest>())).Returns(
+ Task.FromResult(new RefundPaymentResult { NewTransactionStatus = TransactionStatus.Refunded }));
+ _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new PaymentTransaction()));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandlerTests.cs
index a0a8ae8b3..8405cc64b 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandlerTests.cs
@@ -4,48 +4,50 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Queries.Checkout.Orders;
+using Grand.Domain.Localization;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class PartiallyRefundOfflineCommandHandlerTests
{
- [TestClass()]
- public class PartiallyRefundOfflineCommandHandlerTests
- {
- private PartiallyRefundOfflineCommandHandler _handler;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private PartiallyRefundOfflineCommandHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
- _messageProviderServiceMock = new Mock<IMessageProviderService>();
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+ _messageProviderServiceMock = new Mock<IMessageProviderService>();
- _handler = new PartiallyRefundOfflineCommandHandler(_orderServiceMock.Object, _paymentTransactionMock.Object, _mediatorMock.Object, _messageProviderServiceMock.Object, new Domain.Localization.LanguageSettings());
- }
+ _handler = new PartiallyRefundOfflineCommandHandler(_orderServiceMock.Object, _paymentTransactionMock.Object,
+ _mediatorMock.Object, _messageProviderServiceMock.Object, new LanguageSettings());
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new PartiallyRefundOfflineCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyRefundOfflineQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>())).Returns(Task.FromResult(new PaymentTransaction()));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new PartiallyRefundOfflineCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyRefundOfflineQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new PaymentTransaction()));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PrepareOrderCodeCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PrepareOrderCodeCommandHandlerTests.cs
index 4e6c1a063..4d3a7fc58 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PrepareOrderCodeCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PrepareOrderCodeCommandHandlerTests.cs
@@ -1,27 +1,28 @@
using Grand.Business.Checkout.Commands.Handlers.Orders;
+using Grand.Business.Core.Commands.Checkout.Orders;
+using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class PrepareOrderCodeCommandHandlerTests
{
- [TestClass()]
- public class PrepareOrderCodeCommandHandlerTests
- {
- private PrepareOrderCodeCommandHandler _handler;
- const int LengthCode = 6;
+ private const int LengthCode = 6;
+ private PrepareOrderCodeCommandHandler _handler;
- [TestInitialize]
- public void Init()
- {
- _handler = new PrepareOrderCodeCommandHandler(new Domain.Orders.OrderSettings { LengthCode = LengthCode });
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _handler = new PrepareOrderCodeCommandHandler(new OrderSettings { LengthCode = LengthCode });
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Act
- var result = await _handler.Handle(new Core.Commands.Checkout.Orders.PrepareOrderCodeCommand(), CancellationToken.None);
- //Assert
- Assert.AreEqual(LengthCode, result.Length);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Act
+ var result = await _handler.Handle(new PrepareOrderCodeCommand(), CancellationToken.None);
+ //Assert
+ Assert.AreEqual(LengthCode, result.Length);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandlerTests.cs
index 572044984..c642699f6 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandlerTests.cs
@@ -6,57 +6,65 @@ using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Customers;
using Grand.Domain.Directory;
+using Grand.Domain.Orders;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class ReduceLoyaltyPointsCommandHandlerTests
{
- [TestClass()]
- public class ReduceLoyaltyPointsCommandHandlerTests
+ private Mock<ICurrencyService> _currencyServiceMock;
+ private Mock<ICustomerService> _customerServiceMock;
+ private ReduceLoyaltyPointsCommandHandler _handler;
+ private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<ITranslationService> _translationServiceMock;
+
+
+ [TestInitialize]
+ public void Init()
+ {
+ _customerServiceMock = new Mock<ICustomerService>();
+ _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
+ _mediatorMock = new Mock<IMediator>();
+ _currencyServiceMock = new Mock<ICurrencyService>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+
+ _handler = new ReduceLoyaltyPointsCommandHandler(_customerServiceMock.Object, _loyaltyPointsServiceMock.Object,
+ _mediatorMock.Object, _orderServiceMock.Object, _translationServiceMock.Object,
+ _currencyServiceMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task HandleTest()
{
- private ReduceLoyaltyPointsCommandHandler _handler;
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<ITranslationService> _translationServiceMock;
- private Mock<ICurrencyService> _currencyServiceMock;
-
-
- [TestInitialize]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
- _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
- _mediatorMock = new Mock<IMediator>();
- _currencyServiceMock = new Mock<ICurrencyService>();
- _orderServiceMock = new Mock<IOrderService>();
- _translationServiceMock = new Mock<ITranslationService>();
-
- _handler = new ReduceLoyaltyPointsCommandHandler(_customerServiceMock.Object, _loyaltyPointsServiceMock.Object, _mediatorMock.Object, _orderServiceMock.Object, _translationServiceMock.Object, _currencyServiceMock.Object);
- }
-
-
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new ReduceLoyaltyPointsCommand {
- Order = new Domain.Orders.Order { StoreId = "", OrderNumber = 1, CalcLoyaltyPoints = 100 }
- };
- var expectedCustomer = new Customer { Username = "John", Active = true };
- _customerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>())).Returns(() => Task.FromResult(expectedCustomer));
- _currencyServiceMock.Setup(c => c.GetCurrencyByCode(It.IsAny<string>())).Returns(() => Task.FromResult(new Domain.Directory.Currency()));
- _currencyServiceMock.Setup(c => c.ConvertToPrimaryStoreCurrency(100, It.IsAny<Currency>())).Returns(() => Task.FromResult((double)100));
- _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
- _mediatorMock.Setup(x => x.Send(It.IsAny<CalculateLoyaltyPointsCommand>(), default)).Returns(Task.FromResult(100));
-
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
-
- //Assert
- _loyaltyPointsServiceMock.Verify(c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.Is<int>(g => g <0), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Once);
- }
+ //Arrange
+ var command = new ReduceLoyaltyPointsCommand {
+ Order = new Order { StoreId = "", OrderNumber = 1, CalcLoyaltyPoints = 100 }
+ };
+ var expectedCustomer = new Customer { Username = "John", Active = true };
+ _customerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(expectedCustomer));
+ _currencyServiceMock.Setup(c => c.GetCurrencyByCode(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Currency()));
+ _currencyServiceMock.Setup(c => c.ConvertToPrimaryStoreCurrency(100, It.IsAny<Currency>()))
+ .Returns(() => Task.FromResult((double)100));
+ _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CalculateLoyaltyPointsCommand>(), default))
+ .Returns(Task.FromResult(100));
+
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+
+ //Assert
+ _loyaltyPointsServiceMock.Verify(
+ c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.Is<int>(g => g < 0), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs
index 4c6a7ffd7..b18a85f07 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/RefundCommandHandlerTests.cs
@@ -5,6 +5,7 @@ using Grand.Business.Core.Interfaces.Checkout.Payments;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Queries.Checkout.Orders;
using Grand.Business.Core.Utilities.Checkout;
+using Grand.Domain.Localization;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
using MediatR;
@@ -12,47 +13,50 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class RefundCommandHandlerTests
{
- [TestClass()]
- public class RefundCommandHandlerTests
- {
- private RefundCommandHandler _handler;
- private Mock<IPaymentService> _paymentServiceMock;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IMessageProviderService> _messageProviderServiceMock;
- private Mock<ILogger<RefundCommandHandler>> _loggerMock;
+ private RefundCommandHandler _handler;
+ private Mock<ILogger<RefundCommandHandler>> _loggerMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IPaymentService> _paymentServiceMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
- _messageProviderServiceMock = new Mock<IMessageProviderService>();
- _paymentServiceMock = new Mock<IPaymentService>();
- _loggerMock = new Mock<ILogger<RefundCommandHandler>>();
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+ _messageProviderServiceMock = new Mock<IMessageProviderService>();
+ _paymentServiceMock = new Mock<IPaymentService>();
+ _loggerMock = new Mock<ILogger<RefundCommandHandler>>();
- _handler = new RefundCommandHandler(_mediatorMock.Object, _paymentServiceMock.Object, _paymentTransactionMock.Object, _orderServiceMock.Object, _messageProviderServiceMock.Object, _loggerMock.Object, new Domain.Localization.LanguageSettings());
- }
+ _handler = new RefundCommandHandler(_mediatorMock.Object, _paymentServiceMock.Object,
+ _paymentTransactionMock.Object, _orderServiceMock.Object, _messageProviderServiceMock.Object,
+ _loggerMock.Object, new LanguageSettings());
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new RefundCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyRefundQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- _paymentServiceMock.Setup(x => x.Refund(It.IsAny<RefundPaymentRequest>())).Returns(Task.FromResult(new RefundPaymentResult { NewTransactionStatus = TransactionStatus.Refunded }));
- _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>())).Returns(Task.FromResult(new PaymentTransaction()));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new RefundCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanPartiallyRefundQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ _paymentServiceMock.Setup(x => x.Refund(It.IsAny<RefundPaymentRequest>())).Returns(
+ Task.FromResult(new RefundPaymentResult { NewTransactionStatus = TransactionStatus.Refunded }));
+ _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new PaymentTransaction()));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs
index 90632a099..062a4b373 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs
@@ -1,39 +1,42 @@
using Grand.Business.Checkout.Commands.Handlers.Orders;
+using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
-{
- [TestClass()]
- public class ReturnBackRedeemedLoyaltyPointsCommandHandlerTests
- {
- private ReturnBackRedeemedLoyaltyPointsCommandHandler _handler;
- private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
- private Mock<ITranslationService> _translationServiceMock;
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
- [TestInitialize]
- public void Init()
- {
- _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
- _translationServiceMock = new Mock<ITranslationService>();
- _handler = new ReturnBackRedeemedLoyaltyPointsCommandHandler(_loyaltyPointsServiceMock.Object, _translationServiceMock.Object);
- }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new Core.Commands.Checkout.Orders.ReturnBackRedeemedLoyaltyPointsCommand {
- Order = new Domain.Orders.Order { RedeemedLoyaltyPoints = 10 }
- };
- _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
- //Act
- await _handler.Handle(command, CancellationToken.None);
+[TestClass]
+public class ReturnBackRedeemedLoyaltyPointsCommandHandlerTests
+{
+ private ReturnBackRedeemedLoyaltyPointsCommandHandler _handler;
+ private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private Mock<ITranslationService> _translationServiceMock;
- _loyaltyPointsServiceMock.Verify(c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.Is<int>(g => g < 0), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Once);
+ [TestInitialize]
+ public void Init()
+ {
+ _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _handler = new ReturnBackRedeemedLoyaltyPointsCommandHandler(_loyaltyPointsServiceMock.Object,
+ _translationServiceMock.Object);
+ }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new ReturnBackRedeemedLoyaltyPointsCommand {
+ Order = new Order { RedeemedLoyaltyPoints = 10 }
+ };
+ _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
+ //Act
+ await _handler.Handle(command, CancellationToken.None);
- }
+ _loyaltyPointsServiceMock.Verify(
+ c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.Is<int>(g => g < 0), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/UpdateOrderItemCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/UpdateOrderItemCommandHandlerTests.cs
index eaee22520..770a5a5f6 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/UpdateOrderItemCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/UpdateOrderItemCommandHandlerTests.cs
@@ -11,49 +11,52 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class UpdateOrderItemCommandHandlerTests
{
- [TestClass()]
- public class UpdateOrderItemCommandHandlerTests
+ private Mock<IGiftVoucherService> _giftVoucherServiceMock;
+ private UpdateOrderItemCommandHandler _handler;
+ private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private UpdateOrderItemCommandHandler _handler;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IInventoryManageService> _inventoryManageServiceMock;
- private Mock<IGiftVoucherService> _giftVoucherServiceMock;
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _productServiceMock = new Mock<IProductService>();
+ _inventoryManageServiceMock = new Mock<IInventoryManageService>();
+ _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _productServiceMock = new Mock<IProductService>();
- _inventoryManageServiceMock = new Mock<IInventoryManageService>();
- _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
+ _handler = new UpdateOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _shipmentServiceMock.Object, _productServiceMock.Object,
+ _inventoryManageServiceMock.Object);
+ }
- _handler = new UpdateOrderItemCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _shipmentServiceMock.Object, _productServiceMock.Object,
- _inventoryManageServiceMock.Object);
- }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending };
- var orderItem = new OrderItem();
- order.OrderItems.Add(orderItem);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending };
+ var orderItem = new OrderItem();
+ order.OrderItems.Add(orderItem);
- var command = new UpdateOrderItemCommand { Order = order, OrderItem = orderItem };
- _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(order));
- _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
- _giftVoucherServiceMock.Setup(c => c.GetGiftVouchersByPurchasedWithOrderItemId(It.IsAny<string>())).ReturnsAsync(new List<GiftVoucher>());
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ var command = new UpdateOrderItemCommand { Order = order, OrderItem = orderItem };
+ _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(order));
+ _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder(It.IsAny<string>())).ReturnsAsync(new List<Shipment>());
+ _giftVoucherServiceMock.Setup(c => c.GetGiftVouchersByPurchasedWithOrderItemId(It.IsAny<string>()))
+ .ReturnsAsync(new List<GiftVoucher>());
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "2", Published = true, Price = 10 }));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandlerTests.cs
index 0489b5d5a..af4fcde67 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandlerTests.cs
@@ -1,42 +1,47 @@
using Grand.Business.Checkout.Commands.Handlers.Orders;
+using Grand.Business.Core.Commands.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Utilities.Catalog;
+using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class ValidateMinShoppingCartSubtotalAmountCommandHandlerTests
{
- [TestClass()]
- public class ValidateMinShoppingCartSubtotalAmountCommandHandlerTests
- {
- private ValidateMinShoppingCartSubtotalAmountCommandHandler _handler;
- private Mock<IOrderCalculationService> _orderTotalCalculationServiceMock;
- private OrderSettings _orderSettings;
+ private ValidateMinShoppingCartSubtotalAmountCommandHandler _handler;
+ private OrderSettings _orderSettings;
+ private Mock<IOrderCalculationService> _orderTotalCalculationServiceMock;
- [TestInitialize]
- public void Init()
- {
- _orderTotalCalculationServiceMock = new Mock<IOrderCalculationService>();
- _orderSettings = new OrderSettings { MinOrderSubtotalAmount = 10};
- _handler = new ValidateMinShoppingCartSubtotalAmountCommandHandler(_orderTotalCalculationServiceMock.Object, _orderSettings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _orderTotalCalculationServiceMock = new Mock<IOrderCalculationService>();
+ _orderSettings = new OrderSettings { MinOrderSubtotalAmount = 10 };
+ _handler = new ValidateMinShoppingCartSubtotalAmountCommandHandler(_orderTotalCalculationServiceMock.Object,
+ _orderSettings);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- var command = new Core.Commands.Checkout.Orders.ValidateMinShoppingCartSubtotalAmountCommand
- {
- Customer = new Domain.Customers.Customer(),
- Cart = new List<ShoppingCartItem> { new ShoppingCartItem() }
- };
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ var command = new ValidateMinShoppingCartSubtotalAmountCommand {
+ Customer = new Customer(),
+ Cart = new List<ShoppingCartItem> { new() }
+ };
- _orderTotalCalculationServiceMock.Setup(x => x.GetShoppingCartSubTotal(It.IsAny<IList<ShoppingCartItem>>(), false)).Returns(() => Task.FromResult<(double discountAmount, List<ApplyDiscount> appliedDiscounts, double subTotalWithoutDiscount, double subTotalWithDiscount, SortedDictionary<double, double> taxRates)>((20,null, 100,100,null)));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
+ _orderTotalCalculationServiceMock
+ .Setup(x => x.GetShoppingCartSubTotal(It.IsAny<IList<ShoppingCartItem>>(), false)).Returns(() =>
+ Task.FromResult<(double discountAmount, List<ApplyDiscount> appliedDiscounts, double
+ subTotalWithoutDiscount, double subTotalWithDiscount, SortedDictionary<double, double> taxRates)>((
+ 20, null, 100, 100, null)));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs
index 4d6dbd9fc..4fcf142cb 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidCommandHandlerTests.cs
@@ -12,49 +12,50 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class VoidCommandHandlerTests
{
- [TestClass()]
- public class VoidCommandHandlerTests
- {
- private VoidCommandHandler _handler;
- private Mock<IPaymentService> _paymentServiceMock;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IMessageProviderService> _messageProviderServiceMock;
- private Mock<ILogger<VoidCommandHandler>> _loggerMock;
+ private VoidCommandHandler _handler;
+ private Mock<ILogger<VoidCommandHandler>> _loggerMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IPaymentService> _paymentServiceMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
- _messageProviderServiceMock = new Mock<IMessageProviderService>();
- _paymentServiceMock = new Mock<IPaymentService>();
- _loggerMock = new Mock<ILogger<VoidCommandHandler>>();
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+ _messageProviderServiceMock = new Mock<IMessageProviderService>();
+ _paymentServiceMock = new Mock<IPaymentService>();
+ _loggerMock = new Mock<ILogger<VoidCommandHandler>>();
- _handler = new VoidCommandHandler(
- _orderServiceMock.Object,
- _mediatorMock.Object, _paymentServiceMock.Object, _paymentTransactionMock.Object, _loggerMock.Object);
- }
+ _handler = new VoidCommandHandler(
+ _orderServiceMock.Object,
+ _mediatorMock.Object, _paymentServiceMock.Object, _paymentTransactionMock.Object, _loggerMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new VoidCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanVoidQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- _paymentServiceMock.Setup(x => x.Void(It.IsAny<PaymentTransaction>())).Returns(Task.FromResult(new VoidPaymentResult { NewTransactionStatus = TransactionStatus.Voided }));
- _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>())).Returns(Task.FromResult(new PaymentTransaction()));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new VoidCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanVoidQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ _paymentServiceMock.Setup(x => x.Void(It.IsAny<PaymentTransaction>())).Returns(
+ Task.FromResult(new VoidPaymentResult { NewTransactionStatus = TransactionStatus.Voided }));
+ _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new PaymentTransaction()));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidOfflineCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidOfflineCommandHandlerTests.cs
index 070cfeb1f..12d019fd7 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidOfflineCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/VoidOfflineCommandHandlerTests.cs
@@ -10,45 +10,46 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Orders;
+
+[TestClass]
+public class VoidOfflineCommandHandlerTests
{
- [TestClass()]
- public class VoidOfflineCommandHandlerTests
- {
- private VoidOfflineCommandHandler _handler;
- private Mock<IPaymentService> _paymentServiceMock;
- private Mock<IPaymentTransactionService> _paymentTransactionMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IMediator> _mediatorMock;
+ private VoidOfflineCommandHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IPaymentService> _paymentServiceMock;
+ private Mock<IPaymentTransactionService> _paymentTransactionMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _paymentTransactionMock = new Mock<IPaymentTransactionService>();
- _paymentServiceMock = new Mock<IPaymentService>();
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _paymentTransactionMock = new Mock<IPaymentTransactionService>();
+ _paymentServiceMock = new Mock<IPaymentService>();
- _handler = new VoidOfflineCommandHandler(
- _orderServiceMock.Object, _paymentTransactionMock.Object,
- _mediatorMock.Object);
- }
+ _handler = new VoidOfflineCommandHandler(
+ _orderServiceMock.Object, _paymentTransactionMock.Object,
+ _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var command = new VoidOfflineCommand { PaymentTransaction = new PaymentTransaction() };
- _mediatorMock.Setup(x => x.Send(It.IsAny<CanVoidOfflineQuery>(), default))
- .Returns(Task.FromResult(true));
- _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
- _paymentServiceMock.Setup(x => x.Void(It.IsAny<PaymentTransaction>())).Returns(Task.FromResult(new VoidPaymentResult { NewTransactionStatus = TransactionStatus.Voided }));
- _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>())).Returns(Task.FromResult(new PaymentTransaction()));
- //Act
- var result = await _handler.Handle(command, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var command = new VoidOfflineCommand { PaymentTransaction = new PaymentTransaction() };
+ _mediatorMock.Setup(x => x.Send(It.IsAny<CanVoidOfflineQuery>(), default))
+ .Returns(Task.FromResult(true));
+ _orderServiceMock.Setup(x => x.GetOrderByGuid(It.IsAny<Guid>())).Returns(Task.FromResult(new Order()));
+ _paymentServiceMock.Setup(x => x.Void(It.IsAny<PaymentTransaction>())).Returns(
+ Task.FromResult(new VoidPaymentResult { NewTransactionStatus = TransactionStatus.Voided }));
+ _paymentTransactionMock.Setup(x => x.GetById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new PaymentTransaction()));
+ //Act
+ var result = await _handler.Handle(command, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
+ _paymentTransactionMock.Verify(c => c.UpdatePaymentTransaction(It.IsAny<PaymentTransaction>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/DeliveryCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/DeliveryCommandHandlerTests.cs
index e87ea5d2b..c1370f3b5 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/DeliveryCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/DeliveryCommandHandlerTests.cs
@@ -1,4 +1,5 @@
using Grand.Business.Checkout.Commands.Handlers.Shipping;
+using Grand.Business.Core.Commands.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Messages;
@@ -8,38 +9,41 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Shipping
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Shipping;
+
+[TestClass]
+public class DeliveryCommandHandlerTests
{
- [TestClass()]
- public class DeliveryCommandHandlerTests
+ private DeliveryCommandHandler _deliveryCommandHandler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IShipmentService> _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private DeliveryCommandHandler _deliveryCommandHandler;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IMessageProviderService> _messageProviderServiceMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _messageProviderServiceMock = new Mock<IMessageProviderService>();
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _messageProviderServiceMock = new Mock<IMessageProviderService>();
- _deliveryCommandHandler = new DeliveryCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _shipmentServiceMock.Object, _messageProviderServiceMock.Object);
- }
+ _deliveryCommandHandler = new DeliveryCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _shipmentServiceMock.Object, _messageProviderServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
- _shipmentServiceMock.Setup(x => x.GetShipmentsByOrder(It.IsAny<string>())).Returns(Task.FromResult((IList<Shipment>)new List<Shipment>()));
- var deliveryCommand = new Core.Commands.Checkout.Shipping.DeliveryCommand { NotifyCustomer = true, Shipment = new Domain.Shipping.Shipment { ShippedDateUtc = DateTime.Now } };
- //Act
- var result = await _deliveryCommandHandler.Handle(deliveryCommand, CancellationToken.None);
- //Assert
- _shipmentServiceMock.Verify(c => c.UpdateShipment(It.IsAny<Shipment>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
+ _shipmentServiceMock.Setup(x => x.GetShipmentsByOrder(It.IsAny<string>()))
+ .Returns(Task.FromResult((IList<Shipment>)new List<Shipment>()));
+ var deliveryCommand = new DeliveryCommand
+ { NotifyCustomer = true, Shipment = new Shipment { ShippedDateUtc = DateTime.Now } };
+ //Act
+ var result = await _deliveryCommandHandler.Handle(deliveryCommand, CancellationToken.None);
+ //Assert
+ _shipmentServiceMock.Verify(c => c.UpdateShipment(It.IsAny<Shipment>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/ShipCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/ShipCommandHandlerTests.cs
index a7702730f..20e61309e 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/ShipCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Shipping/ShipCommandHandlerTests.cs
@@ -1,4 +1,5 @@
using Grand.Business.Checkout.Commands.Handlers.Shipping;
+using Grand.Business.Core.Commands.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Messages;
@@ -8,38 +9,40 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Commands.Handlers.Shipping
+namespace Grand.Business.Checkout.Tests.Commands.Handlers.Shipping;
+
+[TestClass]
+public class ShipCommandHandlerTests
{
- [TestClass()]
- public class ShipCommandHandlerTests
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IMessageProviderService> _messageProviderServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private ShipCommandHandler _shipCommandHandler;
+ private Mock<IShipmentService> _shipmentServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private ShipCommandHandler _shipCommandHandler;
- private Mock<IMediator> _mediatorMock;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IMessageProviderService> _messageProviderServiceMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _messageProviderServiceMock = new Mock<IMessageProviderService>();
+ _mediatorMock = new Mock<IMediator>();
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _messageProviderServiceMock = new Mock<IMessageProviderService>();
- _shipCommandHandler = new ShipCommandHandler(_mediatorMock.Object, _orderServiceMock.Object, _shipmentServiceMock.Object, _messageProviderServiceMock.Object);
- }
+ _shipCommandHandler = new ShipCommandHandler(_mediatorMock.Object, _orderServiceMock.Object,
+ _shipmentServiceMock.Object, _messageProviderServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
- _shipmentServiceMock.Setup(x => x.GetShipmentsByOrder(It.IsAny<string>())).Returns(Task.FromResult((IList<Shipment>)new List<Shipment>()));
- var shipCommand = new Core.Commands.Checkout.Shipping.ShipCommand { NotifyCustomer = true, Shipment = new Domain.Shipping.Shipment { } };
- //Act
- var result = await _shipCommandHandler.Handle(shipCommand, CancellationToken.None);
- //Assert
- _shipmentServiceMock.Verify(c => c.UpdateShipment(It.IsAny<Shipment>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
+ _shipmentServiceMock.Setup(x => x.GetShipmentsByOrder(It.IsAny<string>()))
+ .Returns(Task.FromResult((IList<Shipment>)new List<Shipment>()));
+ var shipCommand = new ShipCommand { NotifyCustomer = true, Shipment = new Shipment() };
+ //Act
+ var result = await _shipCommandHandler.Handle(shipCommand, CancellationToken.None);
+ //Assert
+ _shipmentServiceMock.Verify(c => c.UpdateShipment(It.IsAny<Shipment>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Customers/CustomerRegisteredEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Customers/CustomerRegisteredEventHandlerTests.cs
index 7d2c6fa36..12049d0a5 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/Customers/CustomerRegisteredEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Customers/CustomerRegisteredEventHandlerTests.cs
@@ -1,43 +1,54 @@
using Grand.Business.Checkout.Events.Customers;
+using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Domain.Customers;
+using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.Customers
+namespace Grand.Business.Checkout.Tests.Events.Customers;
+
+[TestClass]
+public class CustomerRegisteredEventHandlerTests
{
- [TestClass()]
- public class CustomerRegisteredEventHandlerTests
+ private CustomerRegisteredEventHandler _customerRegisteredEventHandler;
+ private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private LoyaltyPointsSettings _loyaltyPointsSettings;
+
+ [TestInitialize]
+ public void Init()
{
- CustomerRegisteredEventHandler _customerRegisteredEventHandler;
- private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
- private Domain.Orders.LoyaltyPointsSettings _loyaltyPointsSettings;
- [TestInitialize()]
- public void Init()
- {
- var translationServiceMock = new Mock<ITranslationService>();
- translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
- _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
- _loyaltyPointsSettings = new Domain.Orders.LoyaltyPointsSettings { Enabled = true, PointsForRegistration = 10 };
- _customerRegisteredEventHandler = new CustomerRegisteredEventHandler(translationServiceMock.Object, _loyaltyPointsServiceMock.Object, _loyaltyPointsSettings);
- }
+ var translationServiceMock = new Mock<ITranslationService>();
+ translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
+ _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
+ _loyaltyPointsSettings = new LoyaltyPointsSettings { Enabled = true, PointsForRegistration = 10 };
+ _customerRegisteredEventHandler = new CustomerRegisteredEventHandler(translationServiceMock.Object,
+ _loyaltyPointsServiceMock.Object, _loyaltyPointsSettings);
+ }
- [TestMethod()]
- public async Task HandleTest_LoyaltyPointsSettings_Enabled()
- {
- //Act
- await _customerRegisteredEventHandler.Handle(new Core.Events.Customers.CustomerRegisteredEvent(new Domain.Customers.Customer()), CancellationToken.None);
- //Assert
- _loyaltyPointsServiceMock.Verify(c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Once);
- }
- [TestMethod()]
- public async Task HandleTest_LoyaltyPointsSettings_Disabled()
- {
- _loyaltyPointsSettings.Enabled = false;
- //Act
- await _customerRegisteredEventHandler.Handle(new Core.Events.Customers.CustomerRegisteredEvent(new Domain.Customers.Customer()), CancellationToken.None);
- //Assert
- _loyaltyPointsServiceMock.Verify(c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Never);
- }
+ [TestMethod]
+ public async Task HandleTest_LoyaltyPointsSettings_Enabled()
+ {
+ //Act
+ await _customerRegisteredEventHandler.Handle(new CustomerRegisteredEvent(new Customer()),
+ CancellationToken.None);
+ //Assert
+ _loyaltyPointsServiceMock.Verify(
+ c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<double>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task HandleTest_LoyaltyPointsSettings_Disabled()
+ {
+ _loyaltyPointsSettings.Enabled = false;
+ //Act
+ await _customerRegisteredEventHandler.Handle(new CustomerRegisteredEvent(new Customer()),
+ CancellationToken.None);
+ //Assert
+ _loyaltyPointsServiceMock.Verify(
+ c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<double>()), Times.Never);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnDeletedEventHandlerTests.cs
index 2c3ab3984..5746efd92 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnDeletedEventHandlerTests.cs
@@ -1,34 +1,34 @@
using Grand.Business.Checkout.Events.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Domain.Orders;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.Orders
+namespace Grand.Business.Checkout.Tests.Events.Orders;
+
+[TestClass]
+public class MerchandiseReturnDeletedEventHandlerTests
{
- [TestClass()]
- public class MerchandiseReturnDeletedEventHandlerTests
- {
- private MerchandiseReturnDeletedEventHandler _merchandiseReturnDeletedEventHandler;
- private Mock<IOrderService> _orderServiceMock;
+ private MerchandiseReturnDeletedEventHandler _merchandiseReturnDeletedEventHandler;
+ private Mock<IOrderService> _orderServiceMock;
- [TestInitialize()]
- public void Init()
- {
- _orderServiceMock = new Mock<IOrderService>();
- _merchandiseReturnDeletedEventHandler = new MerchandiseReturnDeletedEventHandler(_orderServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _orderServiceMock = new Mock<IOrderService>();
+ _merchandiseReturnDeletedEventHandler = new MerchandiseReturnDeletedEventHandler(_orderServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
- var notification = new Infrastructure.Events.EntityDeleted<MerchandiseReturn>(new MerchandiseReturn());
- //Act
- await _merchandiseReturnDeletedEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
+ var notification = new EntityDeleted<MerchandiseReturn>(new MerchandiseReturn());
+ //Act
+ await _merchandiseReturnDeletedEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnInsertEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnInsertEventHandlerTests.cs
index 99fdce254..6adf8acae 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnInsertEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/MerchandiseReturnInsertEventHandlerTests.cs
@@ -1,34 +1,34 @@
using Grand.Business.Checkout.Events.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Domain.Orders;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.Orders
+namespace Grand.Business.Checkout.Tests.Events.Orders;
+
+[TestClass]
+public class MerchandiseReturnInsertEventHandlerTests
{
- [TestClass()]
- public class MerchandiseReturnInsertEventHandlerTests
- {
- private MerchandiseReturnInsertEventHandler _merchandiseReturnInsertEventHandler;
- private Mock<IOrderService> _orderServiceMock;
+ private MerchandiseReturnInsertEventHandler _merchandiseReturnInsertEventHandler;
+ private Mock<IOrderService> _orderServiceMock;
- [TestInitialize()]
- public void Init()
- {
- _orderServiceMock = new Mock<IOrderService>();
- _merchandiseReturnInsertEventHandler = new MerchandiseReturnInsertEventHandler(_orderServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _orderServiceMock = new Mock<IOrderService>();
+ _merchandiseReturnInsertEventHandler = new MerchandiseReturnInsertEventHandler(_orderServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
- var notification = new Infrastructure.Events.EntityInserted<MerchandiseReturn>(new MerchandiseReturn());
- //Act
- await _merchandiseReturnInsertEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(new Order()));
+ var notification = new EntityInserted<MerchandiseReturn>(new MerchandiseReturn());
+ //Act
+ await _merchandiseReturnInsertEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderDeletedEventHandlerTests.cs
index f1a9f8b40..796b171b2 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderDeletedEventHandlerTests.cs
@@ -1,35 +1,36 @@
using Grand.Business.Checkout.Events.Orders;
using Grand.Business.Core.Events.Checkout.Orders;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
+using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.Orders
+namespace Grand.Business.Checkout.Tests.Events.Orders;
+
+[TestClass]
+public class OrderDeletedEventHandlerTests
{
- [TestClass()]
- public class OrderDeletedEventHandlerTests
- {
- private OrderDeletedEventHandler _orderDeletedEventHandler;
- private Mock<IRepository<ProductAlsoPurchased>> _productAlsoPurchasedRepository;
+ private OrderDeletedEventHandler _orderDeletedEventHandler;
+ private Mock<IRepository<ProductAlsoPurchased>> _productAlsoPurchasedRepository;
- [TestInitialize()]
- public void Init()
- {
- _productAlsoPurchasedRepository = new Mock<IRepository<ProductAlsoPurchased>>();
- _orderDeletedEventHandler = new OrderDeletedEventHandler(_productAlsoPurchasedRepository.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _productAlsoPurchasedRepository = new Mock<IRepository<ProductAlsoPurchased>>();
+ _orderDeletedEventHandler = new OrderDeletedEventHandler(_productAlsoPurchasedRepository.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var order = new Domain.Orders.Order();
- var notification = new OrderDeletedEvent(order);
- //Act
- await _orderDeletedEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _productAlsoPurchasedRepository.Verify(c => c.DeleteManyAsync(x => x.OrderId == notification.Order.Id), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var order = new Order();
+ var notification = new OrderDeletedEvent(order);
+ //Act
+ await _orderDeletedEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _productAlsoPurchasedRepository.Verify(c => c.DeleteManyAsync(x => x.OrderId == notification.Order.Id),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderPlacedEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderPlacedEventHandlerTests.cs
index 475e34e4a..6d6a0afb7 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderPlacedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Orders/OrderPlacedEventHandlerTests.cs
@@ -2,48 +2,54 @@
using Grand.Business.Core.Events.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Customers;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.Orders
+namespace Grand.Business.Checkout.Tests.Events.Orders;
+
+[TestClass]
+public class OrderPlacedEventHandlerTests
{
- [TestClass()]
- public class OrderPlacedEventHandlerTests
- {
- private OrderPlacedEventHandler _orderPlacedEventHandler;
- private Mock<IRepository<ProductAlsoPurchased>> _productAlsoPurchasedRepository;
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private Mock<ICustomerService> _customerServiceMock;
+ private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private OrderPlacedEventHandler _orderPlacedEventHandler;
+ private Mock<IRepository<ProductAlsoPurchased>> _productAlsoPurchasedRepository;
- [TestInitialize()]
- public void Init()
- {
- _productAlsoPurchasedRepository = new Mock<IRepository<ProductAlsoPurchased>>();
- _customerServiceMock = new Mock<ICustomerService>();
- _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
- _orderPlacedEventHandler = new OrderPlacedEventHandler(_productAlsoPurchasedRepository.Object, _customerServiceMock.Object, _loyaltyPointsServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _productAlsoPurchasedRepository = new Mock<IRepository<ProductAlsoPurchased>>();
+ _customerServiceMock = new Mock<ICustomerService>();
+ _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
+ _orderPlacedEventHandler = new OrderPlacedEventHandler(_productAlsoPurchasedRepository.Object,
+ _customerServiceMock.Object, _loyaltyPointsServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var order = new Order { RedeemedLoyaltyPointsAmount = 10 };
- order.OrderItems.Add(new OrderItem { ProductId = "1" });
- order.OrderItems.Add(new OrderItem { ProductId = "2" });
- var notification = new OrderPlacedEvent(order);
- //Act
- await _orderPlacedEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _productAlsoPurchasedRepository.Verify(c => c.InsertAsync(It.IsAny<ProductAlsoPurchased>()), Times.AtLeastOnce);
- _loyaltyPointsServiceMock.Verify(c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()), Times.Once);
- _customerServiceMock.Verify(c => c.UpdateCustomerField(order.CustomerId, x => x.FreeShipping, false), Times.Once);
- _customerServiceMock.Verify(c => c.UpdateCustomerField(order.CustomerId, x => x.LastPurchaseDateUtc, order.CreatedOnUtc), Times.Once);
- _customerServiceMock.Verify(c => c.UpdateCustomerField(order.CustomerId, x => x.LastUpdateCartDateUtc, null), Times.Once);
- _customerServiceMock.Verify(c => c.UpdateCustomerField(order.CustomerId, x => x.HasContributions, true), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var order = new Order { RedeemedLoyaltyPointsAmount = 10 };
+ order.OrderItems.Add(new OrderItem { ProductId = "1" });
+ order.OrderItems.Add(new OrderItem { ProductId = "2" });
+ var notification = new OrderPlacedEvent(order);
+ //Act
+ await _orderPlacedEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _productAlsoPurchasedRepository.Verify(c => c.InsertAsync(It.IsAny<ProductAlsoPurchased>()), Times.AtLeastOnce);
+ _loyaltyPointsServiceMock.Verify(
+ c => c.AddLoyaltyPointsHistory(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<double>()), Times.Once);
+ _customerServiceMock.Verify(c => c.UpdateCustomerField(order.CustomerId, x => x.FreeShipping, false),
+ Times.Once);
+ _customerServiceMock.Verify(
+ c => c.UpdateCustomerField(order.CustomerId, x => x.LastPurchaseDateUtc, order.CreatedOnUtc), Times.Once);
+ _customerServiceMock.Verify(c => c.UpdateCustomerField(order.CustomerId, x => x.LastUpdateCartDateUtc, null),
+ Times.Once);
+ _customerServiceMock.Verify(c => c.UpdateCustomerField(order.CustomerId, x => x.HasContributions, true),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentDeletedEventHandlerTests.cs
index f97430455..bb7f9d988 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentDeletedEventHandlerTests.cs
@@ -4,43 +4,45 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.Shipping
+namespace Grand.Business.Checkout.Tests.Events.Shipping;
+
+[TestClass]
+public class ShipmentDeletedEventHandlerTests
{
- [TestClass()]
- public class ShipmentDeletedEventHandlerTests
- {
- private ShipmentDeletedEventHandler _shipmentDeletedEventHandler;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IShipmentService> _shipmentServiceMock;
- private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private ShipmentDeletedEventHandler _shipmentDeletedEventHandler;
+ private Mock<IShipmentService> _shipmentServiceMock;
- [TestInitialize()]
- public void Init()
- {
- _orderServiceMock = new Mock<IOrderService>();
- _shipmentServiceMock = new Mock<IShipmentService>();
- _inventoryManageServiceMock = new Mock<IInventoryManageService>();
- _shipmentDeletedEventHandler = new ShipmentDeletedEventHandler(_orderServiceMock.Object, _shipmentServiceMock.Object, _inventoryManageServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _orderServiceMock = new Mock<IOrderService>();
+ _shipmentServiceMock = new Mock<IShipmentService>();
+ _inventoryManageServiceMock = new Mock<IInventoryManageService>();
+ _shipmentDeletedEventHandler = new ShipmentDeletedEventHandler(_orderServiceMock.Object,
+ _shipmentServiceMock.Object, _inventoryManageServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var order = new Order();
- _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(order));
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var order = new Order();
+ _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(order));
- var shipment = new Shipment();
- shipment.ShipmentItems.Add(new ShipmentItem { OrderItemId = "!" });
- var notification = new Infrastructure.Events.EntityDeleted<Shipment>(shipment);
- //Act
- await _shipmentDeletedEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _inventoryManageServiceMock.Verify(x=>x.ReverseBookedInventory(It.IsAny<Shipment>(), It.IsAny<ShipmentItem>()), Times.Once);
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ var shipment = new Shipment();
+ shipment.ShipmentItems.Add(new ShipmentItem { OrderItemId = "!" });
+ var notification = new EntityDeleted<Shipment>(shipment);
+ //Act
+ await _shipmentDeletedEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _inventoryManageServiceMock.Verify(
+ x => x.ReverseBookedInventory(It.IsAny<Shipment>(), It.IsAny<ShipmentItem>()), Times.Once);
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentInsertedEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentInsertedEventHandlerTests.cs
index 6748041de..b4b790651 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentInsertedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/Shipping/ShipmentInsertedEventHandlerTests.cs
@@ -4,44 +4,48 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Domain.Catalog;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.Shipping
+namespace Grand.Business.Checkout.Tests.Events.Shipping;
+
+[TestClass]
+public class ShipmentInsertedEventHandlerTests
{
- [TestClass()]
- public class ShipmentInsertedEventHandlerTests
- {
- private ShipmentInsertedEventHandler _shipmentInsertedEventHandler;
- private Mock<IOrderService> _orderServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IInventoryManageService> _inventoryManageServiceMock;
+ private Mock<IOrderService> _orderServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private ShipmentInsertedEventHandler _shipmentInsertedEventHandler;
- [TestInitialize()]
- public void Init()
- {
- _orderServiceMock = new Mock<IOrderService>();
- _productServiceMock = new Mock<IProductService>();
- _inventoryManageServiceMock = new Mock<IInventoryManageService>();
- _shipmentInsertedEventHandler = new ShipmentInsertedEventHandler(_orderServiceMock.Object, _productServiceMock.Object, _inventoryManageServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _orderServiceMock = new Mock<IOrderService>();
+ _productServiceMock = new Mock<IProductService>();
+ _inventoryManageServiceMock = new Mock<IInventoryManageService>();
+ _shipmentInsertedEventHandler = new ShipmentInsertedEventHandler(_orderServiceMock.Object,
+ _productServiceMock.Object, _inventoryManageServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var order = new Order();
- _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(order));
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false)).Returns(Task.FromResult(new Domain.Catalog.Product()));
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var order = new Order();
+ _orderServiceMock.Setup(x => x.GetOrderById(It.IsAny<string>())).Returns(Task.FromResult(order));
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(Task.FromResult(new Product()));
- var shipment = new Shipment();
- shipment.ShipmentItems.Add(new ShipmentItem { OrderItemId = "!" });
- var notification = new Infrastructure.Events.EntityInserted<Shipment>(shipment);
- //Act
- await _shipmentInsertedEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _inventoryManageServiceMock.Verify(x => x.BookReservedInventory(It.IsAny<Product>(), It.IsAny<Shipment>(), It.IsAny<ShipmentItem>()), Times.Once);
- _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
- }
+ var shipment = new Shipment();
+ shipment.ShipmentItems.Add(new ShipmentItem { OrderItemId = "!" });
+ var notification = new EntityInserted<Shipment>(shipment);
+ //Act
+ await _shipmentInsertedEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _inventoryManageServiceMock.Verify(
+ x => x.BookReservedInventory(It.IsAny<Product>(), It.IsAny<Shipment>(), It.IsAny<ShipmentItem>()),
+ Times.Once);
+ _orderServiceMock.Verify(c => c.UpdateOrder(It.IsAny<Order>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs
index 587f4a45f..0da4fbdbd 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/CustomerLoggedInEventHandlerTests.cs
@@ -1,36 +1,38 @@
using Grand.Business.Checkout.Events.ShoppingCart;
+using Grand.Business.Core.Events.Customers;
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Domain.Customers;
using Grand.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.ShoppingCart
+namespace Grand.Business.Checkout.Tests.Events.ShoppingCart;
+
+[TestClass]
+public class CustomerLoggedInEventHandlerTests
{
- [TestClass()]
- public class CustomerLoggedInEventHandlerTests
- {
- private CustomerLoggedInEventHandler _customerLoggedInEventHandler;
- private Mock<IShoppingCartService> _shoppingCartServiceMock;
- private Mock<IWorkContext> _workContextMock;
+ private CustomerLoggedInEventHandler _customerLoggedInEventHandler;
+ private Mock<IShoppingCartService> _shoppingCartServiceMock;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- _shoppingCartServiceMock = new Mock<IShoppingCartService>();
- _workContextMock = new Mock<IWorkContext>();
- _customerLoggedInEventHandler = new CustomerLoggedInEventHandler(_shoppingCartServiceMock.Object, _workContextMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _shoppingCartServiceMock = new Mock<IShoppingCartService>();
+ _workContextMock = new Mock<IWorkContext>();
+ _customerLoggedInEventHandler =
+ new CustomerLoggedInEventHandler(_shoppingCartServiceMock.Object, _workContextMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var notification = new Core.Events.Customers.CustomerLoggedInEvent(new Customer());
- //Act
- await _customerLoggedInEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _shoppingCartServiceMock.Verify(c => c.MigrateShoppingCart(It.IsAny<Customer>(), It.IsAny<Customer>(), true), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var notification = new CustomerLoggedInEvent(new Customer());
+ //Act
+ await _customerLoggedInEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _shoppingCartServiceMock.Verify(c => c.MigrateShoppingCart(It.IsAny<Customer>(), It.IsAny<Customer>(), true),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.cs
index 773c428e0..0effa9c8d 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Events/ShoppingCart/ShoppingCartItemDeletedEventHandlerTests.cs
@@ -1,35 +1,39 @@
using Grand.Business.Checkout.Events.ShoppingCart;
using Grand.Business.Core.Interfaces.Catalog.Products;
using Grand.Domain.Catalog;
+using Grand.Domain.Orders;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Events.ShoppingCart
-{
- [TestClass()]
- public class ShoppingCartItemDeletedEventHandlerTests
- {
- private ShoppingCartItemDeletedEventHandler _shoppingCartItemDeletedEventHandler;
+namespace Grand.Business.Checkout.Tests.Events.ShoppingCart;
- private Mock<IProductReservationService> _productReservationServiceMock;
+[TestClass]
+public class ShoppingCartItemDeletedEventHandlerTests
+{
+ private Mock<IProductReservationService> _productReservationServiceMock;
+ private ShoppingCartItemDeletedEventHandler _shoppingCartItemDeletedEventHandler;
- [TestInitialize()]
- public void Init()
- {
- _productReservationServiceMock = new Mock<IProductReservationService>();
- _shoppingCartItemDeletedEventHandler = new ShoppingCartItemDeletedEventHandler(_productReservationServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _productReservationServiceMock = new Mock<IProductReservationService>();
+ _shoppingCartItemDeletedEventHandler =
+ new ShoppingCartItemDeletedEventHandler(_productReservationServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- _productReservationServiceMock.Setup(x => x.GetCustomerReservationsHelperBySciId(It.IsAny<string>())).Returns(Task.FromResult((IList<CustomerReservationsHelper>)new List<CustomerReservationsHelper> { new CustomerReservationsHelper() }));
- var notification = new Infrastructure.Events.EntityDeleted<Domain.Orders.ShoppingCartItem>(new Domain.Orders.ShoppingCartItem { RentalStartDateUtc = DateTime.UtcNow, RentalEndDateUtc = DateTime.UtcNow});
- //Act
- await _shoppingCartItemDeletedEventHandler.Handle(notification, CancellationToken.None);
- //Assert
- _productReservationServiceMock.Verify(c => c.DeleteCustomerReservationsHelper(It.IsAny<CustomerReservationsHelper>()), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ _productReservationServiceMock.Setup(x => x.GetCustomerReservationsHelperBySciId(It.IsAny<string>())).Returns(
+ Task.FromResult((IList<CustomerReservationsHelper>)new List<CustomerReservationsHelper> { new() }));
+ var notification = new EntityDeleted<ShoppingCartItem>(new ShoppingCartItem
+ { RentalStartDateUtc = DateTime.UtcNow, RentalEndDateUtc = DateTime.UtcNow });
+ //Act
+ await _shoppingCartItemDeletedEventHandler.Handle(notification, CancellationToken.None);
+ //Assert
+ _productReservationServiceMock.Verify(
+ c => c.DeleteCustomerReservationsHelper(It.IsAny<CustomerReservationsHelper>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs
index 29d9d4cd4..32b31c1d0 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/PaymentExtensionsTests.cs
@@ -4,43 +4,42 @@ using Grand.Domain.Payments;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Extensions
+namespace Grand.Business.Checkout.Tests.Extensions;
+
+[TestClass]
+public class PaymentExtensionsTests
{
- [TestClass()]
- public class PaymentExtensionsTests
- {
- private Mock<IPaymentProvider> _providerMock;
+ private Mock<IPaymentProvider> _providerMock;
- [TestInitialize]
- public void Init()
- {
- _providerMock = new Mock<IPaymentProvider>();
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _providerMock = new Mock<IPaymentProvider>();
+ }
- [TestMethod()]
- public void IsPaymentMethodActive_ReturnExpectedResult()
- {
- var settings = new PaymentSettings();
- _providerMock.Setup(c => c.SystemName).Returns("stripe");
- settings.ActivePaymentProviderSystemNames.Add("stripe");
- Assert.IsTrue(_providerMock.Object.IsPaymentMethodActive(settings));
- _providerMock.Setup(c => c.SystemName).Returns("klarna");
- Assert.IsFalse(_providerMock.Object.IsPaymentMethodActive(settings));
- }
+ [TestMethod]
+ public void IsPaymentMethodActive_ReturnExpectedResult()
+ {
+ var settings = new PaymentSettings();
+ _providerMock.Setup(c => c.SystemName).Returns("stripe");
+ settings.ActivePaymentProviderSystemNames.Add("stripe");
+ Assert.IsTrue(_providerMock.Object.IsPaymentMethodActive(settings));
+ _providerMock.Setup(c => c.SystemName).Returns("klarna");
+ Assert.IsFalse(_providerMock.Object.IsPaymentMethodActive(settings));
+ }
- [TestMethod()]
- public void IsPaymentMethodActive_NullSettings_ThrowException()
- {
- PaymentSettings settings = null;
- Assert.ThrowsException<ArgumentNullException>(() => _providerMock.Object.IsPaymentMethodActive(settings));
- }
+ [TestMethod]
+ public void IsPaymentMethodActive_NullSettings_ThrowException()
+ {
+ PaymentSettings settings = null;
+ Assert.ThrowsException<ArgumentNullException>(() => _providerMock.Object.IsPaymentMethodActive(settings));
+ }
- [TestMethod()]
- public void IsPaymentMethodActive_NullProvider_ThrowException()
- {
- IPaymentProvider provider = null;
- var settings = new PaymentSettings();
- Assert.ThrowsException<ArgumentNullException>(() => provider.IsPaymentMethodActive(settings));
- }
+ [TestMethod]
+ public void IsPaymentMethodActive_NullProvider_ThrowException()
+ {
+ IPaymentProvider provider = null;
+ var settings = new PaymentSettings();
+ Assert.ThrowsException<ArgumentNullException>(() => provider.IsPaymentMethodActive(settings));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Extensions/ShippingExtensionsTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Extensions/ShippingExtensionsTests.cs
index 5e22e76b0..51aec83d7 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Extensions/ShippingExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Extensions/ShippingExtensionsTests.cs
@@ -1,61 +1,61 @@
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Checkout.Shipping;
+using Grand.Domain.Directory;
using Grand.Domain.Shipping;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Extensions
+namespace Grand.Business.Checkout.Tests.Extensions;
+
+[TestClass]
+public class ShippingExtensionsTests
{
- [TestClass]
- public class ShippingExtensionsTests
+ [TestMethod]
+ public void IsShippingRateMethodActive_ReturnExpectedResult()
{
- [TestMethod]
- public void IsShippingRateMethodActive_ReturnExpectedResult()
- {
- var providerMock = new Mock<IShippingRateCalculationProvider>();
- providerMock.Setup(c => c.SystemName).Returns("dhl");
- var provider = providerMock.Object;
- var settings = new ShippingProviderSettings();
- Assert.IsFalse(provider.IsShippingRateMethodActive(settings));
- settings.ActiveSystemNames.Add("dhl");
- settings.ActiveSystemNames.Add("upc");
- Assert.IsTrue(provider.IsShippingRateMethodActive(settings));
- }
+ var providerMock = new Mock<IShippingRateCalculationProvider>();
+ providerMock.Setup(c => c.SystemName).Returns("dhl");
+ var provider = providerMock.Object;
+ var settings = new ShippingProviderSettings();
+ Assert.IsFalse(provider.IsShippingRateMethodActive(settings));
+ settings.ActiveSystemNames.Add("dhl");
+ settings.ActiveSystemNames.Add("upc");
+ Assert.IsTrue(provider.IsShippingRateMethodActive(settings));
+ }
- [TestMethod]
- public void IsShippingRateMethodActive_NullProvider_ThrowException()
- {
- IShippingRateCalculationProvider provider = null;
- var settings = new ShippingProviderSettings();
- Assert.ThrowsException<ArgumentNullException>(() => provider.IsShippingRateMethodActive(settings));
- }
+ [TestMethod]
+ public void IsShippingRateMethodActive_NullProvider_ThrowException()
+ {
+ IShippingRateCalculationProvider provider = null;
+ var settings = new ShippingProviderSettings();
+ Assert.ThrowsException<ArgumentNullException>(() => provider.IsShippingRateMethodActive(settings));
+ }
- [TestMethod]
- public void IsShippingRateMethodActive_NullSettings_ThrowException()
- {
- var providerMock = new Mock<IShippingRateCalculationProvider>();
- var provider = providerMock.Object;
- Assert.ThrowsException<ArgumentNullException>(() => provider.IsShippingRateMethodActive(null));
- }
+ [TestMethod]
+ public void IsShippingRateMethodActive_NullSettings_ThrowException()
+ {
+ var providerMock = new Mock<IShippingRateCalculationProvider>();
+ var provider = providerMock.Object;
+ Assert.ThrowsException<ArgumentNullException>(() => provider.IsShippingRateMethodActive(null));
+ }
- [TestMethod]
- public void CountryRestrictionExists_ReturnExpectedResult()
- {
- var method = new ShippingMethod();
- var countryId = "countryId";
- Assert.IsFalse(method.CountryRestrictionExists(countryId));
- method.RestrictedCountries.Add(new Domain.Directory.Country { Id = countryId });
- Assert.IsTrue(method.CountryRestrictionExists(countryId));
- }
+ [TestMethod]
+ public void CountryRestrictionExists_ReturnExpectedResult()
+ {
+ var method = new ShippingMethod();
+ var countryId = "countryId";
+ Assert.IsFalse(method.CountryRestrictionExists(countryId));
+ method.RestrictedCountries.Add(new Country { Id = countryId });
+ Assert.IsTrue(method.CountryRestrictionExists(countryId));
+ }
- [TestMethod]
- public void CustomerGroupRestrictionExists_ReturnExpectedResult()
- {
- var method = new ShippingMethod();
- var roleId = "role";
- Assert.IsFalse(method.CustomerGroupRestrictionExists(roleId));
- method.RestrictedGroups.Add(roleId);
- Assert.IsTrue(method.CustomerGroupRestrictionExists(roleId));
- }
+ [TestMethod]
+ public void CustomerGroupRestrictionExists_ReturnExpectedResult()
+ {
+ var method = new ShippingMethod();
+ var roleId = "role";
+ Assert.IsFalse(method.CustomerGroupRestrictionExists(roleId));
+ method.RestrictedGroups.Add(roleId);
+ Assert.IsTrue(method.CustomerGroupRestrictionExists(roleId));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/HandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/HandlerTests.cs
index 583291d62..08ed3da36 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/HandlerTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Queries/Handlers/Orders/HandlerTests.cs
@@ -6,248 +6,342 @@ using Grand.Domain.Payments;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders
+namespace Grand.Business.Checkout.Tests.Queries.Handlers.Orders;
+
+[TestClass]
+public class HandlerTests
{
- [TestClass()]
- public class HandlerTests
- {
- private Mock<IPaymentService> _paymentServiceMock;
-
- [TestInitialize()]
- public void Init()
- {
- _paymentServiceMock = new Mock<IPaymentService>();
- _paymentServiceMock.Setup(x => x.SupportCapture(It.IsAny<string>())).Returns(Task.FromResult(true));
- _paymentServiceMock.Setup(x => x.SupportRefund(It.IsAny<string>())).Returns(Task.FromResult(true));
- _paymentServiceMock.Setup(x => x.SupportPartiallyRefund(It.IsAny<string>())).Returns(Task.FromResult(true));
- _paymentServiceMock.Setup(x => x.SupportVoid(It.IsAny<string>())).Returns(Task.FromResult(true));
- }
-
- [TestMethod()]
- public async Task CanCancelOrderQueryHandler_HandleTest_OrderStatus_Pending_True()
- {
- //Arrange
- var canCancelOrderQueryHandler = new CanCancelOrderQueryHandler();
- //Act
- var result = await canCancelOrderQueryHandler.Handle(new CanCancelOrderQuery { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanCancelOrderQueryHandler_HandleTest_OrderStatus_Processing_False()
- {
- //Arrange
- var canCancelOrderQueryHandler = new CanCancelOrderQueryHandler();
- //Act
- var result = await canCancelOrderQueryHandler.Handle(new CanCancelOrderQuery { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Processing } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
-
-
- [TestMethod()]
- public async Task CanCaptureQueryHandler_HandleTest_TransactionStatus_Authorized_True()
- {
- //Arrange
- var canCaptureQueryHandler = new CanCaptureQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canCaptureQueryHandler.Handle(new CanCaptureQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Authorized } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanCaptureQueryHandler_HandleTest_TransactionStatus_Paid_False()
- {
- //Arrange
- var canCaptureQueryHandler = new CanCaptureQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canCaptureQueryHandler.Handle(new CanCaptureQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Paid } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
- [TestMethod()]
- public async Task CanMarkPaymentTransactionAsAuthorizedQueryHandler_HandleTest_TransactionStatus_Canceled_False()
- {
- //Arrange
- var canMarkPaymentTransactionAsAuthorizedQueryHandler = new CanMarkPaymentTransactionAsAuthorizedQueryHandler();
- //Act
- var result = await canMarkPaymentTransactionAsAuthorizedQueryHandler.Handle(new CanMarkPaymentTransactionAsAuthorizedQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Canceled } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
- [TestMethod()]
- public async Task CanMarkPaymentTransactionAsAuthorizedQueryHandler_HandleTest_TransactionStatus_Pending_True()
- {
- //Arrange
- var canMarkPaymentTransactionAsAuthorizedQueryHandler = new CanMarkPaymentTransactionAsAuthorizedQueryHandler();
- //Act
- var result = await canMarkPaymentTransactionAsAuthorizedQueryHandler.Handle(new CanMarkPaymentTransactionAsAuthorizedQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanMarkPaymentTransactionAsPaidQueryHandler_HandleTest_TransactionStatus_Authorized_True()
- {
- //Arrange
- var canMarkPaymentTransactionAsPaidQueryHandler = new CanMarkPaymentTransactionAsPaidQueryHandler();
- //Act
- var result = await canMarkPaymentTransactionAsPaidQueryHandler.Handle(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Authorized } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanMarkPaymentTransactionAsPaidQueryHandler_HandleTest_TransactionStatus_Canceled_False()
- {
- //Arrange
- var canMarkPaymentTransactionAsPaidQueryHandler = new CanMarkPaymentTransactionAsPaidQueryHandler();
- //Act
- var result = await canMarkPaymentTransactionAsPaidQueryHandler.Handle(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Canceled } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
-
- [TestMethod()]
- public async Task CanPartiallyPaidOfflineQuery_HandleTest_TransactionStatus_Pending_True()
- {
- //Arrange
- var canPartiallyPaidOfflineQueryHandler = new CanPartiallyPaidOfflineQueryHandler();
- //Act
- var result = await canPartiallyPaidOfflineQueryHandler.Handle(new CanPartiallyPaidOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 20 }, AmountToPaid = 10 }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanPartiallyPaidOfflineQuery_HandleTest_TransactionStatus_Paid_False()
- {
- //Arrange
- var canPartiallyPaidOfflineQueryHandler = new CanPartiallyPaidOfflineQueryHandler();
- //Act
- var result = await canPartiallyPaidOfflineQueryHandler.Handle(new CanPartiallyPaidOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 20 }, AmountToPaid = 10 }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
- [TestMethod()]
- public async Task CanPartiallyRefundOfflineQueryHandler_HandleTest_TransactionStatus_Pending_False()
- {
- //Arrange
- var canPartiallyRefundOfflineQueryHandler = new CanPartiallyRefundOfflineQueryHandler();
- //Act
- var result = await canPartiallyRefundOfflineQueryHandler.Handle(new CanPartiallyRefundOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 20 } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
- [TestMethod()]
- public async Task CanPartiallyRefundOfflineQueryHandler_HandleTest_TransactionStatus_Paid_True()
- {
- //Arrange
- var canPartiallyRefundOfflineQueryHandler = new CanPartiallyRefundOfflineQueryHandler();
- //Act
- var result = await canPartiallyRefundOfflineQueryHandler.Handle(new CanPartiallyRefundOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 20 } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
-
- [TestMethod()]
- public async Task CanPartiallyRefundQueryHandler_HandleTest_Paid_True()
- {
- //Arrange
- var canPartiallyRefundQueryHandler = new CanPartiallyRefundQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canPartiallyRefundQueryHandler.Handle(new CanPartiallyRefundQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanPartiallyRefundQueryHandler_HandleTest_Pending_False()
- {
- //Arrange
- var canPartiallyRefundQueryHandler = new CanPartiallyRefundQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canPartiallyRefundQueryHandler.Handle(new CanPartiallyRefundQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
- [TestMethod()]
- public async Task CanRefundOfflineQueryHandler_HandleTest_Paid_True()
- {
- //Arrange
- var canRefundOfflineQueryHandler = new CanRefundOfflineQueryHandler();
- //Act
- var result = await canRefundOfflineQueryHandler.Handle(new CanRefundOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanRefundOfflineQueryHandler_HandleTest_Pending_False()
- {
- //Arrange
- var canRefundOfflineQueryHandler = new CanRefundOfflineQueryHandler();
- //Act
- var result = await canRefundOfflineQueryHandler.Handle(new CanRefundOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
- [TestMethod()]
- public async Task CanRefundQueryHandler_HandleTest_Paid_True()
- {
- //Arrange
- var canRefundQueryHandler = new CanRefundQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canRefundQueryHandler.Handle(new CanRefundQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanRefundQueryHandler_HandleTest_Paid_False()
- {
- //Arrange
- var canRefundQueryHandler = new CanRefundQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canRefundQueryHandler.Handle(new CanRefundQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
- [TestMethod()]
- public async Task CanVoidOfflineQueryHandler_HandleTest_Authorized_True()
- {
- //Arrange
- var canVoidOfflineQueryHandler = new CanVoidOfflineQueryHandler();
- //Act
- var result = await canVoidOfflineQueryHandler.Handle(new CanVoidOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Authorized, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanVoidOfflineQueryHandler_HandleTest_PartialPaid_False()
- {
- //Arrange
- var canVoidOfflineQueryHandler = new CanVoidOfflineQueryHandler();
- //Act
- var result = await canVoidOfflineQueryHandler.Handle(new CanVoidOfflineQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.PartialPaid, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
-
- [TestMethod()]
- public async Task CanVoidQueryHandler_HandleTest_Authorized_True()
- {
- //Arrange
- var canVoidQueryHandler = new CanVoidQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canVoidQueryHandler.Handle(new CanVoidQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Authorized, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public async Task CanVoidQueryHandler_HandleTest_Paid_Fals()
- {
- //Arrange
- var canVoidQueryHandler = new CanVoidQueryHandler(_paymentServiceMock.Object);
- //Act
- var result = await canVoidQueryHandler.Handle(new CanVoidQuery { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 } }, CancellationToken.None);
- //Assert
- Assert.IsFalse(result);
- }
+ private Mock<IPaymentService> _paymentServiceMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _paymentServiceMock = new Mock<IPaymentService>();
+ _paymentServiceMock.Setup(x => x.SupportCapture(It.IsAny<string>())).Returns(Task.FromResult(true));
+ _paymentServiceMock.Setup(x => x.SupportRefund(It.IsAny<string>())).Returns(Task.FromResult(true));
+ _paymentServiceMock.Setup(x => x.SupportPartiallyRefund(It.IsAny<string>())).Returns(Task.FromResult(true));
+ _paymentServiceMock.Setup(x => x.SupportVoid(It.IsAny<string>())).Returns(Task.FromResult(true));
+ }
+
+ [TestMethod]
+ public async Task CanCancelOrderQueryHandler_HandleTest_OrderStatus_Pending_True()
+ {
+ //Arrange
+ var canCancelOrderQueryHandler = new CanCancelOrderQueryHandler();
+ //Act
+ var result = await canCancelOrderQueryHandler.Handle(
+ new CanCancelOrderQuery { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Pending } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanCancelOrderQueryHandler_HandleTest_OrderStatus_Processing_False()
+ {
+ //Arrange
+ var canCancelOrderQueryHandler = new CanCancelOrderQueryHandler();
+ //Act
+ var result = await canCancelOrderQueryHandler.Handle(
+ new CanCancelOrderQuery { Order = new Order { OrderStatusId = (int)OrderStatusSystem.Processing } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+
+ [TestMethod]
+ public async Task CanCaptureQueryHandler_HandleTest_TransactionStatus_Authorized_True()
+ {
+ //Arrange
+ var canCaptureQueryHandler = new CanCaptureQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canCaptureQueryHandler.Handle(
+ new CanCaptureQuery
+ { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Authorized } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanCaptureQueryHandler_HandleTest_TransactionStatus_Paid_False()
+ {
+ //Arrange
+ var canCaptureQueryHandler = new CanCaptureQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canCaptureQueryHandler.Handle(
+ new CanCaptureQuery
+ { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Paid } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanMarkPaymentTransactionAsAuthorizedQueryHandler_HandleTest_TransactionStatus_Canceled_False()
+ {
+ //Arrange
+ var canMarkPaymentTransactionAsAuthorizedQueryHandler = new CanMarkPaymentTransactionAsAuthorizedQueryHandler();
+ //Act
+ var result = await canMarkPaymentTransactionAsAuthorizedQueryHandler.Handle(
+ new CanMarkPaymentTransactionAsAuthorizedQuery
+ { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Canceled } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanMarkPaymentTransactionAsAuthorizedQueryHandler_HandleTest_TransactionStatus_Pending_True()
+ {
+ //Arrange
+ var canMarkPaymentTransactionAsAuthorizedQueryHandler = new CanMarkPaymentTransactionAsAuthorizedQueryHandler();
+ //Act
+ var result = await canMarkPaymentTransactionAsAuthorizedQueryHandler.Handle(
+ new CanMarkPaymentTransactionAsAuthorizedQuery
+ { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanMarkPaymentTransactionAsPaidQueryHandler_HandleTest_TransactionStatus_Authorized_True()
+ {
+ //Arrange
+ var canMarkPaymentTransactionAsPaidQueryHandler = new CanMarkPaymentTransactionAsPaidQueryHandler();
+ //Act
+ var result = await canMarkPaymentTransactionAsPaidQueryHandler.Handle(
+ new CanMarkPaymentTransactionAsPaidQuery
+ { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Authorized } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanMarkPaymentTransactionAsPaidQueryHandler_HandleTest_TransactionStatus_Canceled_False()
+ {
+ //Arrange
+ var canMarkPaymentTransactionAsPaidQueryHandler = new CanMarkPaymentTransactionAsPaidQueryHandler();
+ //Act
+ var result = await canMarkPaymentTransactionAsPaidQueryHandler.Handle(
+ new CanMarkPaymentTransactionAsPaidQuery
+ { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Canceled } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanPartiallyPaidOfflineQuery_HandleTest_TransactionStatus_Pending_True()
+ {
+ //Arrange
+ var canPartiallyPaidOfflineQueryHandler = new CanPartiallyPaidOfflineQueryHandler();
+ //Act
+ var result = await canPartiallyPaidOfflineQueryHandler.Handle(
+ new CanPartiallyPaidOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 20 },
+ AmountToPaid = 10
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanPartiallyPaidOfflineQuery_HandleTest_TransactionStatus_Paid_False()
+ {
+ //Arrange
+ var canPartiallyPaidOfflineQueryHandler = new CanPartiallyPaidOfflineQueryHandler();
+ //Act
+ var result = await canPartiallyPaidOfflineQueryHandler.Handle(
+ new CanPartiallyPaidOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 20 },
+ AmountToPaid = 10
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+ [TestMethod]
+ public async Task CanPartiallyRefundOfflineQueryHandler_HandleTest_TransactionStatus_Pending_False()
+ {
+ //Arrange
+ var canPartiallyRefundOfflineQueryHandler = new CanPartiallyRefundOfflineQueryHandler();
+ //Act
+ var result = await canPartiallyRefundOfflineQueryHandler.Handle(
+ new CanPartiallyRefundOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 20 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanPartiallyRefundOfflineQueryHandler_HandleTest_TransactionStatus_Paid_True()
+ {
+ //Arrange
+ var canPartiallyRefundOfflineQueryHandler = new CanPartiallyRefundOfflineQueryHandler();
+ //Act
+ var result = await canPartiallyRefundOfflineQueryHandler.Handle(
+ new CanPartiallyRefundOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 20 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanPartiallyRefundQueryHandler_HandleTest_Paid_True()
+ {
+ //Arrange
+ var canPartiallyRefundQueryHandler = new CanPartiallyRefundQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canPartiallyRefundQueryHandler.Handle(
+ new CanPartiallyRefundQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanPartiallyRefundQueryHandler_HandleTest_Pending_False()
+ {
+ //Arrange
+ var canPartiallyRefundQueryHandler = new CanPartiallyRefundQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canPartiallyRefundQueryHandler.Handle(
+ new CanPartiallyRefundQuery
+ { PaymentTransaction = new PaymentTransaction { TransactionStatus = TransactionStatus.Pending } },
+ CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanRefundOfflineQueryHandler_HandleTest_Paid_True()
+ {
+ //Arrange
+ var canRefundOfflineQueryHandler = new CanRefundOfflineQueryHandler();
+ //Act
+ var result = await canRefundOfflineQueryHandler.Handle(
+ new CanRefundOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanRefundOfflineQueryHandler_HandleTest_Pending_False()
+ {
+ //Arrange
+ var canRefundOfflineQueryHandler = new CanRefundOfflineQueryHandler();
+ //Act
+ var result = await canRefundOfflineQueryHandler.Handle(
+ new CanRefundOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanRefundQueryHandler_HandleTest_Paid_True()
+ {
+ //Arrange
+ var canRefundQueryHandler = new CanRefundQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canRefundQueryHandler.Handle(
+ new CanRefundQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanRefundQueryHandler_HandleTest_Paid_False()
+ {
+ //Arrange
+ var canRefundQueryHandler = new CanRefundQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canRefundQueryHandler.Handle(
+ new CanRefundQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Pending, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanVoidOfflineQueryHandler_HandleTest_Authorized_True()
+ {
+ //Arrange
+ var canVoidOfflineQueryHandler = new CanVoidOfflineQueryHandler();
+ //Act
+ var result = await canVoidOfflineQueryHandler.Handle(
+ new CanVoidOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Authorized, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanVoidOfflineQueryHandler_HandleTest_PartialPaid_False()
+ {
+ //Arrange
+ var canVoidOfflineQueryHandler = new CanVoidOfflineQueryHandler();
+ //Act
+ var result = await canVoidOfflineQueryHandler.Handle(
+ new CanVoidOfflineQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.PartialPaid, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
+ }
+
+ [TestMethod]
+ public async Task CanVoidQueryHandler_HandleTest_Authorized_True()
+ {
+ //Arrange
+ var canVoidQueryHandler = new CanVoidQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canVoidQueryHandler.Handle(
+ new CanVoidQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Authorized, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task CanVoidQueryHandler_HandleTest_Paid_Fals()
+ {
+ //Arrange
+ var canVoidQueryHandler = new CanVoidQueryHandler(_paymentServiceMock.Object);
+ //Act
+ var result = await canVoidQueryHandler.Handle(
+ new CanVoidQuery {
+ PaymentTransaction = new PaymentTransaction
+ { TransactionStatus = TransactionStatus.Paid, TransactionAmount = 10 }
+ }, CancellationToken.None);
+ //Assert
+ Assert.IsFalse(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs
index d45ddf064..fdec98b8f 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeParserTests.cs
@@ -1,9 +1,9 @@
-using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;
-using Grand.Business.Checkout.Services.CheckoutAttributes;
-using Grand.Domain.Catalog;
-using Grand.Domain.Common;
+using Grand.Business.Checkout.Services.CheckoutAttributes;
+using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;
using Grand.Data;
using Grand.Data.Mongo;
+using Grand.Domain.Catalog;
+using Grand.Domain.Common;
using Grand.Domain.Localization;
using Grand.Domain.Orders;
using Grand.Infrastructure;
@@ -14,146 +14,143 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.CheckoutAttributes
+namespace Grand.Business.Checkout.Tests.Services.CheckoutAttributes;
+
+[TestClass]
+public class CheckoutAttributeParserTests
{
- [TestClass()]
- public class CheckoutAttributeParserTests
+ private ICheckoutAttributeParser _checkoutAttributeParser;
+ private IRepository<CheckoutAttribute> _checkoutAttributeRepo;
+ private ICheckoutAttributeService _checkoutAttributeService;
+ private IMediator _eventPublisher;
+ private Mock<IWorkContext> _workContextMock;
+
+ private CheckoutAttribute ca1, ca2, ca3;
+ private Mock<ICacheBase> cacheManager;
+ private CheckoutAttributeValue cav1_1, cav1_2, cav2_1, cav2_2;
+
+ [TestInitialize]
+ public void TestInitialize()
{
- private IRepository<CheckoutAttribute> _checkoutAttributeRepo;
- private IMediator _eventPublisher;
- private Mock<ICacheBase> cacheManager;
- private Mock<IWorkContext> _workContextMock;
- private ICheckoutAttributeService _checkoutAttributeService;
- private ICheckoutAttributeParser _checkoutAttributeParser;
-
- private CheckoutAttribute ca1, ca2, ca3;
- private CheckoutAttributeValue cav1_1, cav1_2, cav2_1, cav2_2;
-
- [TestInitialize()]
- public void TestInitialize()
+ CommonPath.BaseDirectory = "";
+
+ //color choosing via DropDownList
+ ca1 = new CheckoutAttribute {
+ Id = "1",
+ Name = "Color",
+ TextPrompt = "Select color:",
+ IsRequired = true,
+ AttributeControlTypeId = AttributeControlType.DropdownList,
+ DisplayOrder = 1
+ };
+ cav1_1 = new CheckoutAttributeValue {
+ Id = "11",
+ Name = "Green",
+ DisplayOrder = 1,
+ //CheckoutAttribute = ca1,
+ CheckoutAttributeId = ca1.Id
+ };
+ cav1_2 = new CheckoutAttributeValue {
+ Id = "12",
+ Name = "Red",
+ DisplayOrder = 2,
+ //CheckoutAttribute = ca1,
+ CheckoutAttributeId = ca1.Id
+ };
+ ca1.CheckoutAttributeValues.Add(cav1_1);
+ ca1.CheckoutAttributeValues.Add(cav1_2);
+
+ //choosing via CheckBox'es
+ ca2 = new CheckoutAttribute {
+ Id = "2",
+ Name = "Custom option",
+ TextPrompt = "Select custom option:",
+ IsRequired = true,
+ AttributeControlTypeId = AttributeControlType.Checkboxes,
+ DisplayOrder = 2
+ //CheckoutAttributeValues
+ };
+
+ cav2_1 = new CheckoutAttributeValue {
+ Id = "21",
+ Name = "Option 1",
+ DisplayOrder = 1,
+ //CheckoutAttribute = ca2,
+ CheckoutAttributeId = ca2.Id
+ };
+ cav2_2 = new CheckoutAttributeValue {
+ Id = "22",
+ Name = "Option 2",
+ DisplayOrder = 2,
+ //CheckoutAttribute = ca2,
+ CheckoutAttributeId = ca2.Id
+ };
+ ca2.CheckoutAttributeValues.Add(cav2_1);
+ ca2.CheckoutAttributeValues.Add(cav2_2);
+
+ //via MultiTextBoxes
+ ca3 = new CheckoutAttribute {
+ Id = "3",
+ Name = "Custom text",
+ TextPrompt = "Enter custom text:",
+ IsRequired = true,
+ AttributeControlTypeId = AttributeControlType.MultilineTextbox,
+ DisplayOrder = 3
+ };
+
+ var tempEventPublisher = new Mock<IMediator>();
{
- CommonPath.BaseDirectory = "";
-
- //color choosing via DropDownList
- ca1 = new CheckoutAttribute {
- Id = "1",
- Name = "Color",
- TextPrompt = "Select color:",
- IsRequired = true,
- AttributeControlTypeId = AttributeControlType.DropdownList,
- DisplayOrder = 1
- };
- cav1_1 = new CheckoutAttributeValue {
- Id = "11",
- Name = "Green",
- DisplayOrder = 1,
- //CheckoutAttribute = ca1,
- CheckoutAttributeId = ca1.Id
- };
- cav1_2 = new CheckoutAttributeValue {
- Id = "12",
- Name = "Red",
- DisplayOrder = 2,
- //CheckoutAttribute = ca1,
- CheckoutAttributeId = ca1.Id
- };
- ca1.CheckoutAttributeValues.Add(cav1_1);
- ca1.CheckoutAttributeValues.Add(cav1_2);
-
- //choosing via CheckBox'es
- ca2 = new CheckoutAttribute {
- Id = "2",
- Name = "Custom option",
- TextPrompt = "Select custom option:",
- IsRequired = true,
- AttributeControlTypeId = AttributeControlType.Checkboxes,
- DisplayOrder = 2
- //CheckoutAttributeValues
- };
-
- cav2_1 = new CheckoutAttributeValue {
- Id = "21",
- Name = "Option 1",
- DisplayOrder = 1,
- //CheckoutAttribute = ca2,
- CheckoutAttributeId = ca2.Id
- };
- cav2_2 = new CheckoutAttributeValue {
- Id = "22",
- Name = "Option 2",
- DisplayOrder = 2,
- //CheckoutAttribute = ca2,
- CheckoutAttributeId = ca2.Id
- };
- ca2.CheckoutAttributeValues.Add(cav2_1);
- ca2.CheckoutAttributeValues.Add(cav2_2);
-
- //via MultiTextBoxes
- ca3 = new CheckoutAttribute {
- Id = "3",
- Name = "Custom text",
- TextPrompt = "Enter custom text:",
- IsRequired = true,
- AttributeControlTypeId = AttributeControlType.MultilineTextbox,
- DisplayOrder = 3
- };
-
- var tempEventPublisher = new Mock<IMediator>();
- {
- //tempEventPublisher.Setup(x => x.PublishAsync(It.IsAny<object>()));
- _eventPublisher = tempEventPublisher.Object;
- }
-
- var tempCheckoutAttributeRepo = new Mock<IRepository<CheckoutAttribute>>();
- {
- var IMongoCollection = new Mock<MongoRepository<CheckoutAttribute>>(Mock.Of<IAuditInfoProvider>()).Object;
- IMongoCollection.Insert(ca1);
- IMongoCollection.Insert(ca2);
- IMongoCollection.Insert(ca3);
- tempCheckoutAttributeRepo.Setup(x => x.Table).Returns(IMongoCollection.Table);
- tempCheckoutAttributeRepo.Setup(x => x.GetByIdAsync(ca1.Id)).ReturnsAsync(ca1);
- tempCheckoutAttributeRepo.Setup(x => x.GetByIdAsync(ca2.Id)).ReturnsAsync(ca2);
- tempCheckoutAttributeRepo.Setup(x => x.GetByIdAsync(ca3.Id)).ReturnsAsync(ca3);
- _checkoutAttributeRepo = tempCheckoutAttributeRepo.Object;
- }
-
- cacheManager = new Mock<ICacheBase>();
- _workContextMock = new Mock<IWorkContext>();
-
- _checkoutAttributeService = new CheckoutAttributeService(cacheManager.Object, _checkoutAttributeRepo,
- _eventPublisher, _workContextMock.Object, new AccessControlConfig());
-
- _checkoutAttributeParser = new CheckoutAttributeParser(_checkoutAttributeService);
-
-
-
- var workingLanguage = new Language();
- var tempWorkContext = new Mock<IWorkContext>();
- {
- tempWorkContext.Setup(x => x.WorkingLanguage).Returns(workingLanguage);
- }
+ //tempEventPublisher.Setup(x => x.PublishAsync(It.IsAny<object>()));
+ _eventPublisher = tempEventPublisher.Object;
}
- [TestMethod()]
- public void Can_add_checkoutAttributes()
+ var tempCheckoutAttributeRepo = new Mock<IRepository<CheckoutAttribute>>();
{
- IList<CustomAttribute> attributes = new List<CustomAttribute>();
- //color: green
- attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca1, cav1_1.Id).ToList();
- //custom option: option 1, option 2
- attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca2, cav2_1.Id).ToList();
- attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca2, cav2_2.Id).ToList();
- //custom text
- attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca3, "absolutely any value").ToList();
-
- Assert.IsTrue(attributes.Count == 4);
- Assert.IsTrue(attributes.Any(c => c.Key.Equals(ca1.Id)));
- Assert.IsTrue(attributes.Any(c => c.Key.Equals(ca2.Id)));
- Assert.IsTrue(attributes.Any(c => c.Key.Equals(ca3.Id)));
- attributes = _checkoutAttributeParser.RemoveCheckoutAttribute(attributes, ca1);
- Assert.IsTrue(attributes.Count == 3);
- Assert.IsFalse(attributes.Any(c => c.Key.Equals(ca1.Id)));
+ var IMongoCollection = new Mock<MongoRepository<CheckoutAttribute>>(Mock.Of<IAuditInfoProvider>()).Object;
+ IMongoCollection.Insert(ca1);
+ IMongoCollection.Insert(ca2);
+ IMongoCollection.Insert(ca3);
+ tempCheckoutAttributeRepo.Setup(x => x.Table).Returns(IMongoCollection.Table);
+ tempCheckoutAttributeRepo.Setup(x => x.GetByIdAsync(ca1.Id)).ReturnsAsync(ca1);
+ tempCheckoutAttributeRepo.Setup(x => x.GetByIdAsync(ca2.Id)).ReturnsAsync(ca2);
+ tempCheckoutAttributeRepo.Setup(x => x.GetByIdAsync(ca3.Id)).ReturnsAsync(ca3);
+ _checkoutAttributeRepo = tempCheckoutAttributeRepo.Object;
+ }
+
+ cacheManager = new Mock<ICacheBase>();
+ _workContextMock = new Mock<IWorkContext>();
+ _checkoutAttributeService = new CheckoutAttributeService(cacheManager.Object, _checkoutAttributeRepo,
+ _eventPublisher, _workContextMock.Object, new AccessControlConfig());
+
+ _checkoutAttributeParser = new CheckoutAttributeParser(_checkoutAttributeService);
+
+
+ var workingLanguage = new Language();
+ var tempWorkContext = new Mock<IWorkContext>();
+ {
+ tempWorkContext.Setup(x => x.WorkingLanguage).Returns(workingLanguage);
}
}
-}
+
+ [TestMethod]
+ public void Can_add_checkoutAttributes()
+ {
+ IList<CustomAttribute> attributes = new List<CustomAttribute>();
+ //color: green
+ attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca1, cav1_1.Id).ToList();
+ //custom option: option 1, option 2
+ attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca2, cav2_1.Id).ToList();
+ attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca2, cav2_2.Id).ToList();
+ //custom text
+ attributes = _checkoutAttributeParser.AddCheckoutAttribute(attributes, ca3, "absolutely any value").ToList();
+
+ Assert.IsTrue(attributes.Count == 4);
+ Assert.IsTrue(attributes.Any(c => c.Key.Equals(ca1.Id)));
+ Assert.IsTrue(attributes.Any(c => c.Key.Equals(ca2.Id)));
+ Assert.IsTrue(attributes.Any(c => c.Key.Equals(ca3.Id)));
+ attributes = _checkoutAttributeParser.RemoveCheckoutAttribute(attributes, ca1);
+ Assert.IsTrue(attributes.Count == 3);
+ Assert.IsFalse(attributes.Any(c => c.Key.Equals(ca1.Id)));
+ }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs
index 3b7af3ed3..67ddaee15 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/CheckoutAttributes/CheckoutAttributeServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;
-using Grand.Business.Checkout.Services.CheckoutAttributes;
+using Grand.Business.Checkout.Services.CheckoutAttributes;
+using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;
using Grand.Data;
using Grand.Domain.Orders;
using Grand.Infrastructure;
@@ -10,70 +10,70 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.CheckoutAttributes
+namespace Grand.Business.Checkout.Tests.Services.CheckoutAttributes;
+
+[TestClass]
+public class CheckoutAttributeServiceTests
{
- [TestClass]
- public class CheckoutAttributeServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<IRepository<CheckoutAttribute>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IWorkContext> _workContextMock;
- private ICheckoutAttributeService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<CheckoutAttribute>> _repositoryMock;
+ private ICheckoutAttributeService _service;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _repositoryMock = new Mock<IRepository<CheckoutAttribute>>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _service = new CheckoutAttributeService(_cacheMock.Object, _repositoryMock.Object, _mediatorMock.Object, _workContextMock.Object, new AccessControlConfig());
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _repositoryMock = new Mock<IRepository<CheckoutAttribute>>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
+ _service = new CheckoutAttributeService(_cacheMock.Object, _repositoryMock.Object, _mediatorMock.Object,
+ _workContextMock.Object, new AccessControlConfig());
+ }
- [TestMethod]
- public async Task InsertCheckoutAttribute_InvokeExpectedMethods()
- {
- await _service.InsertCheckoutAttribute(new CheckoutAttribute());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CheckoutAttribute>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CheckoutAttribute>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertCheckoutAttribute_InvokeExpectedMethods()
+ {
+ await _service.InsertCheckoutAttribute(new CheckoutAttribute());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CheckoutAttribute>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CheckoutAttribute>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertCheckoutAttribute_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertCheckoutAttribute(null));
- }
+ [TestMethod]
+ public void InsertCheckoutAttribute_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertCheckoutAttribute(null));
+ }
- [TestMethod]
- public async Task UpdateCheckoutAttribute_InvokeExpectedMethods()
- {
- await _service.UpdateCheckoutAttribute(new CheckoutAttribute());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CheckoutAttribute>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CheckoutAttribute>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateCheckoutAttribute_InvokeExpectedMethods()
+ {
+ await _service.UpdateCheckoutAttribute(new CheckoutAttribute());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CheckoutAttribute>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CheckoutAttribute>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateCheckoutAttribute_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateCheckoutAttribute(null));
- }
+ [TestMethod]
+ public void UpdateCheckoutAttribute_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateCheckoutAttribute(null));
+ }
- [TestMethod]
- public async Task DeleteCheckoutAttribute_InvokeExpectedMethods()
- {
- await _service.DeleteCheckoutAttribute(new CheckoutAttribute());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CheckoutAttribute>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CheckoutAttribute>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteCheckoutAttribute_InvokeExpectedMethods()
+ {
+ await _service.DeleteCheckoutAttribute(new CheckoutAttribute());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CheckoutAttribute>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CheckoutAttribute>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeleteCheckoutAttribute_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteCheckoutAttribute(null));
- }
+ [TestMethod]
+ public void DeleteCheckoutAttribute_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteCheckoutAttribute(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/GiftVouchers/GiftVoucherServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/GiftVouchers/GiftVoucherServiceTests.cs
index 407a99622..4e263a50b 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/GiftVouchers/GiftVoucherServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/GiftVouchers/GiftVoucherServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;
-using Grand.Business.Checkout.Services.GiftVouchers;
+using Grand.Business.Checkout.Services.GiftVouchers;
+using Grand.Business.Core.Interfaces.Checkout.GiftVouchers;
using Grand.Data;
using Grand.Domain.Orders;
using Grand.Infrastructure.Events;
@@ -7,78 +7,77 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.GiftVouchers
+namespace Grand.Business.Checkout.Tests.Services.GiftVouchers;
+
+[TestClass]
+public class GiftVoucherServiceTests
{
- [TestClass]
- public class GiftVoucherServiceTests
- {
- private Mock<IRepository<GiftVoucher>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private IGiftVoucherService _service;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<GiftVoucher>> _repositoryMock;
+ private IGiftVoucherService _service;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<GiftVoucher>>();
- _mediatorMock = new Mock<IMediator>();
- _service = new GiftVoucherService(_repositoryMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<GiftVoucher>>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new GiftVoucherService(_repositoryMock.Object, _mediatorMock.Object);
+ }
- [TestMethod]
- public void GenerateGiftVoucherCode_ShouldReturnUniqueValues()
- {
- var results = new List<string>();
- results.Add(_service.GenerateGiftVoucherCode());
- results.Add(_service.GenerateGiftVoucherCode());
- results.Add(_service.GenerateGiftVoucherCode());
- results.Add(_service.GenerateGiftVoucherCode());
- results.Add(_service.GenerateGiftVoucherCode());
- results.Add(_service.GenerateGiftVoucherCode());
- results.Add(_service.GenerateGiftVoucherCode());
+ [TestMethod]
+ public void GenerateGiftVoucherCode_ShouldReturnUniqueValues()
+ {
+ var results = new List<string>();
+ results.Add(_service.GenerateGiftVoucherCode());
+ results.Add(_service.GenerateGiftVoucherCode());
+ results.Add(_service.GenerateGiftVoucherCode());
+ results.Add(_service.GenerateGiftVoucherCode());
+ results.Add(_service.GenerateGiftVoucherCode());
+ results.Add(_service.GenerateGiftVoucherCode());
+ results.Add(_service.GenerateGiftVoucherCode());
- Assert.IsTrue(results.Count.Equals(results.Distinct().Count()));
- }
+ Assert.IsTrue(results.Count.Equals(results.Distinct().Count()));
+ }
- [TestMethod]
- public async Task InsertGiftVoucher_InovokeExpectedMethods()
- {
- await _service.InsertGiftVoucher(new GiftVoucher { Code = "code" });
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<GiftVoucher>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<GiftVoucher>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertGiftVoucher_InovokeExpectedMethods()
+ {
+ await _service.InsertGiftVoucher(new GiftVoucher { Code = "code" });
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<GiftVoucher>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<GiftVoucher>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertGiftVoucher_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertGiftVoucher(null));
- }
+ [TestMethod]
+ public void InsertGiftVoucher_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertGiftVoucher(null));
+ }
- [TestMethod]
- public async Task UpdateGiftVoucher_InovokeExpectedMethods()
- {
- await _service.UpdateGiftVoucher(new GiftVoucher { Code = "code" });
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<GiftVoucher>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<GiftVoucher>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateGiftVoucher_InovokeExpectedMethods()
+ {
+ await _service.UpdateGiftVoucher(new GiftVoucher { Code = "code" });
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<GiftVoucher>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<GiftVoucher>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateGiftVoucher_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateGiftVoucher(null));
- }
+ [TestMethod]
+ public void UpdateGiftVoucher_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateGiftVoucher(null));
+ }
- [TestMethod]
- public async Task DeleteGiftVoucher_InovokeExpectedMethods()
- {
- await _service.DeleteGiftVoucher(new GiftVoucher());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<GiftVoucher>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<GiftVoucher>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteGiftVoucher_InovokeExpectedMethods()
+ {
+ await _service.DeleteGiftVoucher(new GiftVoucher());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<GiftVoucher>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<GiftVoucher>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeleteGiftVoucher_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteGiftVoucher(null));
- }
+ [TestMethod]
+ public void DeleteGiftVoucher_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteGiftVoucher(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/LoyaltyPointsServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/LoyaltyPointsServiceTests.cs
index 3f9233beb..b09fc8a27 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/LoyaltyPointsServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/LoyaltyPointsServiceTests.cs
@@ -1,65 +1,70 @@
using Grand.Business.Checkout.Services.Orders;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Orders;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Orders
-{
- [TestClass()]
- public class LoyaltyPointsServiceTests
- {
- private LoyaltyPointsService _loyaltyPointsService;
- private IRepository<LoyaltyPointsHistory> _repository;
- private Mock<IMediator> _mediatorMock;
+namespace Grand.Business.Checkout.Tests.Services.Orders;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<LoyaltyPointsHistory>();
- _mediatorMock = new Mock<IMediator>();
+[TestClass]
+public class LoyaltyPointsServiceTests
+{
+ private LoyaltyPointsService _loyaltyPointsService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<LoyaltyPointsHistory> _repository;
- _loyaltyPointsService = new LoyaltyPointsService(_repository, new LoyaltyPointsSettings { }, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<LoyaltyPointsHistory>();
+ _mediatorMock = new Mock<IMediator>();
- [TestMethod()]
- public async Task GetLoyaltyPointsBalanceTest()
- {
- //Assert
- await _repository.InsertAsync(new LoyaltyPointsHistory { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 10 });
- await _repository.InsertAsync(new LoyaltyPointsHistory { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 20 });
- await _repository.InsertAsync(new LoyaltyPointsHistory { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 30 });
- //Act
- var result = await _loyaltyPointsService.GetLoyaltyPointsBalance("1", "");
- //Assert
- Assert.AreEqual(30, result);
+ _loyaltyPointsService =
+ new LoyaltyPointsService(_repository, new LoyaltyPointsSettings(), _mediatorMock.Object);
+ }
- }
+ [TestMethod]
+ public async Task GetLoyaltyPointsBalanceTest()
+ {
+ //Assert
+ await _repository.InsertAsync(new LoyaltyPointsHistory
+ { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 10 });
+ await _repository.InsertAsync(new LoyaltyPointsHistory
+ { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 20 });
+ await _repository.InsertAsync(new LoyaltyPointsHistory
+ { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 30 });
+ //Act
+ var result = await _loyaltyPointsService.GetLoyaltyPointsBalance("1", "");
+ //Assert
+ Assert.AreEqual(30, result);
+ }
- [TestMethod()]
- public async Task AddLoyaltyPointsHistoryTest()
- {
- //Act
- var result = await _loyaltyPointsService.AddLoyaltyPointsHistory("1", 10, "");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(10, result.Points);
- Assert.IsTrue(_repository.Table.Any());
- }
+ [TestMethod]
+ public async Task AddLoyaltyPointsHistoryTest()
+ {
+ //Act
+ var result = await _loyaltyPointsService.AddLoyaltyPointsHistory("1", 10, "");
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(10, result.Points);
+ Assert.IsTrue(_repository.Table.Any());
+ }
- [TestMethod()]
- public async Task GetLoyaltyPointsHistoryTest()
- {
- //Assert
- await _repository.InsertAsync(new LoyaltyPointsHistory { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 10 });
- await _repository.InsertAsync(new LoyaltyPointsHistory { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 20 });
- await _repository.InsertAsync(new LoyaltyPointsHistory { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 30 });
- //Act
- var result = await _loyaltyPointsService.GetLoyaltyPointsHistory("1");
- //Assert
- Assert.AreEqual(3, result.Count);
- }
+ [TestMethod]
+ public async Task GetLoyaltyPointsHistoryTest()
+ {
+ //Assert
+ await _repository.InsertAsync(new LoyaltyPointsHistory
+ { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 10 });
+ await _repository.InsertAsync(new LoyaltyPointsHistory
+ { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 20 });
+ await _repository.InsertAsync(new LoyaltyPointsHistory
+ { CustomerId = "1", StoreId = "", Points = 10, PointsBalance = 30 });
+ //Act
+ var result = await _loyaltyPointsService.GetLoyaltyPointsHistory("1");
+ //Assert
+ Assert.AreEqual(3, result.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/MerchandiseReturnServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/MerchandiseReturnServiceTests.cs
index 20817be92..155a6dad3 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/MerchandiseReturnServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/MerchandiseReturnServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Checkout.Services.Orders;
using Grand.Business.Core.Queries.Checkout.Orders;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Orders;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -10,312 +10,315 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Orders
+namespace Grand.Business.Checkout.Tests.Services.Orders;
+
+[TestClass]
+public class MerchandiseReturnServiceTests
{
- [TestClass()]
- public class MerchandiseReturnServiceTests
+ private MemoryCacheBase _cacheBase;
+
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<MerchandiseReturnAction> _merchandiseReturnActionRepository;
+ private IRepository<MerchandiseReturnNote> _merchandiseReturnNoteRepository;
+ private IRepository<MerchandiseReturnReason> _merchandiseReturnReasonRepository;
+ private MerchandiseReturnService _merchandiseReturnService;
+
+ private IRepository<MerchandiseReturn> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<MerchandiseReturn>();
+ _merchandiseReturnActionRepository = new MongoDBRepositoryTest<MerchandiseReturnAction>();
+ _merchandiseReturnReasonRepository = new MongoDBRepositoryTest<MerchandiseReturnReason>();
+ _merchandiseReturnNoteRepository = new MongoDBRepositoryTest<MerchandiseReturnNote>();
+
+ _mediatorMock = new Mock<IMediator>();
+
+ var query = from p in _repository.Table
+ select p;
+ _mediatorMock.Setup(x => x.Send(It.IsAny<GetMerchandiseReturnQuery>(), default))
+ .Returns(Task.FromResult(query));
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _merchandiseReturnService = new MerchandiseReturnService(_repository, _merchandiseReturnActionRepository,
+ _merchandiseReturnReasonRepository, _merchandiseReturnNoteRepository, _cacheBase, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetMerchandiseReturnByIdTest()
+ {
+ //Arange
+ var merchandiseReturn = new MerchandiseReturn();
+ await _repository.InsertAsync(merchandiseReturn);
+
+ //Act
+ var result = _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturn.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetMerchandiseReturnByIdTest_ReturnNumber()
+ {
+ //Arange
+ var merchandiseReturn = new MerchandiseReturn { ReturnNumber = 1 };
+ await _repository.InsertAsync(merchandiseReturn);
+
+ //Act
+ var result = _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturn.ReturnNumber);
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task SearchMerchandiseReturnsTest()
+ {
+ //Arange
+ var merchandiseReturn = new MerchandiseReturn();
+ await _repository.InsertAsync(merchandiseReturn);
+
+ //Act
+ var result = await _merchandiseReturnService.SearchMerchandiseReturns();
+
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetAllMerchandiseReturnActionsTest()
+ {
+ //Arrange
+ await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction());
+ await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction());
+
+ //Act
+ var result = await _merchandiseReturnService.GetAllMerchandiseReturnActions();
+
+ //Assert
+ Assert.IsTrue(result.Any());
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetMerchandiseReturnActionByIdTest()
+ {
+ //Arrange
+ await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction { Id = "1" });
+ await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction());
+
+ //Act
+ var result = await _merchandiseReturnService.GetMerchandiseReturnActionById("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task InsertMerchandiseReturnTest()
+ {
+ //Act
+ await _merchandiseReturnService.InsertMerchandiseReturn(new MerchandiseReturn());
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateMerchandiseReturnTest()
+ {
+ //Arange
+ var merchandiseReturn = new MerchandiseReturn();
+ await _repository.InsertAsync(merchandiseReturn);
+
+ //Act
+ merchandiseReturn.CustomerComments = "test";
+ await _merchandiseReturnService.UpdateMerchandiseReturn(merchandiseReturn);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == merchandiseReturn.Id).CustomerComments == "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteMerchandiseReturnTest()
+ {
+ //Arange
+ var merchandiseReturn = new MerchandiseReturn();
+ await _repository.InsertAsync(merchandiseReturn);
+
+ //Act
+ await _merchandiseReturnService.DeleteMerchandiseReturn(merchandiseReturn);
+
+ //Assert
+ Assert.IsFalse(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertMerchandiseReturnActionTest()
+ {
+ //Act
+ await _merchandiseReturnService.InsertMerchandiseReturnAction(new MerchandiseReturnAction());
+
+ //Assert
+ Assert.IsTrue(_merchandiseReturnActionRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateMerchandiseReturnActionTest()
+ {
+ //Arange
+ var merchandiseReturnAction = new MerchandiseReturnAction();
+ await _merchandiseReturnActionRepository.InsertAsync(merchandiseReturnAction);
+
+ //Act
+ merchandiseReturnAction.Name = "test";
+ await _merchandiseReturnService.UpdateMerchandiseReturnAction(merchandiseReturnAction);
+
+ //Assert
+ Assert.IsTrue(_merchandiseReturnActionRepository.Table.FirstOrDefault(x => x.Id == merchandiseReturnAction.Id)
+ .Name == "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteMerchandiseReturnActionTest()
{
- private MerchandiseReturnService _merchandiseReturnService;
-
- private IRepository<MerchandiseReturn> _repository;
- private IRepository<MerchandiseReturnAction> _merchandiseReturnActionRepository;
- private IRepository<MerchandiseReturnReason> _merchandiseReturnReasonRepository;
- private IRepository<MerchandiseReturnNote> _merchandiseReturnNoteRepository;
-
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<MerchandiseReturn>();
- _merchandiseReturnActionRepository = new MongoDBRepositoryTest<MerchandiseReturnAction>();
- _merchandiseReturnReasonRepository = new MongoDBRepositoryTest<MerchandiseReturnReason>();
- _merchandiseReturnNoteRepository = new MongoDBRepositoryTest<MerchandiseReturnNote>();
-
- _mediatorMock = new Mock<IMediator>();
-
- var query = from p in _repository.Table
- select p;
- _mediatorMock.Setup(x => x.Send(It.IsAny<GetMerchandiseReturnQuery>(), default))
- .Returns(Task.FromResult(query));
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _merchandiseReturnService = new MerchandiseReturnService(_repository, _merchandiseReturnActionRepository, _merchandiseReturnReasonRepository, _merchandiseReturnNoteRepository, _cacheBase, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetMerchandiseReturnByIdTest()
- {
- //Arange
- var merchandiseReturn = new MerchandiseReturn();
- await _repository.InsertAsync(merchandiseReturn);
-
- //Act
- var result = _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturn.Id);
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetMerchandiseReturnByIdTest_ReturnNumber()
- {
- //Arange
- var merchandiseReturn = new MerchandiseReturn { ReturnNumber = 1 };
- await _repository.InsertAsync(merchandiseReturn);
-
- //Act
- var result = _merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturn.ReturnNumber);
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task SearchMerchandiseReturnsTest()
- {
- //Arange
- var merchandiseReturn = new MerchandiseReturn();
- await _repository.InsertAsync(merchandiseReturn);
-
- //Act
- var result = await _merchandiseReturnService.SearchMerchandiseReturns();
-
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetAllMerchandiseReturnActionsTest()
- {
- //Arrange
- await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction());
- await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction());
-
- //Act
- var result = await _merchandiseReturnService.GetAllMerchandiseReturnActions();
-
- //Assert
- Assert.IsTrue(result.Any());
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task GetMerchandiseReturnActionByIdTest()
- {
- //Arrange
- await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction { Id = "1" });
- await _merchandiseReturnActionRepository.InsertAsync(new MerchandiseReturnAction());
-
- //Act
- var result = await _merchandiseReturnService.GetMerchandiseReturnActionById("1");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task InsertMerchandiseReturnTest()
- {
- //Act
- await _merchandiseReturnService.InsertMerchandiseReturn(new MerchandiseReturn());
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateMerchandiseReturnTest()
- {
- //Arange
- var merchandiseReturn = new MerchandiseReturn();
- await _repository.InsertAsync(merchandiseReturn);
-
- //Act
- merchandiseReturn.CustomerComments = "test";
- await _merchandiseReturnService.UpdateMerchandiseReturn(merchandiseReturn);
-
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x=>x.Id == merchandiseReturn.Id).CustomerComments == "test");
- }
-
- [TestMethod()]
- public async Task DeleteMerchandiseReturnTest()
- {
- //Arange
- var merchandiseReturn = new MerchandiseReturn();
- await _repository.InsertAsync(merchandiseReturn);
-
- //Act
- await _merchandiseReturnService.DeleteMerchandiseReturn(merchandiseReturn);
-
- //Assert
- Assert.IsFalse(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task InsertMerchandiseReturnActionTest()
- {
- //Act
- await _merchandiseReturnService.InsertMerchandiseReturnAction(new MerchandiseReturnAction());
-
- //Assert
- Assert.IsTrue(_merchandiseReturnActionRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateMerchandiseReturnActionTest()
- {
- //Arange
- var merchandiseReturnAction = new MerchandiseReturnAction();
- await _merchandiseReturnActionRepository.InsertAsync(merchandiseReturnAction);
-
- //Act
- merchandiseReturnAction.Name = "test";
- await _merchandiseReturnService.UpdateMerchandiseReturnAction(merchandiseReturnAction);
-
- //Assert
- Assert.IsTrue(_merchandiseReturnActionRepository.Table.FirstOrDefault(x => x.Id == merchandiseReturnAction.Id).Name == "test");
- }
-
- [TestMethod()]
- public async Task DeleteMerchandiseReturnActionTest()
- {
- //Arange
- var merchandiseReturnAction = new MerchandiseReturnAction();
- await _merchandiseReturnActionRepository.InsertAsync(merchandiseReturnAction);
-
- //Act
- await _merchandiseReturnService.DeleteMerchandiseReturnAction(merchandiseReturnAction);
-
- //Assert
- Assert.IsFalse(_merchandiseReturnActionRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task DeleteMerchandiseReturnReasonTest()
- {
- //Arange
- var merchandiseReturnReason = new MerchandiseReturnReason();
- await _merchandiseReturnReasonRepository.InsertAsync(merchandiseReturnReason);
-
- //Act
- await _merchandiseReturnService.DeleteMerchandiseReturnReason(merchandiseReturnReason);
-
- //Assert
- Assert.IsFalse(_merchandiseReturnReasonRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetAllMerchandiseReturnReasonsTest()
- {
- //Arrange
- await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason { Id = "1" });
- await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason());
-
- //Act
- var result = await _merchandiseReturnService.GetAllMerchandiseReturnReasons();
-
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task GetMerchandiseReturnReasonByIdTest()
- {
- //Arrange
- await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason { Id = "1" });
- await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason());
-
- //Act
- var result = await _merchandiseReturnService.GetMerchandiseReturnReasonById("1");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task InsertMerchandiseReturnReasonTest()
- {
- //Arange
- var merchandiseReturnReason = new MerchandiseReturnReason();
-
- //Act
- await _merchandiseReturnService.InsertMerchandiseReturnReason(merchandiseReturnReason);
-
- //Assert
- Assert.IsTrue(_merchandiseReturnReasonRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateMerchandiseReturnReasonTest()
- {
- //Arange
- var merchandiseReturnReason = new MerchandiseReturnReason();
- await _merchandiseReturnReasonRepository.InsertAsync(merchandiseReturnReason);
- //Act
- merchandiseReturnReason.Name = "test";
- await _merchandiseReturnService.UpdateMerchandiseReturnReason(merchandiseReturnReason);
-
- //Assert
- Assert.IsTrue(_merchandiseReturnReasonRepository.Table.FirstOrDefault(x => x.Id == merchandiseReturnReason.Id).Name == "test");
- }
-
- [TestMethod()]
- public async Task DeleteMerchandiseReturnNoteTest()
- {
- //Arange
- var merchandiseReturnNote = new MerchandiseReturnNote();
- await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);
-
- //Act
- await _merchandiseReturnService.DeleteMerchandiseReturnNote(merchandiseReturnNote);
-
- //Assert
- Assert.IsFalse(_merchandiseReturnNoteRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task InsertMerchandiseReturnNoteTest()
- {
- //Arange
- var merchandiseReturnNote = new MerchandiseReturnNote();
-
- //Act
- await _merchandiseReturnService.InsertMerchandiseReturnNote(merchandiseReturnNote);
-
- //Assert
- Assert.IsTrue(_merchandiseReturnNoteRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetMerchandiseReturnNotesTest()
- {
- //Arange
- var merchandiseReturnNote = new MerchandiseReturnNote { MerchandiseReturnId = "1" };
- await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);
-
- //Act
- var result = await _merchandiseReturnService.GetMerchandiseReturnNotes("1");
-
- //Assert
- Assert.AreEqual(1, result.Count);
- }
-
- [TestMethod()]
- public async Task GetMerchandiseReturnNoteTest()
- {
- //Arange
- var merchandiseReturnNote = new MerchandiseReturnNote { Id = "1" };
- await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);
-
- //Act
- var result = await _merchandiseReturnService.GetMerchandiseReturnNote("1");
-
- //Assert
- Assert.IsNotNull(result);
- }
+ //Arange
+ var merchandiseReturnAction = new MerchandiseReturnAction();
+ await _merchandiseReturnActionRepository.InsertAsync(merchandiseReturnAction);
+
+ //Act
+ await _merchandiseReturnService.DeleteMerchandiseReturnAction(merchandiseReturnAction);
+
+ //Assert
+ Assert.IsFalse(_merchandiseReturnActionRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task DeleteMerchandiseReturnReasonTest()
+ {
+ //Arange
+ var merchandiseReturnReason = new MerchandiseReturnReason();
+ await _merchandiseReturnReasonRepository.InsertAsync(merchandiseReturnReason);
+
+ //Act
+ await _merchandiseReturnService.DeleteMerchandiseReturnReason(merchandiseReturnReason);
+
+ //Assert
+ Assert.IsFalse(_merchandiseReturnReasonRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task GetAllMerchandiseReturnReasonsTest()
+ {
+ //Arrange
+ await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason { Id = "1" });
+ await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason());
+
+ //Act
+ var result = await _merchandiseReturnService.GetAllMerchandiseReturnReasons();
+
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetMerchandiseReturnReasonByIdTest()
+ {
+ //Arrange
+ await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason { Id = "1" });
+ await _merchandiseReturnReasonRepository.InsertAsync(new MerchandiseReturnReason());
+
+ //Act
+ var result = await _merchandiseReturnService.GetMerchandiseReturnReasonById("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task InsertMerchandiseReturnReasonTest()
+ {
+ //Arange
+ var merchandiseReturnReason = new MerchandiseReturnReason();
+
+ //Act
+ await _merchandiseReturnService.InsertMerchandiseReturnReason(merchandiseReturnReason);
+
+ //Assert
+ Assert.IsTrue(_merchandiseReturnReasonRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateMerchandiseReturnReasonTest()
+ {
+ //Arange
+ var merchandiseReturnReason = new MerchandiseReturnReason();
+ await _merchandiseReturnReasonRepository.InsertAsync(merchandiseReturnReason);
+ //Act
+ merchandiseReturnReason.Name = "test";
+ await _merchandiseReturnService.UpdateMerchandiseReturnReason(merchandiseReturnReason);
+
+ //Assert
+ Assert.IsTrue(_merchandiseReturnReasonRepository.Table.FirstOrDefault(x => x.Id == merchandiseReturnReason.Id)
+ .Name == "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteMerchandiseReturnNoteTest()
+ {
+ //Arange
+ var merchandiseReturnNote = new MerchandiseReturnNote();
+ await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);
+
+ //Act
+ await _merchandiseReturnService.DeleteMerchandiseReturnNote(merchandiseReturnNote);
+
+ //Assert
+ Assert.IsFalse(_merchandiseReturnNoteRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertMerchandiseReturnNoteTest()
+ {
+ //Arange
+ var merchandiseReturnNote = new MerchandiseReturnNote();
+
+ //Act
+ await _merchandiseReturnService.InsertMerchandiseReturnNote(merchandiseReturnNote);
+
+ //Assert
+ Assert.IsTrue(_merchandiseReturnNoteRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task GetMerchandiseReturnNotesTest()
+ {
+ //Arange
+ var merchandiseReturnNote = new MerchandiseReturnNote { MerchandiseReturnId = "1" };
+ await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);
+
+ //Act
+ var result = await _merchandiseReturnService.GetMerchandiseReturnNotes("1");
+
+ //Assert
+ Assert.AreEqual(1, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetMerchandiseReturnNoteTest()
+ {
+ //Arange
+ var merchandiseReturnNote = new MerchandiseReturnNote { Id = "1" };
+ await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote);
+
+ //Act
+ var result = await _merchandiseReturnService.GetMerchandiseReturnNote("1");
+
+ //Assert
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
index 107c9b869..4670e196b 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderCalculationServiceTests.cs
@@ -16,219 +16,263 @@ using Grand.Domain.Directory;
using Grand.Domain.Discounts;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
+using Grand.Domain.Stores;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Orders
+namespace Grand.Business.Checkout.Tests.Services.Orders;
+
+[TestClass]
+public class OrderCalculationServiceTests
{
- [TestClass()]
- public class OrderCalculationServiceTests
+ private CatalogSettings _catalogSettings;
+ private Mock<ICheckoutAttributeParser> _checkoutAttributeParserMock;
+ private Mock<ICurrencyService> _currencyServiceMock;
+ private Mock<IDiscountService> _discountServiceMock;
+ private Mock<IDiscountValidationService> _discountValidationService;
+ private Mock<IGiftVoucherService> _giftVoucherServiceMock;
+ private Mock<IGroupService> _groupServiceMock;
+ private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
+ private LoyaltyPointsSettings _loyaltyPointsSettings;
+ private Mock<IPaymentService> _paymentServiceMock;
+ private Mock<IPricingService> _pricingServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private OrderCalculationService _service;
+ private Mock<IShippingService> _shippingServiceMock;
+ private ShippingSettings _shippingSettings;
+ private ShoppingCartSettings _shoppingCartSettings;
+ private Mock<ITaxService> _taxServiceMock;
+ private TaxSettings _taxSettings;
+
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _workContextMock = new Mock<IWorkContext>();
+ _pricingServiceMock = new Mock<IPricingService>();
+ _taxServiceMock = new Mock<ITaxService>();
+ _shippingServiceMock = new Mock<IShippingService>();
+ _paymentServiceMock = new Mock<IPaymentService>();
+ _checkoutAttributeParserMock = new Mock<ICheckoutAttributeParser>();
+ _discountServiceMock = new Mock<IDiscountService>();
+ _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
+ _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
+ _productServiceMock = new Mock<IProductService>();
+ _currencyServiceMock = new Mock<ICurrencyService>();
+ _groupServiceMock = new Mock<IGroupService>();
+ _taxSettings = new TaxSettings();
+ _loyaltyPointsSettings = new LoyaltyPointsSettings();
+ _shippingSettings = new ShippingSettings();
+ _shoppingCartSettings = new ShoppingCartSettings();
+ _catalogSettings = new CatalogSettings();
+ _discountValidationService = new Mock<IDiscountValidationService>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkingCurrency).Returns(() => new Currency());
+ _workContextMock.Setup(c => c.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
+
+ _service = new OrderCalculationService(_workContextMock.Object, _pricingServiceMock.Object,
+ _taxServiceMock.Object, _shippingServiceMock.Object,
+ _paymentServiceMock.Object, _checkoutAttributeParserMock.Object, _discountServiceMock.Object,
+ _giftVoucherServiceMock.Object,
+ _loyaltyPointsServiceMock.Object, _productServiceMock.Object, _currencyServiceMock.Object,
+ _groupServiceMock.Object, _discountValidationService.Object,
+ _taxSettings, _loyaltyPointsSettings, _shippingSettings, _shoppingCartSettings, _catalogSettings);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartSubTotalTest()
+ {
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>()))
+ .Returns(() =>
+ Task.FromResult(
+ (IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)
+ new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
+ _discountServiceMock
+ .Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<Discount>)new List<Discount>()));
+
+ var shoppingCartItem = new List<ShoppingCartItem> { new() { Quantity = 1 } };
+ var result = await _service.GetShoppingCartSubTotal(shoppingCartItem, false);
+
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartAdditionalShippingChargeTest()
+ {
+ //Arrange
+ var cgs = new List<CustomerGroup> { new() };
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
+
+ var shoppingCartItem = new List<ShoppingCartItem>
+ { new() { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10 } };
+ //Act
+ var result = await _service.GetShoppingCartAdditionalShippingCharge(shoppingCartItem);
+ //Assert
+ Assert.AreEqual(10, result);
+ }
+
+ [TestMethod]
+ public async Task IsFreeShippingTest()
+ {
+ //Arrange
+ var cgs = new List<CustomerGroup> { new() };
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
+
+ var shoppingCartItem = new List<ShoppingCartItem> {
+ new() { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true }
+ };
+ //Act
+ var result = await _service.GetShoppingCartAdditionalShippingCharge(shoppingCartItem);
+ //Assert
+ Assert.AreEqual(0, result);
+ }
+
+ [TestMethod]
+ public async Task AdjustShippingRateTest()
+ {
+ //Arrange
+ var cgs = new List<CustomerGroup> { new() };
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
+
+ var shoppingCartItem = new List<ShoppingCartItem>
+ { new() { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10 } };
+ //Act
+ var result = await _service.AdjustShippingRate(10, shoppingCartItem);
+
+ //Assert
+ Assert.AreEqual(20, result.shippingRate);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartShippingTotalTest()
+ {
+ //Arrange
+ var cgs = new List<CustomerGroup> { new() };
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>()))
+ .Returns(() =>
+ Task.FromResult(
+ (IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)
+ new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
+ _discountServiceMock
+ .Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<Discount>)new List<Discount>()));
+
+ var shoppingCartItem = new List<ShoppingCartItem> {
+ new() { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true }
+ };
+ //Act
+ var result = await _service.GetShoppingCartShippingTotal(shoppingCartItem);
+
+ //Assert
+ Assert.AreEqual(0, result.shoppingCartShippingTotal);
+ }
+
+ [TestMethod]
+ public async Task GetTaxTotalTest()
+ {
+ //TODO
+ //Arrange
+ var cgs = new List<CustomerGroup> { new() };
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>()))
+ .Returns(() =>
+ Task.FromResult(
+ (IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)
+ new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
+ _discountServiceMock
+ .Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<Discount>)new List<Discount>()));
+
+ var shoppingCartItem = new List<ShoppingCartItem> {
+ new() { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true }
+ };
+ //Act
+ var result = await _service.GetTaxTotal(shoppingCartItem, false);
+ //Assert
+ Assert.AreEqual(0, result.taxtotal);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartTotalTest()
+ {
+ //TODO
+ //Arrange
+ var cgs = new List<CustomerGroup> { new() };
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>()))
+ .Returns(() =>
+ Task.FromResult(
+ (IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)
+ new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
+ _discountServiceMock
+ .Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<Discount>)new List<Discount>()));
+
+ var shoppingCartItem = new List<ShoppingCartItem> {
+ new() { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true }
+ };
+ //Act
+ var result = await _service.GetShoppingCartTotal(shoppingCartItem, false, false);
+ //Assert
+ Assert.AreEqual(0, result.shoppingCartTotal);
+ }
+
+ [TestMethod]
+ public async Task ConvertLoyaltyPointsToAmountTest()
+ {
+ //Arrange
+ _loyaltyPointsSettings.ExchangeRate = 1;
+ //Act
+ var result = await _service.ConvertLoyaltyPointsToAmount(10);
+ //Assert
+ Assert.AreEqual(10, result);
+ }
+
+ [TestMethod]
+ public void ConvertAmountToLoyaltyPointsTest()
+ {
+ //Arrange
+ _loyaltyPointsSettings.ExchangeRate = 1;
+ //Act
+ var result = _service.ConvertAmountToLoyaltyPoints(10);
+ //Assert
+ Assert.AreEqual(10, result);
+ }
+
+ [TestMethod]
+ public void CheckMinimumLoyaltyPointsToUseRequirementTest()
{
- private OrderCalculationService _service;
-
- private Mock<IWorkContext> _workContextMock;
- private Mock<IPricingService> _pricingServiceMock;
- private Mock<ITaxService> _taxServiceMock;
- private Mock<IShippingService> _shippingServiceMock;
- private Mock<IPaymentService> _paymentServiceMock;
- private Mock<ICheckoutAttributeParser> _checkoutAttributeParserMock;
- private Mock<IDiscountService> _discountServiceMock;
- private Mock<IGiftVoucherService> _giftVoucherServiceMock;
- private Mock<ILoyaltyPointsService> _loyaltyPointsServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<ICurrencyService> _currencyServiceMock;
- private Mock<IGroupService> _groupServiceMock;
- private Mock<IDiscountValidationService> _discountValidationService;
- private TaxSettings _taxSettings;
- private LoyaltyPointsSettings _loyaltyPointsSettings;
- private ShippingSettings _shippingSettings;
- private ShoppingCartSettings _shoppingCartSettings;
- private CatalogSettings _catalogSettings;
-
- [TestInitialize()]
- public void Init()
- {
- _workContextMock = new Mock<IWorkContext>();
- _pricingServiceMock = new Mock<IPricingService>();
- _taxServiceMock = new Mock<ITaxService>();
- _shippingServiceMock = new Mock<IShippingService>();
- _paymentServiceMock = new Mock<IPaymentService>();
- _checkoutAttributeParserMock = new Mock<ICheckoutAttributeParser>();
- _discountServiceMock = new Mock<IDiscountService>();
- _giftVoucherServiceMock = new Mock<IGiftVoucherService>();
- _loyaltyPointsServiceMock = new Mock<ILoyaltyPointsService>();
- _productServiceMock = new Mock<IProductService>();
- _currencyServiceMock = new Mock<ICurrencyService>();
- _groupServiceMock = new Mock<IGroupService>();
- _taxSettings = new TaxSettings();
- _loyaltyPointsSettings = new LoyaltyPointsSettings();
- _shippingSettings = new ShippingSettings();
- _shoppingCartSettings = new ShoppingCartSettings();
- _catalogSettings = new CatalogSettings();
- _discountValidationService = new Mock<IDiscountValidationService>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- var customer = new Customer();
- customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
- _workContextMock.Setup(c => c.WorkingCurrency).Returns(() => new Currency());
- _workContextMock.Setup(c => c.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
-
- _service = new OrderCalculationService(_workContextMock.Object, _pricingServiceMock.Object, _taxServiceMock.Object, _shippingServiceMock.Object,
- _paymentServiceMock.Object, _checkoutAttributeParserMock.Object, _discountServiceMock.Object, _giftVoucherServiceMock.Object,
- _loyaltyPointsServiceMock.Object, _productServiceMock.Object, _currencyServiceMock.Object, _groupServiceMock.Object, _discountValidationService.Object,
- _taxSettings, _loyaltyPointsSettings, _shippingSettings, _shoppingCartSettings, _catalogSettings);
- }
-
- [TestMethod()]
- public async Task GetShoppingCartSubTotalTest()
- {
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
- _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));
-
- var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1 } };
- var result = await _service.GetShoppingCartSubTotal(shoppingCartItem, false);
-
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetShoppingCartAdditionalShippingChargeTest()
- {
- //Arrange
- var cgs = new List<CustomerGroup> { new CustomerGroup() };
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
- .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
-
- var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10 } };
- //Act
- var result = await _service.GetShoppingCartAdditionalShippingCharge(shoppingCartItem);
- //Assert
- Assert.AreEqual(10, result);
- }
-
- [TestMethod()]
- public async Task IsFreeShippingTest()
- {
- //Arrange
- var cgs = new List<CustomerGroup> { new CustomerGroup() };
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
- .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
-
- var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true } };
- //Act
- var result = await _service.GetShoppingCartAdditionalShippingCharge(shoppingCartItem);
- //Assert
- Assert.AreEqual(0, result);
- }
-
- [TestMethod()]
- public async Task AdjustShippingRateTest()
- {
- //Arrange
- var cgs = new List<CustomerGroup> { new CustomerGroup() };
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
- .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
-
- var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10 } };
- //Act
- var result = await _service.AdjustShippingRate(10, shoppingCartItem);
-
- //Assert
- Assert.AreEqual(20, result.shippingRate);
- }
-
- [TestMethod()]
- public async Task GetShoppingCartShippingTotalTest()
- {
- //Arrange
- var cgs = new List<CustomerGroup> { new CustomerGroup() };
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
- .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
- _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));
-
- var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true } };
- //Act
- var result = await _service.GetShoppingCartShippingTotal(shoppingCartItem);
-
- //Assert
- Assert.AreEqual(0, result.shoppingCartShippingTotal);
- }
-
- [TestMethod()]
- public async Task GetTaxTotalTest()
- {
- //TODO
- //Arrange
- var cgs = new List<CustomerGroup> { new CustomerGroup() };
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
- .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
- _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));
-
- var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true } };
- //Act
- var result = await _service.GetTaxTotal(shoppingCartItem, false);
- //Assert
- Assert.AreEqual(0, result.taxtotal);
- }
-
- [TestMethod()]
- public async Task GetShoppingCartTotalTest()
- {
- //TODO
- //Arrange
- var cgs = new List<CustomerGroup> { new CustomerGroup() };
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
- .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _checkoutAttributeParserMock.Setup(a => a.ParseCheckoutAttributeValue(It.IsAny<List<CustomAttribute>>())).Returns(() => Task.FromResult((IList<(CheckoutAttribute ca, CheckoutAttributeValue cav)>)new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>()));
- _discountServiceMock.Setup(a => a.GetDiscountsQuery(DiscountType.AssignedToOrderSubTotal, It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(() => Task.FromResult((IList<Discount>)new List<Discount> { }));
-
- var shoppingCartItem = new List<ShoppingCartItem> { new ShoppingCartItem { Quantity = 1, IsShipEnabled = true, AdditionalShippingChargeProduct = 10, IsFreeShipping = true } };
- //Act
- var result = await _service.GetShoppingCartTotal(shoppingCartItem, false, false);
- //Assert
- Assert.AreEqual(0, result.shoppingCartTotal);
-
- }
-
- [TestMethod()]
- public async Task ConvertLoyaltyPointsToAmountTest()
- {
- //Arrange
- _loyaltyPointsSettings.ExchangeRate = 1;
- //Act
- var result = await _service.ConvertLoyaltyPointsToAmount(10);
- //Assert
- Assert.AreEqual(10, result);
- }
-
- [TestMethod()]
- public void ConvertAmountToLoyaltyPointsTest()
- {
- //Arrange
- _loyaltyPointsSettings.ExchangeRate = 1;
- //Act
- var result = _service.ConvertAmountToLoyaltyPoints(10);
- //Assert
- Assert.AreEqual(10, result);
- }
-
- [TestMethod()]
- public void CheckMinimumLoyaltyPointsToUseRequirementTest()
- {
- //Assert
- _loyaltyPointsSettings.MinimumLoyaltyPointsToUse = 20;
- //Act
- var result = _service.CheckMinimumLoyaltyPointsToUseRequirement(10);
- //Assert
- Assert.IsFalse(result);
- }
+ //Assert
+ _loyaltyPointsSettings.MinimumLoyaltyPointsToUse = 20;
+ //Act
+ var result = _service.CheckMinimumLoyaltyPointsToUseRequirement(10);
+ //Assert
+ Assert.IsFalse(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderServiceTests.cs
index 38a6e42a1..c522c3fac 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderServiceTests.cs
@@ -6,65 +6,64 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Orders
+namespace Grand.Business.Checkout.Tests.Services.Orders;
+
+[TestClass]
+public class OrderServiceTests
{
- [TestClass]
- public class OrderServiceTests
- {
- private Mock<IRepository<Order>> _orderRepositoryMock;
- private Mock<IRepository<OrderNote>> _orderNoteRepositoryMock;
- private Mock<IMediator> _mediatorMock;
- private OrderService _service;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<OrderNote>> _orderNoteRepositoryMock;
+ private Mock<IRepository<Order>> _orderRepositoryMock;
+ private OrderService _service;
- [TestInitialize]
- public void Init()
- {
- _orderRepositoryMock = new Mock<IRepository<Order>>();
- _orderNoteRepositoryMock = new Mock<IRepository<OrderNote>>();
- _mediatorMock = new Mock<IMediator>();
- _service = new OrderService(_orderRepositoryMock.Object, _orderNoteRepositoryMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _orderRepositoryMock = new Mock<IRepository<Order>>();
+ _orderNoteRepositoryMock = new Mock<IRepository<OrderNote>>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new OrderService(_orderRepositoryMock.Object, _orderNoteRepositoryMock.Object, _mediatorMock.Object);
+ }
- [TestMethod]
- public async Task UpdateOrder_InvokeExpectedMethods()
- {
- await _service.UpdateOrder(new Order());
- _orderRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Order>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Order>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateOrder_InvokeExpectedMethods()
+ {
+ await _service.UpdateOrder(new Order());
+ _orderRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Order>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Order>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateOrder_NullArguments_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateOrder(null));
- }
+ [TestMethod]
+ public void UpdateOrder_NullArguments_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateOrder(null));
+ }
- [TestMethod]
- public async Task InsertOrderNote_InvokeExpectedMethods()
- {
- await _service.InsertOrderNote(new OrderNote());
- _orderNoteRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<OrderNote>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<OrderNote>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertOrderNote_InvokeExpectedMethods()
+ {
+ await _service.InsertOrderNote(new OrderNote());
+ _orderNoteRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<OrderNote>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<OrderNote>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertOrderNote_NullArguments_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertOrderNote(null));
- }
+ [TestMethod]
+ public void InsertOrderNote_NullArguments_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertOrderNote(null));
+ }
- [TestMethod]
- public async Task DeleteOrderNote_InvokeExpectedMethods()
- {
- await _service.DeleteOrderNote(new OrderNote());
- _orderNoteRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<OrderNote>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<OrderNote>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteOrderNote_InvokeExpectedMethods()
+ {
+ await _service.DeleteOrderNote(new OrderNote());
+ _orderNoteRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<OrderNote>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<OrderNote>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeleteOrderNote_NullArguments_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteOrderNote(null));
- }
+ [TestMethod]
+ public void DeleteOrderNote_NullArguments_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteOrderNote(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderStatusServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderStatusServiceTests.cs
index df6eda8cf..226b88b34 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderStatusServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderStatusServiceTests.cs
@@ -7,68 +7,67 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Orders
+namespace Grand.Business.Checkout.Tests.Services.Orders;
+
+[TestClass]
+public class OrderStatusServiceTests
{
- [TestClass]
- public class OrderStatusServiceTests
- {
- private Mock<IRepository<OrderStatus>> _repositoryMock;
- private Mock<ICacheBase> _cacheMock;
- private Mock<IMediator> _mediatorMock;
- private OrderStatusService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<OrderStatus>> _repositoryMock;
+ private OrderStatusService _service;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<OrderStatus>>();
- _cacheMock = new Mock<ICacheBase>();
- _mediatorMock = new Mock<IMediator>();
- _service = new OrderStatusService(_repositoryMock.Object, _cacheMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<OrderStatus>>();
+ _cacheMock = new Mock<ICacheBase>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new OrderStatusService(_repositoryMock.Object, _cacheMock.Object, _mediatorMock.Object);
+ }
- [TestMethod]
- public async Task Insert_InvokeExpectedMethods()
- {
- await _service.Insert(new OrderStatus());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<OrderStatus>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<OrderStatus>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task Insert_InvokeExpectedMethods()
+ {
+ await _service.Insert(new OrderStatus());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<OrderStatus>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<OrderStatus>>(), default), Times.Once);
+ }
- [TestMethod]
- public void Insert_NullArguemnt_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.Insert(null));
- }
+ [TestMethod]
+ public void Insert_NullArguemnt_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.Insert(null));
+ }
- [TestMethod]
- public async Task Update_InvokeExpectedMethods()
- {
- await _service.Update(new OrderStatus());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<OrderStatus>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<OrderStatus>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task Update_InvokeExpectedMethods()
+ {
+ await _service.Update(new OrderStatus());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<OrderStatus>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<OrderStatus>>(), default), Times.Once);
+ }
- [TestMethod]
- public void Update_NullArguemnt_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.Update(null));
- }
+ [TestMethod]
+ public void Update_NullArguemnt_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.Update(null));
+ }
- [TestMethod]
- public async Task Delete_InvokeExpectedMethods()
- {
- await _service.Delete(new OrderStatus());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<OrderStatus>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<OrderStatus>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task Delete_InvokeExpectedMethods()
+ {
+ await _service.Delete(new OrderStatus());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<OrderStatus>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<OrderStatus>>(), default), Times.Once);
+ }
- [TestMethod]
- public void Delete_NullArguemnt_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.Delete(null));
- }
+ [TestMethod]
+ public void Delete_NullArguemnt_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.Delete(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderTagServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderTagServiceTests.cs
index 4558232de..bad79cf45 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderTagServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/OrderTagServiceTests.cs
@@ -1,6 +1,6 @@
using Grand.Business.Checkout.Services.Orders;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Orders;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -9,166 +9,168 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Orders
+namespace Grand.Business.Checkout.Tests.Services.Orders;
+
+[TestClass]
+public class OrderTagServiceTests
{
- [TestClass()]
- public class OrderTagServiceTests
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Order> _orderRepository;
+ private IRepository<OrderTag> _orderTagRepository;
+ private OrderTagService _service;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _orderTagRepository = new MongoDBRepositoryTest<OrderTag>();
+ _orderRepository = new MongoDBRepositoryTest<Order>();
+
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _service = new OrderTagService(_orderTagRepository, _orderRepository, _cacheBase, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetAllOrderTagsTest()
+ {
+ //Arrange
+ await _orderTagRepository.InsertAsync(new OrderTag());
+ await _orderTagRepository.InsertAsync(new OrderTag());
+ await _orderTagRepository.InsertAsync(new OrderTag());
+
+ //Act
+ var result = await _service.GetAllOrderTags();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetOrderTagByIdTest()
+ {
+ //Arrange
+ await _orderTagRepository.InsertAsync(new OrderTag { Id = "1" });
+ await _orderTagRepository.InsertAsync(new OrderTag());
+ await _orderTagRepository.InsertAsync(new OrderTag());
+
+ //Act
+ var result = await _service.GetOrderTagById("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetOrderTagByNameTest()
+ {
+ //Arrange
+ await _orderTagRepository.InsertAsync(new OrderTag { Id = "1", Name = "test" });
+ await _orderTagRepository.InsertAsync(new OrderTag());
+ await _orderTagRepository.InsertAsync(new OrderTag());
+
+ //Act
+ var result = await _service.GetOrderTagByName("test");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task InsertOrderTagTest()
+ {
+ //Act
+ await _service.InsertOrderTag(new OrderTag());
+
+ //Assert
+ Assert.IsTrue(_orderTagRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateOrderTagTest()
+ {
+ //Arrange
+ var orderTag = new OrderTag();
+ await _orderTagRepository.InsertAsync(orderTag);
+
+ //Act
+ orderTag.Name = "test";
+ await _service.UpdateOrderTag(orderTag);
+
+ //Assert
+ Assert.IsTrue(_orderTagRepository.Table.FirstOrDefault(x => x.Id == orderTag.Id).Name == "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteOrderTagTest()
+ {
+ //Arrange
+ var orderTag = new OrderTag();
+ await _orderTagRepository.InsertAsync(orderTag);
+
+ //Act
+ await _service.DeleteOrderTag(orderTag);
+
+ //Assert
+ Assert.IsFalse(_orderTagRepository.Table.FirstOrDefault(x => x.Id == orderTag.Id)?.Name == "test");
+ }
+
+ [TestMethod]
+ public async Task AttachOrderTagTest()
{
- private OrderTagService _service;
- private IRepository<OrderTag> _orderTagRepository;
- private IRepository<Order> _orderRepository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _orderTagRepository = new MongoDBRepositoryTest<OrderTag>();
- _orderRepository = new MongoDBRepositoryTest<Order>();
-
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _service = new OrderTagService(_orderTagRepository, _orderRepository, _cacheBase, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetAllOrderTagsTest()
- {
- //Arrange
- await _orderTagRepository.InsertAsync(new OrderTag());
- await _orderTagRepository.InsertAsync(new OrderTag());
- await _orderTagRepository.InsertAsync(new OrderTag());
-
- //Act
- var result = await _service.GetAllOrderTags();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetOrderTagByIdTest()
- {
- //Arrange
- await _orderTagRepository.InsertAsync(new OrderTag { Id = "1"});
- await _orderTagRepository.InsertAsync(new OrderTag());
- await _orderTagRepository.InsertAsync(new OrderTag());
-
- //Act
- var result = await _service.GetOrderTagById("1");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetOrderTagByNameTest()
- {
- //Arrange
- await _orderTagRepository.InsertAsync(new OrderTag { Id = "1", Name = "test" });
- await _orderTagRepository.InsertAsync(new OrderTag());
- await _orderTagRepository.InsertAsync(new OrderTag());
-
- //Act
- var result = await _service.GetOrderTagByName("test");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task InsertOrderTagTest()
- {
- //Act
- await _service.InsertOrderTag(new OrderTag());
-
- //Assert
- Assert.IsTrue(_orderTagRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateOrderTagTest()
- {
- //Arrange
- var orderTag = new OrderTag();
- await _orderTagRepository.InsertAsync(orderTag);
-
- //Act
- orderTag.Name = "test";
- await _service.UpdateOrderTag(orderTag);
-
- //Assert
- Assert.IsTrue(_orderTagRepository.Table.FirstOrDefault(x=>x.Id == orderTag.Id).Name == "test");
- }
-
- [TestMethod()]
- public async Task DeleteOrderTagTest()
- {
- //Arrange
- var orderTag = new OrderTag();
- await _orderTagRepository.InsertAsync(orderTag);
-
- //Act
- await _service.DeleteOrderTag(orderTag);
-
- //Assert
- Assert.IsFalse(_orderTagRepository.Table.FirstOrDefault(x => x.Id == orderTag.Id)?.Name == "test");
- }
-
- [TestMethod()]
- public async Task AttachOrderTagTest()
- {
- //Arrange
- var orderTag = new OrderTag();
- await _orderTagRepository.InsertAsync(orderTag);
- var order = new Order();
- await _orderRepository.InsertAsync(order);
-
- //Act
- await _service.AttachOrderTag(orderTag.Id, order.Id);
-
- //Assert
- Assert.IsTrue(_orderRepository.Table.FirstOrDefault(x => x.Id == order.Id).OrderTags.Any(z => z == orderTag.Id));
- Assert.IsTrue(_orderTagRepository.Table.FirstOrDefault(x => x.Id == orderTag.Id).Count == 1);
- }
-
- [TestMethod()]
- public async Task DetachOrderTagTest()
- {
- //Arrange
- var orderTag = new OrderTag();
- await _orderTagRepository.InsertAsync(orderTag);
- var order = new Order();
- await _orderRepository.InsertAsync(order);
-
- await _service.AttachOrderTag(orderTag.Id, order.Id);
-
- //Act
- await _service.DetachOrderTag(orderTag.Id, order.Id);
-
- //Assert
- Assert.IsFalse(_orderRepository.Table.FirstOrDefault(x => x.Id == order.Id).OrderTags.Any(z => z == orderTag.Id));
- Assert.IsTrue(_orderTagRepository.Table.FirstOrDefault(x => x.Id == orderTag.Id).Count == 0);
- }
-
- [TestMethod()]
- public async Task GetOrderCountTest()
- {
- //Arrange
- var orderTag = new OrderTag();
- await _orderTagRepository.InsertAsync(orderTag);
- var order = new Order();
- await _orderRepository.InsertAsync(order);
-
- await _service.AttachOrderTag(orderTag.Id, order.Id);
-
- //Act
- var result = await _service.GetOrderCount(orderTag.Id, string.Empty);
-
- //Assert
- Assert.AreEqual(1, result);
- }
+ //Arrange
+ var orderTag = new OrderTag();
+ await _orderTagRepository.InsertAsync(orderTag);
+ var order = new Order();
+ await _orderRepository.InsertAsync(order);
+
+ //Act
+ await _service.AttachOrderTag(orderTag.Id, order.Id);
+
+ //Assert
+ Assert.IsTrue(_orderRepository.Table.FirstOrDefault(x => x.Id == order.Id).OrderTags
+ .Any(z => z == orderTag.Id));
+ Assert.IsTrue(_orderTagRepository.Table.FirstOrDefault(x => x.Id == orderTag.Id).Count == 1);
+ }
+
+ [TestMethod]
+ public async Task DetachOrderTagTest()
+ {
+ //Arrange
+ var orderTag = new OrderTag();
+ await _orderTagRepository.InsertAsync(orderTag);
+ var order = new Order();
+ await _orderRepository.InsertAsync(order);
+
+ await _service.AttachOrderTag(orderTag.Id, order.Id);
+
+ //Act
+ await _service.DetachOrderTag(orderTag.Id, order.Id);
+
+ //Assert
+ Assert.IsFalse(
+ _orderRepository.Table.FirstOrDefault(x => x.Id == order.Id).OrderTags.Any(z => z == orderTag.Id));
+ Assert.IsTrue(_orderTagRepository.Table.FirstOrDefault(x => x.Id == orderTag.Id).Count == 0);
+ }
+
+ [TestMethod]
+ public async Task GetOrderCountTest()
+ {
+ //Arrange
+ var orderTag = new OrderTag();
+ await _orderTagRepository.InsertAsync(orderTag);
+ var order = new Order();
+ await _orderRepository.InsertAsync(order);
+
+ await _service.AttachOrderTag(orderTag.Id, order.Id);
+
+ //Act
+ var result = await _service.GetOrderCount(orderTag.Id, string.Empty);
+
+ //Assert
+ Assert.AreEqual(1, result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs
index e2daaaeac..edd066fa8 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/ShoppingCartServiceTests.cs
@@ -9,187 +9,219 @@ using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Directory;
using Grand.Domain.Orders;
+using Grand.Domain.Stores;
using Grand.Domain.Tax;
using Grand.Infrastructure;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Orders
+namespace Grand.Business.Checkout.Tests.Services.Orders;
+
+[TestClass]
+public class ShoppingCartServiceTests
{
- [TestClass()]
- public class ShoppingCartServiceTests
+ private Mock<ICustomerService> _customerServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IProductService> _productServiceMock;
+ private ShoppingCartService _shoppingCartService;
+ private ShoppingCartSettings _shoppingCartSettings;
+ private Mock<IShoppingCartValidator> _shoppingCartValidatorMock;
+ private Mock<IUserFieldService> _userFieldServiceMock;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _workContextMock = new Mock<IWorkContext>();
+ _productServiceMock = new Mock<IProductService>();
+ _shoppingCartSettings = new ShoppingCartSettings();
+ _customerServiceMock = new Mock<ICustomerService>();
+ _mediatorMock = new Mock<IMediator>();
+ _userFieldServiceMock = new Mock<IUserFieldService>();
+ _shoppingCartValidatorMock = new Mock<IShoppingCartValidator>();
+
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+ _workContextMock.Setup(c => c.WorkingCurrency).Returns(() => new Currency());
+ _workContextMock.Setup(c => c.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
+
+ _shoppingCartService = new ShoppingCartService(_workContextMock.Object, _productServiceMock.Object,
+ _customerServiceMock.Object, _mediatorMock.Object, _userFieldServiceMock.Object,
+ _shoppingCartValidatorMock.Object, _shoppingCartSettings);
+ }
+
+ [TestMethod]
+ public async Task GetShoppingCartTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+
+ //Act
+ var result = await _shoppingCartService.GetShoppingCart();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task FindShoppingCartItemTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "", ProductId = "1" });
+ customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "", ProductId = "2" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+
+ //Act
+ var result = await _shoppingCartService.FindShoppingCartItem(customer.ShoppingCartItems.ToList(),
+ ShoppingCartType.ShoppingCart, "1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task AddToCartTest_Success()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(),
+ It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null,
+ It.IsAny<int>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+ _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(),
+ It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+
+ //Act
+ var result = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
+
+ //Assert
+ Assert.IsNotNull(result.shoppingCartItem);
+ }
+
+ [TestMethod]
+ public async Task AddToCartTest_Warning()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(),
+ It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null,
+ It.IsAny<int>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+ _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(),
+ It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string> { "Error" }));
+
+ //Act
+ var result = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
+
+ //Assert
+ Assert.AreEqual(1, result.warnings.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateShoppingCartItemTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(),
+ It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null,
+ It.IsAny<int>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+ _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(),
+ It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+
+ var item = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
+ //Act
+ var result = await _shoppingCartService.UpdateShoppingCartItem(customer, item.shoppingCartItem.Id, "",
+ new List<CustomAttribute>(), null);
+ //Assert
+ _customerServiceMock.Verify(x => x.UpdateShoppingCartItem(It.IsAny<string>(), It.IsAny<ShoppingCartItem>()),
+ Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteShoppingCartItemTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(),
+ It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null,
+ It.IsAny<int>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+ _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(),
+ It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+
+ var item = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
+ //Act
+ await _shoppingCartService.DeleteShoppingCartItem(customer, item.shoppingCartItem);
+ //Assert
+ _customerServiceMock.Verify(x => x.DeleteShoppingCartItem(It.IsAny<string>(), It.IsAny<ShoppingCartItem>()),
+ Times.Once);
+ }
+
+ [TestMethod]
+ public async Task MigrateShoppingCartTest()
{
- private ShoppingCartService _shoppingCartService;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IUserFieldService> _userFieldServiceMock;
- private Mock<IShoppingCartValidator> _shoppingCartValidatorMock;
- private ShoppingCartSettings _shoppingCartSettings;
-
- [TestInitialize()]
- public void Init()
- {
- _workContextMock = new Mock<IWorkContext>();
- _productServiceMock = new Mock<IProductService>();
- _shoppingCartSettings = new ShoppingCartSettings();
- _customerServiceMock = new Mock<ICustomerService>();
- _mediatorMock = new Mock<IMediator>();
- _userFieldServiceMock = new Mock<IUserFieldService>();
- _shoppingCartValidatorMock = new Mock<IShoppingCartValidator>();
-
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- var customer = new Customer();
- customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
- _workContextMock.Setup(c => c.WorkingCurrency).Returns(() => new Currency());
- _workContextMock.Setup(c => c.TaxDisplayType).Returns(() => TaxDisplayType.ExcludingTax);
-
- _shoppingCartService = new ShoppingCartService(_workContextMock.Object, _productServiceMock.Object,
- _customerServiceMock.Object, _mediatorMock.Object, _userFieldServiceMock.Object, _shoppingCartValidatorMock.Object, _shoppingCartSettings);
- }
-
- [TestMethod()]
- public async Task GetShoppingCartTest()
- {
- //Arrange
- var customer = new Customer();
- customer.Groups.Add("1");
- customer.ShoppingCartItems.Add(new ShoppingCartItem { ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
-
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
-
- //Act
- var result = await _shoppingCartService.GetShoppingCart();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task FindShoppingCartItemTest()
- {
- //Arrange
- var customer = new Customer();
- customer.Groups.Add("1");
- customer.ShoppingCartItems.Add(new ShoppingCartItem { ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "", ProductId = "1" });
- customer.ShoppingCartItems.Add(new ShoppingCartItem { ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "", ProductId = "2" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
-
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
-
- //Act
- var result = await _shoppingCartService.FindShoppingCartItem(customer.ShoppingCartItems.ToList(), ShoppingCartType.ShoppingCart, "1");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task AddToCartTest_Success()
- {
- //Arrange
- var customer = new Customer();
- customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
-
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(), It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null, It.IsAny<int>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
- _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(), It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
-
- //Act
- var result = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
-
- //Assert
- Assert.IsNotNull(result.shoppingCartItem);
- }
- [TestMethod()]
- public async Task AddToCartTest_Warning()
- {
- //Arrange
- var customer = new Customer();
- customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
-
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(), It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null, It.IsAny<int>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
- _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(), It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { "Error" }));
-
- //Act
- var result = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
-
- //Assert
- Assert.AreEqual(1, result.warnings.Count);
- }
- [TestMethod()]
- public async Task UpdateShoppingCartItemTest()
- {
- //Arrange
- var customer = new Customer();
- customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
-
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(), It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null, It.IsAny<int>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
- _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(), It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
-
- var item = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
- //Act
- var result = await _shoppingCartService.UpdateShoppingCartItem(customer, item.shoppingCartItem.Id, "", new List<CustomAttribute>(), null);
- //Assert
- _customerServiceMock.Verify(x => x.UpdateShoppingCartItem(It.IsAny<string>(), It.IsAny<ShoppingCartItem>()), Times.Once);
- }
-
- [TestMethod()]
- public async Task DeleteShoppingCartItemTest()
- {
- //Arrange
- var customer = new Customer();
- customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
-
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(), It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null, It.IsAny<int>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
- _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(), It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
-
- var item = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
- //Act
- await _shoppingCartService.DeleteShoppingCartItem(customer, item.shoppingCartItem);
- //Assert
- _customerServiceMock.Verify(x => x.DeleteShoppingCartItem(It.IsAny<string>(), It.IsAny<ShoppingCartItem>()), Times.Once);
- }
-
- [TestMethod()]
- public async Task MigrateShoppingCartTest()
- {
- //Arrange
- var customer = new Customer();
- customer.Groups.Add("1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
-
- _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() => Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
- _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(), It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null, It.IsAny<int>(), It.IsAny<string>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
- _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(), It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
- .Returns(() => Task.FromResult((IList<string>)new List<string> { }));
-
- var item = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
- var customer2 = new Customer();
- //Act
- await _shoppingCartService.MigrateShoppingCart(customer, customer2, false);
- //Assert
- Assert.IsTrue(customer2.ShoppingCartItems.Any());
- Assert.IsFalse(customer.ShoppingCartItems.Any());
- }
+ //Arrange
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => customer);
+
+ _productServiceMock.Setup(a => a.GetProductById(It.IsAny<string>(), false)).Returns(() =>
+ Task.FromResult(new Product { Id = "1", Published = true, Price = 10 }));
+ _shoppingCartValidatorMock.Setup(x => x.CheckCommonWarnings(It.IsAny<Customer>(),
+ It.IsAny<IList<ShoppingCartItem>>(), It.IsAny<Product>(), ShoppingCartType.ShoppingCart, null, null,
+ It.IsAny<int>(), It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+ _shoppingCartValidatorMock.Setup(x => x.GetShoppingCartItemWarnings(It.IsAny<Customer>(),
+ It.IsAny<ShoppingCartItem>(), It.IsAny<Product>(), It.IsAny<ShoppingCartValidatorOptions>()))
+ .Returns(() => Task.FromResult((IList<string>)new List<string>()));
+
+ var item = await _shoppingCartService.AddToCart(customer, "2", ShoppingCartType.ShoppingCart, "");
+ var customer2 = new Customer();
+ //Act
+ await _shoppingCartService.MigrateShoppingCart(customer, customer2, false);
+ //Assert
+ Assert.IsTrue(customer2.ShoppingCartItems.Any());
+ Assert.IsFalse(customer.ShoppingCartItems.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs
index 99e38b24b..fd7e84717 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentServiceTests.cs
@@ -1,6 +1,6 @@
-using Grand.Business.Core.Enums.Checkout;
+using Grand.Business.Checkout.Services.Payments;
+using Grand.Business.Core.Enums.Checkout;
using Grand.Business.Core.Interfaces.Checkout.Payments;
-using Grand.Business.Checkout.Services.Payments;
using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Domain.Orders;
using Grand.Domain.Payments;
@@ -8,164 +8,175 @@ using Grand.SharedKernel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Payments
+namespace Grand.Business.Checkout.Tests.Services.Payments;
+
+[TestClass]
+public class PaymentServiceTests
{
- [TestClass()]
- public class PaymentServiceTests
+ private Mock<IPaymentProvider> _paymentProviderMock;
+ private IPaymentService _paymentService;
+ private PaymentSettings _paymentSettings;
+ private Mock<ISettingService> _settingService;
+
+ [TestInitialize]
+ public void TestInitialize()
+ {
+ _paymentSettings = new PaymentSettings {
+ ActivePaymentProviderSystemNames = [
+ "Payments.TestMethod"
+ ]
+ };
+ _settingService = new Mock<ISettingService>();
+ _paymentProviderMock = new Mock<IPaymentProvider>();
+ _paymentService = new PaymentService(_paymentSettings,
+ new List<IPaymentProvider> { _paymentProviderMock.Object }, _settingService.Object);
+ }
+
+ [TestMethod]
+ public void LoadPaymentMethodBySystemName_ReturnPeyment()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ var systemName = "systemName";
+ var result = _paymentService.LoadPaymentMethodBySystemName(systemName);
+ Assert.AreEqual(result, _paymentProviderMock.Object);
+ }
+
+ [TestMethod]
+ public void GetRestrictedCountryIds()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ var expectedResult = new List<string> { "1", "2", "3", "4" };
+ var expectedKey = "PaymentMethodRestictions.systemName";
+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, ""))
+ .Returns(() => new PaymentRestrictedSettings { Ids = expectedResult });
+
+ var result = _paymentService.GetRestrictedCountryIds(_paymentProviderMock.Object);
+ Assert.IsTrue(expectedResult.SequenceEqual(result));
+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);
+ }
+
+ [TestMethod]
+ public void GetRestrictedCountryIds_ReturnEmptyList()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ var expectedKey = "PaymentMethodRestictions.systemName";
+ _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, ""))
+ .Returns(() => null);
+
+ var result = _paymentService.GetRestrictedCountryIds(_paymentProviderMock.Object);
+ Assert.IsTrue(result.Count == 0);
+ _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task SaveRestictedCountryIds_InvokeSettingsService()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ var countryIds = new List<string> { "1", "2", "3", "4" };
+ var expectedKey = "PaymentMethodRestictions.systemName";
+
+ await _paymentService.SaveRestrictedCountryIds(_paymentProviderMock.Object, countryIds);
+ _settingService.Verify(
+ s => s.SetSetting(expectedKey, It.IsAny<PaymentRestrictedSettings>(), It.IsAny<string>(), It.IsAny<bool>()),
+ Times.Once);
+ }
+
+ [TestMethod]
+ public async Task ProcessPayment_OrderTotalZero_ReturnPaidPaymentStatus()
+ {
+ var request = new PaymentTransaction {
+ TransactionAmount = 0
+ };
+ var response = await _paymentService.ProcessPayment(request);
+ Assert.IsTrue(response.NewPaymentTransactionStatus == TransactionStatus.Paid);
+ }
+
+ [TestMethod]
+ public async Task ProcessPayment_InvokeProcessPaymentFromPaymentMethod()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ var request = new PaymentTransaction { PaymentMethodSystemName = "systemName", TransactionAmount = 500 };
+
+
+ await _paymentService.ProcessPayment(request);
+ _paymentProviderMock.Verify(m => m.ProcessPayment(request), Times.Once);
+ }
+
+ [TestMethod]
+ public void ProcessPayment_NotFoundPaymentMethod_ThrowException()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName2");
+ var request = new PaymentTransaction { PaymentMethodSystemName = "systemName", TransactionAmount = 500 };
+ Assert.ThrowsExceptionAsync<GrandException>(async () => await _paymentService.ProcessPayment(request));
+ }
+
+ [TestMethod]
+ public async Task PostProcessPayment_InvokePostProccessFromPaymentMethod()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ var request = new PaymentTransaction {
+ PaymentMethodSystemName = "systemName", TransactionAmount = 500,
+ TransactionStatus = TransactionStatus.Authorized
+ };
+ await _paymentService.PostProcessPayment(request);
+ _paymentProviderMock.Verify(m => m.PostProcessPayment(request), Times.Once);
+ }
+
+ [TestMethod]
+ public void PostProcessPayment_NotFoundPaymentMethod_ThrowException()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ var request = new PaymentTransaction {
+ PaymentMethodSystemName = "systemName2", TransactionAmount = 500,
+ TransactionStatus = TransactionStatus.Authorized
+ };
+ Assert.ThrowsExceptionAsync<GrandException>(async () => await _paymentService.PostProcessPayment(request),
+ "Payment method couldn't be loaded");
+ }
+
+ [TestMethod]
+ public async Task CanRePostRedirectPayment_ReturnExpectedResult()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ _paymentProviderMock.Setup(c => c.CanRePostRedirectPayment(It.IsAny<PaymentTransaction>())).ReturnsAsync(true);
+ var request = new PaymentTransaction { PaymentMethodSystemName = "systemName" };
+ _paymentSettings.AllowRePostingPayments = false;
+ Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
+ _paymentSettings.AllowRePostingPayments = true;
+ _paymentProviderMock.Setup(c => c.PaymentMethodType).Returns(PaymentMethodType.Other);
+ Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
+ request.TransactionStatus = TransactionStatus.Canceled;
+ Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
+ request.TransactionStatus = TransactionStatus.Pending;
+ Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
+ _paymentProviderMock.Setup(c => c.PaymentMethodType).Returns(PaymentMethodType.Redirection);
+ request.TransactionStatus = TransactionStatus.Pending;
+ Assert.IsTrue(await _paymentService.CanRePostRedirectPayment(request));
+ }
+
+ [TestMethod]
+ public async Task GetAdditionalHandlingFee_ReturnExpectedResults()
+ {
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ _paymentProviderMock.Setup(c => c.GetAdditionalHandlingFee(It.IsAny<IList<ShoppingCartItem>>()))
+ .ReturnsAsync(100);
+ var cart = new List<ShoppingCartItem> {
+ new(),
+ new()
+ };
+ Assert.AreEqual(100, await _paymentService.GetAdditionalHandlingFee(cart, "systemName"));
+ }
+
+ [TestMethod]
+ public async Task GetAdditionalHandlingFee_SystemnameNull_ReturnZero()
{
- private PaymentSettings _paymentSettings;
- private Mock<ISettingService> _settingService;
- private Mock<IPaymentProvider> _paymentProviderMock;
- private IPaymentService _paymentService;
-
- [TestInitialize()]
- public void TestInitialize()
- {
- _paymentSettings = new PaymentSettings {
- ActivePaymentProviderSystemNames = [
- "Payments.TestMethod"
- ]
- };
- _settingService = new Mock<ISettingService>();
- _paymentProviderMock = new Mock<IPaymentProvider>();
- _paymentService = new PaymentService(_paymentSettings, new List<IPaymentProvider> { _paymentProviderMock.Object }, _settingService.Object);
- }
-
- [TestMethod()]
- public void LoadPaymentMethodBySystemName_ReturnPeyment()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- var systemName = "systemName";
- var result = _paymentService.LoadPaymentMethodBySystemName(systemName);
- Assert.AreEqual(result, _paymentProviderMock.Object);
- }
-
- [TestMethod()]
- public void GetRestrictedCountryIds()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- var expectedResult = new List<string> { "1", "2", "3", "4" };
- var expectedKey = "PaymentMethodRestictions.systemName";
- _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, ""))
- .Returns(() => new PaymentRestrictedSettings { Ids = expectedResult });
-
- var result = _paymentService.GetRestrictedCountryIds(_paymentProviderMock.Object);
- Assert.IsTrue(expectedResult.SequenceEqual(result));
- _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);
- }
-
- [TestMethod()]
- public void GetRestrictedCountryIds_ReturnEmptyList()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- var expectedKey = "PaymentMethodRestictions.systemName";
- _settingService.Setup(s => s.GetSettingByKey<PaymentRestrictedSettings>(It.IsAny<string>(), null, ""))
- .Returns(() => null);
-
- var result = _paymentService.GetRestrictedCountryIds(_paymentProviderMock.Object);
- Assert.IsTrue(result.Count == 0);
- _settingService.Verify(s => s.GetSettingByKey<PaymentRestrictedSettings>(expectedKey, null, ""), Times.Once);
- }
-
- [TestMethod()]
- public async Task SaveRestictedCountryIds_InvokeSettingsService()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- var countryIds = new List<string> { "1", "2", "3", "4" };
- var expectedKey = "PaymentMethodRestictions.systemName";
-
- await _paymentService.SaveRestrictedCountryIds(_paymentProviderMock.Object, countryIds);
- _settingService.Verify(s => s.SetSetting(expectedKey, It.IsAny<PaymentRestrictedSettings>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
-
- [TestMethod()]
- public async Task ProcessPayment_OrderTotalZero_ReturnPaidPaymentStatus()
- {
- var request = new PaymentTransaction {
- TransactionAmount = 0
- };
- var response = await _paymentService.ProcessPayment(request);
- Assert.IsTrue(response.NewPaymentTransactionStatus == TransactionStatus.Paid);
- }
-
- [TestMethod()]
- public async Task ProcessPayment_InvokeProcessPaymentFromPaymentMethod()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- var request = new PaymentTransaction { PaymentMethodSystemName = "systemName", TransactionAmount = 500 };
-
-
- await _paymentService.ProcessPayment(request);
- _paymentProviderMock.Verify(m => m.ProcessPayment(request), Times.Once);
- }
-
- [TestMethod()]
- public void ProcessPayment_NotFoundPaymentMethod_ThrowException()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName2");
- var request = new PaymentTransaction { PaymentMethodSystemName = "systemName", TransactionAmount = 500 };
- Assert.ThrowsExceptionAsync<GrandException>(async () => await _paymentService.ProcessPayment(request));
- }
-
- [TestMethod()]
- public async Task PostProcessPayment_InvokePostProccessFromPaymentMethod()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- var request = new PaymentTransaction { PaymentMethodSystemName = "systemName", TransactionAmount = 500, TransactionStatus = TransactionStatus.Authorized };
- await _paymentService.PostProcessPayment(request);
- _paymentProviderMock.Verify(m => m.PostProcessPayment(request), Times.Once);
- }
-
- [TestMethod()]
- public void PostProcessPayment_NotFoundPaymentMethod_ThrowException()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- var request = new PaymentTransaction { PaymentMethodSystemName = "systemName2", TransactionAmount = 500, TransactionStatus = TransactionStatus.Authorized };
- Assert.ThrowsExceptionAsync<GrandException>(async () => await _paymentService.PostProcessPayment(request), "Payment method couldn't be loaded");
- }
-
- [TestMethod]
- public async Task CanRePostRedirectPayment_ReturnExpectedResult()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- _paymentProviderMock.Setup(c => c.CanRePostRedirectPayment(It.IsAny<PaymentTransaction>())).ReturnsAsync(true);
- var request = new PaymentTransaction { PaymentMethodSystemName = "systemName" };
- _paymentSettings.AllowRePostingPayments = false;
- Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
- _paymentSettings.AllowRePostingPayments = true;
- _paymentProviderMock.Setup(c => c.PaymentMethodType).Returns(PaymentMethodType.Other);
- Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
- request.TransactionStatus = TransactionStatus.Canceled;
- Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
- request.TransactionStatus = TransactionStatus.Pending;
- Assert.IsFalse(await _paymentService.CanRePostRedirectPayment(request));
- _paymentProviderMock.Setup(c => c.PaymentMethodType).Returns(PaymentMethodType.Redirection);
- request.TransactionStatus = TransactionStatus.Pending;
- Assert.IsTrue(await _paymentService.CanRePostRedirectPayment(request));
- }
-
- [TestMethod]
- public async Task GetAdditionalHandlingFee_ReturnExpectedResults()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- _paymentProviderMock.Setup(c => c.GetAdditionalHandlingFee(It.IsAny<IList<ShoppingCartItem>>())).ReturnsAsync(100);
- var cart = new List<ShoppingCartItem> {
- new ShoppingCartItem(),
- new ShoppingCartItem()
- };
- Assert.AreEqual(100, await _paymentService.GetAdditionalHandlingFee(cart, "systemName"));
- }
-
- [TestMethod]
- public async Task GetAdditionalHandlingFee_SystemnameNull_ReturnZero()
- {
- _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
- _paymentProviderMock.Setup(c => c.GetAdditionalHandlingFee(It.IsAny<IList<ShoppingCartItem>>())).ReturnsAsync(100);
- var cart = new List<ShoppingCartItem> {
- new ShoppingCartItem(),
- new ShoppingCartItem()
- };
- Assert.AreEqual(0, await _paymentService.GetAdditionalHandlingFee(cart, null));
- }
+ _paymentProviderMock.Setup(c => c.SystemName).Returns("systemName");
+ _paymentProviderMock.Setup(c => c.GetAdditionalHandlingFee(It.IsAny<IList<ShoppingCartItem>>()))
+ .ReturnsAsync(100);
+ var cart = new List<ShoppingCartItem> {
+ new(),
+ new()
+ };
+ Assert.AreEqual(0, await _paymentService.GetAdditionalHandlingFee(cart, null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentTransactionServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentTransactionServiceTests.cs
index 7bd24d5f1..85f9d897a 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentTransactionServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Payments/PaymentTransactionServiceTests.cs
@@ -6,63 +6,62 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Payments
+namespace Grand.Business.Checkout.Tests.Services.Payments;
+
+[TestClass]
+public class PaymentTransactionServiceTests
{
- [TestClass]
- public class PaymentTransactionServiceTests
- {
- private Mock<IRepository<PaymentTransaction>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private PaymentTransactionService _service;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<PaymentTransaction>> _repositoryMock;
+ private PaymentTransactionService _service;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<PaymentTransaction>>();
- _mediatorMock = new Mock<IMediator>();
- _service = new PaymentTransactionService(_repositoryMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<PaymentTransaction>>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new PaymentTransactionService(_repositoryMock.Object, _mediatorMock.Object);
+ }
- [TestMethod]
- public async Task InsertPaymentTransaction_InvokeExpectedMethods()
- {
- await _service.InsertPaymentTransaction(new PaymentTransaction());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<PaymentTransaction>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<PaymentTransaction>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertPaymentTransaction_InvokeExpectedMethods()
+ {
+ await _service.InsertPaymentTransaction(new PaymentTransaction());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<PaymentTransaction>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<PaymentTransaction>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertPaymentTransaction_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertPaymentTransaction(null));
- }
+ [TestMethod]
+ public void InsertPaymentTransaction_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertPaymentTransaction(null));
+ }
- [TestMethod]
- public async Task UpdatePaymentTransaction_InvokeExpectedMethods()
- {
- await _service.UpdatePaymentTransaction(new PaymentTransaction());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<PaymentTransaction>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<PaymentTransaction>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdatePaymentTransaction_InvokeExpectedMethods()
+ {
+ await _service.UpdatePaymentTransaction(new PaymentTransaction());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<PaymentTransaction>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<PaymentTransaction>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdatePaymentTransaction_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdatePaymentTransaction(null));
- }
+ [TestMethod]
+ public void UpdatePaymentTransaction_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdatePaymentTransaction(null));
+ }
- [TestMethod]
- public async Task DeletePaymentTransaction_InvokeExpectedMethods()
- {
- await _service.DeletePaymentTransaction(new PaymentTransaction());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<PaymentTransaction>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<PaymentTransaction>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeletePaymentTransaction_InvokeExpectedMethods()
+ {
+ await _service.DeletePaymentTransaction(new PaymentTransaction());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<PaymentTransaction>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<PaymentTransaction>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeletePaymentTransaction_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeletePaymentTransaction(null));
- }
+ [TestMethod]
+ public void DeletePaymentTransaction_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeletePaymentTransaction(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/DeliveryDateServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/DeliveryDateServiceTests.cs
index 778598226..34908a496 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/DeliveryDateServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/DeliveryDateServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Checkout.Shipping;
-using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Data;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Caching;
@@ -8,67 +8,66 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Shipping
+namespace Grand.Business.Checkout.Tests.Services.Shipping;
+
+[TestClass]
+public class DeliveryDateServiceTests
{
- [TestClass]
- public class DeliveryDateServiceTests
- {
- private Mock<IRepository<DeliveryDate>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<ICacheBase> _cacheMock;
- private IDeliveryDateService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<DeliveryDate>> _repositoryMock;
+ private IDeliveryDateService _service;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<DeliveryDate>>();
- _mediatorMock = new Mock<IMediator>();
- _cacheMock = new Mock<ICacheBase>();
- _service = new DeliveryDateService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<DeliveryDate>>();
+ _mediatorMock = new Mock<IMediator>();
+ _cacheMock = new Mock<ICacheBase>();
+ _service = new DeliveryDateService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
+ }
- [TestMethod]
- public async Task InsertDeliveryDate_InvokeExpectedMethods()
- {
- await _service.InsertDeliveryDate(new DeliveryDate());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<DeliveryDate>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<DeliveryDate>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertDeliveryDate_InvokeExpectedMethods()
+ {
+ await _service.InsertDeliveryDate(new DeliveryDate());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<DeliveryDate>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<DeliveryDate>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertDeliveryDate_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertDeliveryDate(null));
- }
+ [TestMethod]
+ public void InsertDeliveryDate_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertDeliveryDate(null));
+ }
- [TestMethod]
- public async Task UpdateDeliveryDate_InvokeExpectedMethods()
- {
- await _service.UpdateDeliveryDate(new DeliveryDate());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<DeliveryDate>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<DeliveryDate>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateDeliveryDate_InvokeExpectedMethods()
+ {
+ await _service.UpdateDeliveryDate(new DeliveryDate());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<DeliveryDate>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<DeliveryDate>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateDeliveryDate_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateDeliveryDate(null));
- }
+ [TestMethod]
+ public void UpdateDeliveryDate_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateDeliveryDate(null));
+ }
- [TestMethod]
- public async Task DeleteDeliveryDate_InvokeExpectedMethods()
- {
- await _service.DeleteDeliveryDate(new DeliveryDate());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<DeliveryDate>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<DeliveryDate>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteDeliveryDate_InvokeExpectedMethods()
+ {
+ await _service.DeleteDeliveryDate(new DeliveryDate());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<DeliveryDate>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<DeliveryDate>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeleteDeliveryDate_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteDeliveryDate(null));
- }
+ [TestMethod]
+ public void DeleteDeliveryDate_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteDeliveryDate(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/PickupPointServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/PickupPointServiceTests.cs
index eac35ae6e..54a568364 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/PickupPointServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/PickupPointServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Checkout.Shipping;
-using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Data;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Caching;
@@ -8,68 +8,67 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Shipping
+namespace Grand.Business.Checkout.Tests.Services.Shipping;
+
+[TestClass]
+public class PickupPointServiceTests
{
- [TestClass]
- public class PickupPointServiceTests
- {
- private Mock<IRepository<PickupPoint>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<ICacheBase> _cacheMock;
- private IPickupPointService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<PickupPoint>> _repositoryMock;
+ private IPickupPointService _service;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<PickupPoint>>();
- _mediatorMock = new Mock<IMediator>();
- _cacheMock = new Mock<ICacheBase>();
- _service = new PickupPointService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<PickupPoint>>();
+ _mediatorMock = new Mock<IMediator>();
+ _cacheMock = new Mock<ICacheBase>();
+ _service = new PickupPointService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
+ }
- [TestMethod]
- public async Task InsertPickupPoint_InvokeExpectedMethods()
- {
- await _service.InsertPickupPoint(new PickupPoint());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<PickupPoint>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<PickupPoint>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertPickupPoint_InvokeExpectedMethods()
+ {
+ await _service.InsertPickupPoint(new PickupPoint());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<PickupPoint>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<PickupPoint>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertPickupPoint_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertPickupPoint(null));
- }
+ [TestMethod]
+ public void InsertPickupPoint_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertPickupPoint(null));
+ }
- [TestMethod]
- public async Task UpdatePickupPoint_InvokeExpectedMethods()
- {
- await _service.UpdatePickupPoint(new PickupPoint());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<PickupPoint>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<PickupPoint>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdatePickupPoint_InvokeExpectedMethods()
+ {
+ await _service.UpdatePickupPoint(new PickupPoint());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<PickupPoint>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<PickupPoint>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdatePickupPoint_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdatePickupPoint(null));
- }
+ [TestMethod]
+ public void UpdatePickupPoint_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdatePickupPoint(null));
+ }
- [TestMethod]
- public async Task DeletePickupPoint_InvokeExpectedMethods()
- {
- await _service.DeletePickupPoint(new PickupPoint());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<PickupPoint>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<PickupPoint>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeletePickupPoint_InvokeExpectedMethods()
+ {
+ await _service.DeletePickupPoint(new PickupPoint());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<PickupPoint>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<PickupPoint>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeletePickupPoint_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeletePickupPoint(null));
- }
+ [TestMethod]
+ public void DeletePickupPoint_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeletePickupPoint(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShipmentServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShipmentServiceTests.cs
index 99e76e323..7ed2b5624 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShipmentServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShipmentServiceTests.cs
@@ -7,65 +7,63 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Shipping
-{
- [TestClass()]
- public class ShipmentServiceTests
- {
- private Mock<IRepository<Shipment>> _repositoryMock;
- private Mock<IRepository<ShipmentNote>> _repositoryShipmentNoteMock;
- private Mock<IMediator> _mediatorMock;
- private IShipmentService _service;
+namespace Grand.Business.Checkout.Tests.Services.Shipping;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<Shipment>>();
- _repositoryShipmentNoteMock = new Mock<IRepository<ShipmentNote>>();
- _mediatorMock = new Mock<IMediator>();
- _service = new ShipmentService(_repositoryMock.Object, _repositoryShipmentNoteMock.Object, _mediatorMock.Object);
- }
-
- [TestMethod]
- public async Task InsertShipment_InvokeExpectedMethods()
- {
- await _service.InsertShipment(new Shipment());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Shipment>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Shipment>>(), default(CancellationToken)), Times.Once);
- }
+[TestClass]
+public class ShipmentServiceTests
+{
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Shipment>> _repositoryMock;
+ private Mock<IRepository<ShipmentNote>> _repositoryShipmentNoteMock;
+ private IShipmentService _service;
- [TestMethod()]
- public async Task UpdateShipment_InvokeExpectedMethods()
- {
- await _service.UpdateShipment(new Shipment());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Shipment>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Shipment>>(), default(CancellationToken)), Times.Once);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<Shipment>>();
+ _repositoryShipmentNoteMock = new Mock<IRepository<ShipmentNote>>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new ShipmentService(_repositoryMock.Object, _repositoryShipmentNoteMock.Object,
+ _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task DeleteShipment_InvokeExpectedMethods()
- {
- await _service.DeleteShipment(new Shipment());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Shipment>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Shipment>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertShipment_InvokeExpectedMethods()
+ {
+ await _service.InsertShipment(new Shipment());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Shipment>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Shipment>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteShipmentNote_InvokeExpectedMethods()
- {
- await _service.DeleteShipmentNote(new ShipmentNote());
- _repositoryShipmentNoteMock.Verify(c => c.DeleteAsync(It.IsAny<ShipmentNote>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<ShipmentNote>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateShipment_InvokeExpectedMethods()
+ {
+ await _service.UpdateShipment(new Shipment());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Shipment>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Shipment>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertShipmentNote_InvokeExpectedMethods()
- {
- await _service.InsertShipmentNote(new ShipmentNote());
- _repositoryShipmentNoteMock.Verify(c => c.InsertAsync(It.IsAny<ShipmentNote>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<ShipmentNote>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteShipment_InvokeExpectedMethods()
+ {
+ await _service.DeleteShipment(new Shipment());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Shipment>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Shipment>>(), default), Times.Once);
+ }
+ [TestMethod]
+ public async Task DeleteShipmentNote_InvokeExpectedMethods()
+ {
+ await _service.DeleteShipmentNote(new ShipmentNote());
+ _repositoryShipmentNoteMock.Verify(c => c.DeleteAsync(It.IsAny<ShipmentNote>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<ShipmentNote>>(), default), Times.Once);
+ }
+ [TestMethod]
+ public async Task InsertShipmentNote_InvokeExpectedMethods()
+ {
+ await _service.InsertShipmentNote(new ShipmentNote());
+ _repositoryShipmentNoteMock.Verify(c => c.InsertAsync(It.IsAny<ShipmentNote>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<ShipmentNote>>(), default), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingMethodServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingMethodServiceTests.cs
index ce5b6eb49..d9e8abd9e 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingMethodServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingMethodServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Checkout.Shipping;
-using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Data;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Caching;
@@ -8,68 +8,67 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Shipping
+namespace Grand.Business.Checkout.Tests.Services.Shipping;
+
+[TestClass]
+public class ShippingMethodServiceTests
{
- [TestClass]
- public class ShippingMethodServiceTests
- {
- private Mock<IRepository<ShippingMethod>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<ICacheBase> _cacheMock;
- private IShippingMethodService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<ShippingMethod>> _repositoryMock;
+ private IShippingMethodService _service;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<ShippingMethod>>();
- _mediatorMock = new Mock<IMediator>();
- _cacheMock = new Mock<ICacheBase>();
- _service = new ShippingMethodService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<ShippingMethod>>();
+ _mediatorMock = new Mock<IMediator>();
+ _cacheMock = new Mock<ICacheBase>();
+ _service = new ShippingMethodService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
+ }
- [TestMethod]
- public async Task InsertShippingMethod_InvokeExpectedMethods()
- {
- await _service.InsertShippingMethod(new ShippingMethod());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<ShippingMethod>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<ShippingMethod>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertShippingMethod_InvokeExpectedMethods()
+ {
+ await _service.InsertShippingMethod(new ShippingMethod());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<ShippingMethod>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<ShippingMethod>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertShippingMethod_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertShippingMethod(null));
- }
+ [TestMethod]
+ public void InsertShippingMethod_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertShippingMethod(null));
+ }
- [TestMethod]
- public async Task UpdateShippingMethod_InvokeExpectedMethods()
- {
- await _service.UpdateShippingMethod(new ShippingMethod());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<ShippingMethod>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<ShippingMethod>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateShippingMethod_InvokeExpectedMethods()
+ {
+ await _service.UpdateShippingMethod(new ShippingMethod());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<ShippingMethod>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<ShippingMethod>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateShippingMethod_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateShippingMethod(null));
- }
+ [TestMethod]
+ public void UpdateShippingMethod_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateShippingMethod(null));
+ }
- [TestMethod]
- public async Task DeleteShippingMethod_InvokeExpectedMethods()
- {
- await _service.DeleteShippingMethod(new ShippingMethod());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<ShippingMethod>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<ShippingMethod>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteShippingMethod_InvokeExpectedMethods()
+ {
+ await _service.DeleteShippingMethod(new ShippingMethod());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<ShippingMethod>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<ShippingMethod>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeleteShippingMethod_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteShippingMethod(null));
- }
+ [TestMethod]
+ public void DeleteShippingMethod_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteShippingMethod(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs
index d8264afde..34486b9de 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ShippingServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Checkout.Shipping;
-using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Domain.Common;
@@ -11,109 +11,107 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Shipping
+namespace Grand.Business.Checkout.Tests.Services.Shipping;
+
+[TestClass]
+public class ShippingServiceTests
{
- [TestClass]
- public class ShippingServiceTests
+ private Mock<ICountryService> _countryServiceMokc;
+ private Mock<ILogger<ShippingService>> _loggerMock;
+ private Mock<IShippingRateCalculationProvider> _rateProviderMock;
+ private IShippingService _service;
+ private ShippingProviderSettings _shippingProviderSettings;
+ private ShippingSettings _shippingSettings;
+ private Mock<ITranslationService> _translationServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<ILogger<ShippingService>> _loggerMock;
- private Mock<ITranslationService> _translationServiceMock;
- private Mock<ICountryService> _countryServiceMokc;
- private ShippingProviderSettings _shippingProviderSettings;
- private ShippingSettings _shippingSettings;
- private Mock<IShippingRateCalculationProvider> _rateProviderMock;
- private IShippingService _service;
+ _loggerMock = new Mock<ILogger<ShippingService>>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _countryServiceMokc = new Mock<ICountryService>();
+ _shippingProviderSettings = new ShippingProviderSettings();
+ _shippingSettings = new ShippingSettings();
+ _rateProviderMock = new Mock<IShippingRateCalculationProvider>();
+ _service = new ShippingService(_loggerMock.Object, _countryServiceMokc.Object,
+ new List<IShippingRateCalculationProvider> { _rateProviderMock.Object }, _shippingProviderSettings,
+ _shippingSettings);
+ }
- [TestInitialize]
- public void Init()
- {
- _loggerMock = new Mock<ILogger<ShippingService>>();
- _translationServiceMock = new Mock<ITranslationService>();
- _countryServiceMokc = new Mock<ICountryService>();
- _shippingProviderSettings = new ShippingProviderSettings();
- _shippingSettings = new ShippingSettings();
- _rateProviderMock = new Mock<IShippingRateCalculationProvider>();
- _service = new ShippingService(_loggerMock.Object, _countryServiceMokc.Object,
- new List<IShippingRateCalculationProvider> { _rateProviderMock.Object }, _shippingProviderSettings, _shippingSettings);
- }
+ [TestMethod]
+ public async Task LoadActiveShippingRateCalculationProviders_IsLimitToStore_ReturnEmptyList()
+ {
+ _rateProviderMock.Setup(c => c.LimitedToStores).Returns(new List<string>());
+ _rateProviderMock.Setup(c => c.LimitedToGroups).Returns(new List<string>());
+ var result = await _service.LoadActiveShippingRateCalculationProviders(new Customer(), "storeId");
+ Assert.IsTrue(result.Count == 0);
+ }
- [TestMethod]
- public async Task LoadActiveShippingRateCalculationProviders_IsLimitToStore_ReturnEmptyList()
- {
- _rateProviderMock.Setup(c => c.LimitedToStores).Returns(new List<string>());
- _rateProviderMock.Setup(c => c.LimitedToGroups).Returns(new List<string>());
- var result = await _service.LoadActiveShippingRateCalculationProviders(new Customer(), "storeId");
- Assert.IsTrue(result.Count == 0);
- }
+ [TestMethod]
+ public async Task LoadActiveShippingRateCalculationProviders_HideShipmentMethods_ReturnEmptyList()
+ {
+ _rateProviderMock.Setup(c => c.LimitedToStores).Returns(new List<string> { "storeId" });
+ _rateProviderMock.Setup(c => c.LimitedToGroups).Returns(new List<string>());
+ _rateProviderMock.Setup(c => c.HideShipmentMethods(It.IsAny<IList<ShoppingCartItem>>())).ReturnsAsync(true);
+ var result = await _service.LoadActiveShippingRateCalculationProviders(new Customer(), "storeId");
+ Assert.IsTrue(result.Count == 0);
+ }
- [TestMethod]
- public async Task LoadActiveShippingRateCalculationProviders_HideShipmentMethods_ReturnEmptyList()
- {
- _rateProviderMock.Setup(c => c.LimitedToStores).Returns(new List<string> { "storeId" });
- _rateProviderMock.Setup(c => c.LimitedToGroups).Returns(new List<string> { });
- _rateProviderMock.Setup(c => c.HideShipmentMethods(It.IsAny<IList<ShoppingCartItem>>())).ReturnsAsync(true);
- var result = await _service.LoadActiveShippingRateCalculationProviders(new Customer(), "storeId");
- Assert.IsTrue(result.Count == 0);
- }
+ [TestMethod]
+ public async Task LoadActiveShippingRateCalculationProviders_ReturnExpectedValues()
+ {
+ _shippingProviderSettings.ActiveSystemNames = ["sysname"];
+ _rateProviderMock.Setup(c => c.LimitedToStores).Returns(new List<string> { "storeId" });
+ _rateProviderMock.Setup(c => c.LimitedToGroups).Returns(new List<string>());
+ _rateProviderMock.Setup(c => c.SystemName).Returns("sysname");
+ _rateProviderMock.Setup(c => c.HideShipmentMethods(It.IsAny<IList<ShoppingCartItem>>())).ReturnsAsync(false);
+ var result = await _service.LoadActiveShippingRateCalculationProviders(new Customer(), "storeId");
+ Assert.IsTrue(result.Count == 1);
+ Assert.AreEqual(result.First().SystemName, _rateProviderMock.Object.SystemName);
+ }
- [TestMethod]
- public async Task LoadActiveShippingRateCalculationProviders_ReturnExpectedValues()
- {
- _shippingProviderSettings.ActiveSystemNames = ["sysname"];
- _rateProviderMock.Setup(c => c.LimitedToStores).Returns(new List<string> { "storeId" });
- _rateProviderMock.Setup(c => c.LimitedToGroups).Returns(new List<string> { });
- _rateProviderMock.Setup(c => c.SystemName).Returns("sysname");
- _rateProviderMock.Setup(c => c.HideShipmentMethods(It.IsAny<IList<ShoppingCartItem>>())).ReturnsAsync(false);
- var result = await _service.LoadActiveShippingRateCalculationProviders(new Customer(), "storeId");
- Assert.IsTrue(result.Count == 1);
- Assert.AreEqual(result.First().SystemName, _rateProviderMock.Object.SystemName);
- }
+ [TestMethod]
+ public async Task CreateShippingOptionRequests_ReturnExpectedResults()
+ {
+ var cart = new List<ShoppingCartItem> {
+ new() {
+ IsShipEnabled = true,
+ WarehouseId = "id"
+ }
+ };
- [TestMethod]
- public async Task CreateShippingOptionRequests_ReturnExpectedResults()
- {
- var cart = new List<ShoppingCartItem>
- {
- new ShoppingCartItem {
- IsShipEnabled=true,
- WarehouseId="id"
- }
- };
+ var customer = new Customer();
+ var shippingAddress = new Address();
+ var store = new Store { Id = "id" };
+ var warehouse = new Warehouse {
+ Address = null
+ };
- var customer = new Customer();
- var shippingAddress = new Address();
- var store = new Store { Id = "id" };
- var warehouse = new Warehouse {
- Address = null
- };
-
- var result = await _service.CreateShippingOptionRequests(customer, cart, shippingAddress, store);
+ var result = await _service.CreateShippingOptionRequests(customer, cart, shippingAddress, store);
- Assert.AreEqual(result.ShippingAddress, shippingAddress);
- Assert.AreEqual(result.StoreId, "id");
- Assert.AreEqual(result.Customer, customer);
- }
+ Assert.AreEqual(result.ShippingAddress, shippingAddress);
+ Assert.AreEqual(result.StoreId, "id");
+ Assert.AreEqual(result.Customer, customer);
+ }
- [TestMethod]
- public async Task CreateShippingOptionRequests_ShipNotEnable_ReturnEmptyList()
- {
- var cart = new List<ShoppingCartItem>
- {
- new ShoppingCartItem {
- IsShipEnabled=false,
- WarehouseId="id"
- }
- };
+ [TestMethod]
+ public async Task CreateShippingOptionRequests_ShipNotEnable_ReturnEmptyList()
+ {
+ var cart = new List<ShoppingCartItem> {
+ new() {
+ IsShipEnabled = false,
+ WarehouseId = "id"
+ }
+ };
- var customer = new Customer();
- var shippingAddress = new Address();
- var store = new Store { Id = "id" };
- var warehouse = new Warehouse {
- Address = null
- };
+ var customer = new Customer();
+ var shippingAddress = new Address();
+ var store = new Store { Id = "id" };
+ var warehouse = new Warehouse {
+ Address = null
+ };
- var result = await _service.CreateShippingOptionRequests(customer, cart, shippingAddress, store);
- Assert.IsTrue(result != null);
- }
+ var result = await _service.CreateShippingOptionRequests(customer, cart, shippingAddress, store);
+ Assert.IsTrue(result != null);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/WarehouseServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/WarehouseServiceTests.cs
index d25393b98..2e3f68d15 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/WarehouseServiceTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/WarehouseServiceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Checkout.Shipping;
-using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Checkout.Services.Shipping;
+using Grand.Business.Core.Interfaces.Checkout.Shipping;
using Grand.Data;
using Grand.Domain.Shipping;
using Grand.Infrastructure.Caching;
@@ -8,69 +8,68 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Services.Shipping
+namespace Grand.Business.Checkout.Tests.Services.Shipping;
+
+[TestClass]
+public class WarehouseServiceTests
{
- [TestClass]
- public class WarehouseServiceTests
- {
- private Mock<IRepository<Warehouse>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<ICacheBase> _cacheMock;
- private IWarehouseService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Warehouse>> _repositoryMock;
+ private IWarehouseService _service;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<Warehouse>>();
- _mediatorMock = new Mock<IMediator>();
- _cacheMock = new Mock<ICacheBase>();
- _service = new WarehouseService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<Warehouse>>();
+ _mediatorMock = new Mock<IMediator>();
+ _cacheMock = new Mock<ICacheBase>();
+ _service = new WarehouseService(_repositoryMock.Object, _mediatorMock.Object, _cacheMock.Object);
+ }
- [TestMethod]
- public async Task InsertWarehouse_InvokeExpectedMethods()
- {
- await _service.InsertWarehouse(new Warehouse());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Warehouse>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Warehouse>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertWarehouse_InvokeExpectedMethods()
+ {
+ await _service.InsertWarehouse(new Warehouse());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Warehouse>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Warehouse>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertWarehouse_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertWarehouse(null));
- }
+ [TestMethod]
+ public void InsertWarehouse_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertWarehouse(null));
+ }
- [TestMethod]
- public async Task UpdateWarehouse_InvokeExpectedMethods()
- {
- await _service.UpdateWarehouse(new Warehouse());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Warehouse>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Warehouse>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateWarehouse_InvokeExpectedMethods()
+ {
+ await _service.UpdateWarehouse(new Warehouse());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Warehouse>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Warehouse>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateWarehouse_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateWarehouse(null));
- }
+ [TestMethod]
+ public void UpdateWarehouse_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateWarehouse(null));
+ }
- [TestMethod]
- public async Task DeleteWarehouse_InvokeExpectedMethods()
- {
- await _service.DeleteWarehouse(new Warehouse());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Warehouse>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Warehouse>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteWarehouse_InvokeExpectedMethods()
+ {
+ await _service.DeleteWarehouse(new Warehouse());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Warehouse>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.AtLeast(1));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Warehouse>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeleteWarehouse_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteWarehouse(null));
- }
+ [TestMethod]
+ public void DeleteWarehouse_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteWarehouse(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Startup/StartupApplicationTests.cs
index 6d6a5acb5..9f2f6f233 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Checkout.Tests.Startup
+namespace Grand.Business.Checkout.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs
index 6c337b88f..aad27d198 100644
--- a/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs
+++ b/src/Tests/Grand.Business.Checkout.Tests/Validators/ShoppingCartValidatorsTests.cs
@@ -10,353 +10,423 @@ using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Orders;
using Grand.Domain.Permissions;
+using Grand.Domain.Stores;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Checkout.Tests.Validators
+namespace Grand.Business.Checkout.Tests.Validators;
+
+[TestClass]
+public class ShoppingCartValidatorsTests
{
- [TestClass]
- public class ShoppingCartValidatorsTests
+ private Mock<IAclService> _aclServiceMock;
+ private Mock<ICheckoutAttributeParser> _checkoutAttributeParserMock;
+ private Mock<ICheckoutAttributeService> _checkoutAttributeServiceMock;
+ private Mock<IPermissionService> _permissionServiceMock;
+ private Mock<IProductAttributeService> _productAttributeService;
+ private Mock<IProductReservationService> _productReservationServiceMock;
+ private Mock<IProductService> _productServiceMock;
+ private IStockQuantityService _stockQuantityService;
+ private Mock<ITranslationService> _translationServiceMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _translationServiceMock = new Mock<ITranslationService>();
+ _checkoutAttributeParserMock = new Mock<ICheckoutAttributeParser>();
+ _checkoutAttributeServiceMock = new Mock<ICheckoutAttributeService>();
+ _productServiceMock = new Mock<IProductService>();
+ _aclServiceMock = new Mock<IAclService>();
+ _productAttributeService = new Mock<IProductAttributeService>();
+ _productReservationServiceMock = new Mock<IProductReservationService>();
+ _permissionServiceMock = new Mock<IPermissionService>();
+ _stockQuantityService = new StockQuantityService();
+ _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
+ }
+
+ [TestMethod]
+ public void ShoppingCartAuctionValidator_Success()
{
- private Mock<ITranslationService> _translationServiceMock;
- private Mock<ICheckoutAttributeParser> _checkoutAttributeParserMock;
- private Mock<ICheckoutAttributeService> _checkoutAttributeServiceMock;
- private Mock<IProductService> _productServiceMock;
- private Mock<IAclService> _aclServiceMock;
- private Mock<IProductAttributeService> _productAttributeService;
- private Mock<IProductReservationService> _productReservationServiceMock;
- private Mock<IPermissionService> _permissionServiceMock;
- private IStockQuantityService _stockQuantityService;
-
- [TestInitialize]
- public void Init()
- {
- _translationServiceMock = new Mock<ITranslationService>();
- _checkoutAttributeParserMock = new Mock<ICheckoutAttributeParser>();
- _checkoutAttributeServiceMock = new Mock<ICheckoutAttributeService>();
- _productServiceMock = new Mock<IProductService>();
- _aclServiceMock = new Mock<IAclService>();
- _productAttributeService = new Mock<IProductAttributeService>();
- _productReservationServiceMock = new Mock<IProductReservationService>();
- _permissionServiceMock = new Mock<IPermissionService>();
- _stockQuantityService = new StockQuantityService();
- _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Name");
- }
-
- [TestMethod]
- public void ShoppingCartAuctionValidator_Success()
- {
- //Arrange
- var shoppingCartAuctionValidator = new ShoppingCartAuctionValidator(_translationServiceMock.Object);
- //Act
- var result = shoppingCartAuctionValidator.Validate(new ShoppingCartAuctionValidatorRecord(new Domain.Customers.Customer(), new Domain.Catalog.Product { AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1) }, new Domain.Orders.ShoppingCartItem(), 10));
- //Assert
- Assert.IsTrue(result.IsValid);
-
- }
-
- [TestMethod]
- public void ShoppingCartAuctionValidator_Fail()
- {
- //Arrange
- var shoppingCartAuctionValidator = new ShoppingCartAuctionValidator(_translationServiceMock.Object);
- //Act
- var result = shoppingCartAuctionValidator.Validate(new ShoppingCartAuctionValidatorRecord(new Domain.Customers.Customer(), new Domain.Catalog.Product { AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1), StartPrice = 20 }, new Domain.Orders.ShoppingCartItem(), 10));
- //Assert
- Assert.IsFalse(result.IsValid);
- }
- [TestMethod]
- public void ShoppingCartGiftVoucherValidator_Success()
- {
- //Arrange
- var shoppingCartGiftVoucherValidator = new ShoppingCartGiftVoucherValidator(_translationServiceMock.Object);
- var customAttributes = new List<CustomAttribute>();
- customAttributes.Add(new CustomAttribute { Key = "RecipientName", Value = "value" });
- customAttributes.Add(new CustomAttribute { Key = "RecipientEmail", Value = "[email protected]" });
- customAttributes.Add(new CustomAttribute { Key = "SenderName", Value = "value" });
- customAttributes.Add(new CustomAttribute { Key = "SenderEmail", Value = "[email protected]" });
- customAttributes.Add(new CustomAttribute { Key = "Message", Value = "value" });
- //Act
- var result = shoppingCartGiftVoucherValidator.Validate(new ShoppingCartGiftVoucherValidatorRecord(new Domain.Customers.Customer(), new Domain.Catalog.Product {
+ //Arrange
+ var shoppingCartAuctionValidator = new ShoppingCartAuctionValidator(_translationServiceMock.Object);
+ //Act
+ var result = shoppingCartAuctionValidator.Validate(new ShoppingCartAuctionValidatorRecord(new Customer(),
+ new Product { AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1) }, new ShoppingCartItem(), 10));
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public void ShoppingCartAuctionValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartAuctionValidator = new ShoppingCartAuctionValidator(_translationServiceMock.Object);
+ //Act
+ var result = shoppingCartAuctionValidator.Validate(new ShoppingCartAuctionValidatorRecord(new Customer(),
+ new Product { AvailableEndDateTimeUtc = DateTime.UtcNow.AddDays(1), StartPrice = 20 },
+ new ShoppingCartItem(), 10));
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public void ShoppingCartGiftVoucherValidator_Success()
+ {
+ //Arrange
+ var shoppingCartGiftVoucherValidator = new ShoppingCartGiftVoucherValidator(_translationServiceMock.Object);
+ var customAttributes = new List<CustomAttribute>();
+ customAttributes.Add(new CustomAttribute { Key = "RecipientName", Value = "value" });
+ customAttributes.Add(new CustomAttribute { Key = "RecipientEmail", Value = "[email protected]" });
+ customAttributes.Add(new CustomAttribute { Key = "SenderName", Value = "value" });
+ customAttributes.Add(new CustomAttribute { Key = "SenderEmail", Value = "[email protected]" });
+ customAttributes.Add(new CustomAttribute { Key = "Message", Value = "value" });
+ //Act
+ var result = shoppingCartGiftVoucherValidator.Validate(new ShoppingCartGiftVoucherValidatorRecord(
+ new Customer(), new Product {
GiftVoucherTypeId = GiftVoucherType.Virtual
- }, new Domain.Orders.ShoppingCartItem { Attributes = customAttributes }));
- //Assert
- Assert.IsTrue(result.IsValid);
-
- }
-
- [TestMethod]
- public void ShoppingCartGiftVoucherValidator_Fail_Wrong_SenderEmail()
- {
- //Arrange
- var shoppingCartGiftVoucherValidator = new ShoppingCartGiftVoucherValidator(_translationServiceMock.Object);
- var customAttributes = new List<CustomAttribute>();
- customAttributes.Add(new CustomAttribute { Key = "RecipientName", Value = "value" });
- customAttributes.Add(new CustomAttribute { Key = "RecipientEmail", Value = "[email protected]" });
- customAttributes.Add(new CustomAttribute { Key = "SenderName", Value = "value" });
- customAttributes.Add(new CustomAttribute { Key = "SenderEmail", Value = "@email.com" });
- customAttributes.Add(new CustomAttribute { Key = "Message", Value = "value" });
- //Act
- var result = shoppingCartGiftVoucherValidator.Validate(new ShoppingCartGiftVoucherValidatorRecord(new Domain.Customers.Customer(), new Domain.Catalog.Product {
+ }, new ShoppingCartItem { Attributes = customAttributes }));
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public void ShoppingCartGiftVoucherValidator_Fail_Wrong_SenderEmail()
+ {
+ //Arrange
+ var shoppingCartGiftVoucherValidator = new ShoppingCartGiftVoucherValidator(_translationServiceMock.Object);
+ var customAttributes = new List<CustomAttribute>();
+ customAttributes.Add(new CustomAttribute { Key = "RecipientName", Value = "value" });
+ customAttributes.Add(new CustomAttribute { Key = "RecipientEmail", Value = "[email protected]" });
+ customAttributes.Add(new CustomAttribute { Key = "SenderName", Value = "value" });
+ customAttributes.Add(new CustomAttribute { Key = "SenderEmail", Value = "@email.com" });
+ customAttributes.Add(new CustomAttribute { Key = "Message", Value = "value" });
+ //Act
+ var result = shoppingCartGiftVoucherValidator.Validate(new ShoppingCartGiftVoucherValidatorRecord(
+ new Customer(), new Product {
GiftVoucherTypeId = GiftVoucherType.Virtual
- }, new Domain.Orders.ShoppingCartItem { Attributes = customAttributes }));
- //Assert
- Assert.IsFalse(result.IsValid);
-
- }
-
- [TestMethod]
- public async Task ShoppingCartCheckoutAttributesValidator_Success()
- {
- //Arrange
- var shoppingCartCheckoutValidator = new ShoppingCartCheckoutAttributesValidator(_translationServiceMock.Object,
- _checkoutAttributeParserMock.Object, _checkoutAttributeServiceMock.Object);
-
- _checkoutAttributeParserMock.Setup(x => x.ParseCheckoutAttributes(It.IsAny<IList<CustomAttribute>>()))
- .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> { new CheckoutAttribute { Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox } }));
-
- _checkoutAttributeServiceMock.Setup(x => x.GetAllCheckoutAttributes(It.IsAny<string>(), true, false))
- .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> { new CheckoutAttribute { Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox } }));
-
- _checkoutAttributeParserMock.Setup(x => x.IsConditionMet(
- It.IsAny<CheckoutAttribute>(), It.IsAny<IList<CustomAttribute>>())).Returns(() => Task.FromResult((bool?)true));
-
- //Act
- var result = await shoppingCartCheckoutValidator.ValidateAsync(new ShoppingCartCheckoutAttributesValidatorRecord(
- new Domain.Customers.Customer(),
- new Domain.Stores.Store(),
- new List<ShoppingCartItem> { new ShoppingCartItem { } },
- new List<CustomAttribute> { new CustomAttribute { Key = "1", Value = "test" } }
- ));
-
- //Assert
- Assert.IsTrue(result.IsValid);
- }
-
- [TestMethod]
- public async Task ShoppingCartCheckoutAttributesValidator_Fail()
- {
- //Arrange
- var shoppingCartCheckoutValidator = new ShoppingCartCheckoutAttributesValidator(_translationServiceMock.Object,
- _checkoutAttributeParserMock.Object, _checkoutAttributeServiceMock.Object);
-
- _checkoutAttributeParserMock.Setup(x => x.ParseCheckoutAttributes(It.IsAny<IList<CustomAttribute>>()))
- .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> { new CheckoutAttribute { Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox, ValidationMinLength = 10 } }));
-
- _checkoutAttributeServiceMock.Setup(x => x.GetAllCheckoutAttributes(It.IsAny<string>(), true, false))
- .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> { new CheckoutAttribute { Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox, ValidationMinLength = 10 } }));
-
- _checkoutAttributeParserMock.Setup(x => x.IsConditionMet(
- It.IsAny<CheckoutAttribute>(), It.IsAny<IList<CustomAttribute>>())).Returns(() => Task.FromResult((bool?)true));
-
- //Act
- var result = await shoppingCartCheckoutValidator.ValidateAsync(new ShoppingCartCheckoutAttributesValidatorRecord(
- new Domain.Customers.Customer(),
- new Domain.Stores.Store(),
- new List<ShoppingCartItem> { new ShoppingCartItem { } },
- new List<CustomAttribute> { new CustomAttribute { Key = "1", Value = "" } }
- ));
-
- //Assert
- Assert.IsFalse(result.IsValid);
- }
-
- [TestMethod]
- public async Task ShoppingCartInventoryProductValidator_Success()
- {
- //Arrange
- var shoppingCartInventoryValidator = new ShoppingCartInventoryProductValidator(_translationServiceMock.Object,
- _productServiceMock.Object, _stockQuantityService, new ShoppingCartSettings { });
-
- //Act
- var result = await shoppingCartInventoryValidator.ValidateAsync(new ShoppingCartInventoryProductValidatorRecord(
- new Domain.Customers.Customer(),
- new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock },
- new ShoppingCartItem { ProductId = "1", Quantity = 1 }
- ));
-
- //Assert
- Assert.IsTrue(result.IsValid);
- }
- [TestMethod]
- public async Task ShoppingCartInventoryProductValidator_Fail()
- {
- //Arrange
- var shoppingCartInventoryValidator = new ShoppingCartInventoryProductValidator(_translationServiceMock.Object,
- _productServiceMock.Object, _stockQuantityService, new ShoppingCartSettings { });
-
- //Act
- var result = await shoppingCartInventoryValidator.ValidateAsync(new ShoppingCartInventoryProductValidatorRecord(
- new Domain.Customers.Customer(),
- new Product { Id = "1", StockQuantity = 0, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock },
- new ShoppingCartItem { ProductId = "1", Quantity = 1 }
- ));
-
- //Assert
- Assert.IsFalse(result.IsValid);
- }
-
- [TestMethod]
- public async Task ShoppingCartItemAttributeValidator_Success()
- {
- //Arrange
- var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object,
- _productServiceMock.Object, _productAttributeService.Object);
-
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
- .Returns(() => Task.FromResult(new Product()));
-
- _productAttributeService.Setup(x => x.GetProductAttributeById(It.IsAny<string>()))
- .Returns(() => Task.FromResult(new ProductAttribute { Name = "test" }));
-
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock };
- var mapping = new ProductAttributeMapping { Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList, IsRequired = true };
- mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
- product.ProductAttributeMappings.Add(mapping);
-
- var attributes = new List<CustomAttribute> { new CustomAttribute { Key = "1", Value = "1" } };
-
- //Act
- var result = await shoppingCartItemAttributeValidator.ValidateAsync(new ShoppingCartItemAttributeValidatorRecord(
- new Domain.Customers.Customer(),
+ }, new ShoppingCartItem { Attributes = customAttributes }));
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartCheckoutAttributesValidator_Success()
+ {
+ //Arrange
+ var shoppingCartCheckoutValidator = new ShoppingCartCheckoutAttributesValidator(_translationServiceMock.Object,
+ _checkoutAttributeParserMock.Object, _checkoutAttributeServiceMock.Object);
+
+ _checkoutAttributeParserMock.Setup(x => x.ParseCheckoutAttributes(It.IsAny<IList<CustomAttribute>>()))
+ .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> {
+ new() {
+ Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox
+ }
+ }));
+
+ _checkoutAttributeServiceMock.Setup(x => x.GetAllCheckoutAttributes(It.IsAny<string>(), true, false))
+ .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> {
+ new() {
+ Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox
+ }
+ }));
+
+ _checkoutAttributeParserMock.Setup(x => x.IsConditionMet(
+ It.IsAny<CheckoutAttribute>(), It.IsAny<IList<CustomAttribute>>()))
+ .Returns(() => Task.FromResult((bool?)true));
+
+ //Act
+ var result = await shoppingCartCheckoutValidator.ValidateAsync(
+ new ShoppingCartCheckoutAttributesValidatorRecord(
+ new Customer(),
+ new Store(),
+ new List<ShoppingCartItem> { new() },
+ new List<CustomAttribute> { new() { Key = "1", Value = "test" } }
+ ));
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartCheckoutAttributesValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartCheckoutValidator = new ShoppingCartCheckoutAttributesValidator(_translationServiceMock.Object,
+ _checkoutAttributeParserMock.Object, _checkoutAttributeServiceMock.Object);
+
+ _checkoutAttributeParserMock.Setup(x => x.ParseCheckoutAttributes(It.IsAny<IList<CustomAttribute>>()))
+ .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> {
+ new() {
+ Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox,
+ ValidationMinLength = 10
+ }
+ }));
+
+ _checkoutAttributeServiceMock.Setup(x => x.GetAllCheckoutAttributes(It.IsAny<string>(), true, false))
+ .Returns(() => Task.FromResult((IList<CheckoutAttribute>)new List<CheckoutAttribute> {
+ new() {
+ Id = "1", Name = "test", IsRequired = true, AttributeControlTypeId = AttributeControlType.TextBox,
+ ValidationMinLength = 10
+ }
+ }));
+
+ _checkoutAttributeParserMock.Setup(x => x.IsConditionMet(
+ It.IsAny<CheckoutAttribute>(), It.IsAny<IList<CustomAttribute>>()))
+ .Returns(() => Task.FromResult((bool?)true));
+
+ //Act
+ var result = await shoppingCartCheckoutValidator.ValidateAsync(
+ new ShoppingCartCheckoutAttributesValidatorRecord(
+ new Customer(),
+ new Store(),
+ new List<ShoppingCartItem> { new() },
+ new List<CustomAttribute> { new() { Key = "1", Value = "" } }
+ ));
+
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartInventoryProductValidator_Success()
+ {
+ //Arrange
+ var shoppingCartInventoryValidator = new ShoppingCartInventoryProductValidator(_translationServiceMock.Object,
+ _productServiceMock.Object, _stockQuantityService, new ShoppingCartSettings());
+
+ //Act
+ var result = await shoppingCartInventoryValidator.ValidateAsync(new ShoppingCartInventoryProductValidatorRecord(
+ new Customer(),
+ new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ },
+ new ShoppingCartItem { ProductId = "1", Quantity = 1 }
+ ));
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartInventoryProductValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartInventoryValidator = new ShoppingCartInventoryProductValidator(_translationServiceMock.Object,
+ _productServiceMock.Object, _stockQuantityService, new ShoppingCartSettings());
+
+ //Act
+ var result = await shoppingCartInventoryValidator.ValidateAsync(new ShoppingCartInventoryProductValidatorRecord(
+ new Customer(),
+ new Product {
+ Id = "1", StockQuantity = 0, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ },
+ new ShoppingCartItem { ProductId = "1", Quantity = 1 }
+ ));
+
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartItemAttributeValidator_Success()
+ {
+ //Arrange
+ var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object,
+ _productServiceMock.Object, _productAttributeService.Object);
+
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(() => Task.FromResult(new Product()));
+
+ _productAttributeService.Setup(x => x.GetProductAttributeById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new ProductAttribute { Name = "test" }));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ };
+ var mapping = new ProductAttributeMapping {
+ Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList,
+ IsRequired = true
+ };
+ mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
+ product.ProductAttributeMappings.Add(mapping);
+
+ var attributes = new List<CustomAttribute> { new() { Key = "1", Value = "1" } };
+
+ //Act
+ var result = await shoppingCartItemAttributeValidator.ValidateAsync(
+ new ShoppingCartItemAttributeValidatorRecord(
+ new Customer(),
product,
new ShoppingCartItem { ProductId = "1", Quantity = 1, Attributes = attributes },
false
- ));
-
- //Assert
- Assert.IsTrue(result.IsValid);
- }
- [TestMethod]
- public async Task ShoppingCartItemAttributeValidator_Fail()
- {
- //Arrange
- var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object,
- _productServiceMock.Object, _productAttributeService.Object);
-
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
- .Returns(() => Task.FromResult(new Product()));
-
- _productAttributeService.Setup(x => x.GetProductAttributeById(It.IsAny<string>()))
- .Returns(() => Task.FromResult(new ProductAttribute { Name = "test" }));
-
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock };
- var mapping = new ProductAttributeMapping { Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList, IsRequired = true };
- mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
- product.ProductAttributeMappings.Add(mapping);
-
- var attributes = new List<CustomAttribute> { new CustomAttribute { Key = "2" } };
-
- //Act
- var result = await shoppingCartItemAttributeValidator.ValidateAsync(new ShoppingCartItemAttributeValidatorRecord(
- new Domain.Customers.Customer(),
+ ));
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartItemAttributeValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartItemAttributeValidator = new ShoppingCartItemAttributeValidator(_translationServiceMock.Object,
+ _productServiceMock.Object, _productAttributeService.Object);
+
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(() => Task.FromResult(new Product()));
+
+ _productAttributeService.Setup(x => x.GetProductAttributeById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new ProductAttribute { Name = "test" }));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ };
+ var mapping = new ProductAttributeMapping {
+ Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList,
+ IsRequired = true
+ };
+ mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
+ product.ProductAttributeMappings.Add(mapping);
+
+ var attributes = new List<CustomAttribute> { new() { Key = "2" } };
+
+ //Act
+ var result = await shoppingCartItemAttributeValidator.ValidateAsync(
+ new ShoppingCartItemAttributeValidatorRecord(
+ new Customer(),
product,
new ShoppingCartItem { ProductId = "1", Quantity = 1, Attributes = attributes },
false
- ));
-
- //Assert
- Assert.IsFalse(result.IsValid);
- }
-
- [TestMethod]
- public async Task ShoppingCartRequiredProductValidator_Success()
- {
- //Arrange
- var shoppingCartRequiredProductValidator = new ShoppingCartRequiredProductValidator(_translationServiceMock.Object, _productServiceMock.Object, new ShoppingCartSettings());
-
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
- .Returns(() => Task.FromResult(new Product()));
-
- _productServiceMock.Setup(x => x.GetProductById("1", false))
- .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
-
- _productServiceMock.Setup(x => x.GetProductById("2", false))
- .Returns(() => Task.FromResult(new Product { Id = "2", Name = "test" }));
-
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- RequireOtherProducts = true,
- RequiredProductIds = "2"
- };
- var customer = new Domain.Customers.Customer();
- customer.ShoppingCartItems.Add(new ShoppingCartItem { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
- //Act
- var result = await shoppingCartRequiredProductValidator.ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(
+ ));
+
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartRequiredProductValidator_Success()
+ {
+ //Arrange
+ var shoppingCartRequiredProductValidator =
+ new ShoppingCartRequiredProductValidator(_translationServiceMock.Object, _productServiceMock.Object,
+ new ShoppingCartSettings());
+
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(() => Task.FromResult(new Product()));
+
+ _productServiceMock.Setup(x => x.GetProductById("1", false))
+ .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
+
+ _productServiceMock.Setup(x => x.GetProductById("2", false))
+ .Returns(() => Task.FromResult(new Product { Id = "2", Name = "test" }));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ RequireOtherProducts = true,
+ RequiredProductIds = "2"
+ };
+ var customer = new Customer();
+ customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
+ //Act
+ var result = await shoppingCartRequiredProductValidator.ValidateAsync(
+ new ShoppingCartRequiredProductValidatorRecord(
customer,
- new Domain.Stores.Store { Id = "1" },
+ new Store { Id = "1" },
product,
- new ShoppingCartItem { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
- ));
-
- //Assert
- Assert.IsTrue(result.IsValid);
- }
-
- [TestMethod]
- public async Task ShoppingCartRequiredProductValidator_Fail()
- {
- //Arrange
- var shoppingCartRequiredProductValidator = new ShoppingCartRequiredProductValidator(_translationServiceMock.Object, _productServiceMock.Object, new ShoppingCartSettings());
-
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
- .Returns(() => Task.FromResult(new Product()));
-
- _productServiceMock.Setup(x => x.GetProductById("1", false))
- .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
-
- _productServiceMock.Setup(x => x.GetProductById("2", false))
- .Returns(() => Task.FromResult(new Product { Id = "2", Name = "test" }));
-
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
- RequireOtherProducts = true,
- RequiredProductIds = "2"
- };
- var customer = new Domain.Customers.Customer();
- //Act
- var result = await shoppingCartRequiredProductValidator.ValidateAsync(new ShoppingCartRequiredProductValidatorRecord(
+ new ShoppingCartItem
+ { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
+ ));
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartRequiredProductValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartRequiredProductValidator =
+ new ShoppingCartRequiredProductValidator(_translationServiceMock.Object, _productServiceMock.Object,
+ new ShoppingCartSettings());
+
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(() => Task.FromResult(new Product()));
+
+ _productServiceMock.Setup(x => x.GetProductById("1", false))
+ .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
+
+ _productServiceMock.Setup(x => x.GetProductById("2", false))
+ .Returns(() => Task.FromResult(new Product { Id = "2", Name = "test" }));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock,
+ RequireOtherProducts = true,
+ RequiredProductIds = "2"
+ };
+ var customer = new Customer();
+ //Act
+ var result = await shoppingCartRequiredProductValidator.ValidateAsync(
+ new ShoppingCartRequiredProductValidatorRecord(
customer,
- new Domain.Stores.Store { Id = "1" },
+ new Store { Id = "1" },
product,
- new ShoppingCartItem { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
- ));
+ new ShoppingCartItem
+ { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
+ ));
- //Assert
- Assert.IsFalse(result.IsValid);
- }
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
- [TestMethod]
- public async Task ShoppingCartReservationProductValidator_Success()
- {
- //Arrange
- var shoppingCartReservationProductValidator = new ShoppingCartReservationProductValidator(_translationServiceMock.Object, _productReservationServiceMock.Object);
+ [TestMethod]
+ public async Task ShoppingCartReservationProductValidator_Success()
+ {
+ //Arrange
+ var shoppingCartReservationProductValidator =
+ new ShoppingCartReservationProductValidator(_translationServiceMock.Object,
+ _productReservationServiceMock.Object);
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
- .Returns(() => Task.FromResult(new Product()));
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(() => Task.FromResult(new Product()));
- _productServiceMock.Setup(x => x.GetProductById("1", false))
- .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
+ _productServiceMock.Setup(x => x.GetProductById("1", false))
+ .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
- _productReservationServiceMock.Setup(x => x.GetCustomerReservationsHelpers(It.IsAny<string>()))
- .Returns(() => Task.FromResult((IList<CustomerReservationsHelper>)new List<CustomerReservationsHelper> { new CustomerReservationsHelper { Id = "1", CustomerId = "1", ShoppingCartItemId = "2" } }));
+ _productReservationServiceMock.Setup(x => x.GetCustomerReservationsHelpers(It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<CustomerReservationsHelper>)new List<CustomerReservationsHelper>
+ { new() { Id = "1", CustomerId = "1", ShoppingCartItemId = "2" } }));
- _productReservationServiceMock.Setup(x => x.GetProductReservationsByProductId(It.IsAny<string>(), true, null, 0, int.MaxValue))
- .Returns(() => Task.FromResult((IPagedList<ProductReservation>)
+ _productReservationServiceMock.Setup(x =>
+ x.GetProductReservationsByProductId(It.IsAny<string>(), true, null, 0, int.MaxValue))
+ .Returns(() => Task.FromResult((IPagedList<ProductReservation>)
new PagedList<ProductReservation> {
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(4).Date, Resource = "" },
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(3).Date, Resource = "" },
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(2).Date, Resource = "" },
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(1).Date, Resource = "" },
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.Date, Resource = "" } }
- ));
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(4).Date, Resource = "" },
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(3).Date, Resource = "" },
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(2).Date, Resource = "" },
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(1).Date, Resource = "" },
+ new() { Id = "1", Date = DateTime.UtcNow.Date, Resource = "" }
+ }
+ ));
- var product = new Product { Id = "1", ProductTypeId = ProductType.Reservation, IntervalUnitId = IntervalUnit.Day };
+ var product = new Product
+ { Id = "1", ProductTypeId = ProductType.Reservation, IntervalUnitId = IntervalUnit.Day };
- var customer = new Domain.Customers.Customer();
- customer.ShoppingCartItems.Add(new ShoppingCartItem { Id = "1", ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
- //Act
- var result = await shoppingCartReservationProductValidator.ValidateAsync(new ShoppingCartReservationProductValidatorRecord(
+ var customer = new Customer();
+ customer.ShoppingCartItems.Add(new ShoppingCartItem {
+ Id = "1", ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1"
+ });
+ //Act
+ var result = await shoppingCartReservationProductValidator.ValidateAsync(
+ new ShoppingCartReservationProductValidatorRecord(
customer,
product,
new ShoppingCartItem {
@@ -367,43 +437,53 @@ namespace Grand.Business.Checkout.Tests.Validators
RentalStartDateUtc = DateTime.UtcNow.AddDays(1).Date,
RentalEndDateUtc = DateTime.UtcNow.AddDays(2).Date
}
- ));
+ ));
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
- //Assert
- Assert.IsTrue(result.IsValid);
- }
- [TestMethod]
- public async Task ShoppingCartReservationProductValidator_Fail()
- {
- //Arrange
- var shoppingCartReservationProductValidator = new ShoppingCartReservationProductValidator(_translationServiceMock.Object, _productReservationServiceMock.Object);
+ [TestMethod]
+ public async Task ShoppingCartReservationProductValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartReservationProductValidator =
+ new ShoppingCartReservationProductValidator(_translationServiceMock.Object,
+ _productReservationServiceMock.Object);
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
- .Returns(() => Task.FromResult(new Product()));
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(() => Task.FromResult(new Product()));
- _productServiceMock.Setup(x => x.GetProductById("1", false))
- .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
+ _productServiceMock.Setup(x => x.GetProductById("1", false))
+ .Returns(() => Task.FromResult(new Product { Id = "1", Name = "test" }));
- _productReservationServiceMock.Setup(x => x.GetCustomerReservationsHelpers(It.IsAny<string>()))
- .Returns(() => Task.FromResult((IList<CustomerReservationsHelper>)new List<CustomerReservationsHelper> { new CustomerReservationsHelper { Id = "1", CustomerId = "1", ShoppingCartItemId = "2" } }));
+ _productReservationServiceMock.Setup(x => x.GetCustomerReservationsHelpers(It.IsAny<string>()))
+ .Returns(() => Task.FromResult((IList<CustomerReservationsHelper>)new List<CustomerReservationsHelper>
+ { new() { Id = "1", CustomerId = "1", ShoppingCartItemId = "2" } }));
- _productReservationServiceMock.Setup(x => x.GetProductReservationsByProductId(It.IsAny<string>(), true, null, 0, int.MaxValue))
- .Returns(() => Task.FromResult((IPagedList<ProductReservation>)
+ _productReservationServiceMock.Setup(x =>
+ x.GetProductReservationsByProductId(It.IsAny<string>(), true, null, 0, int.MaxValue))
+ .Returns(() => Task.FromResult((IPagedList<ProductReservation>)
new PagedList<ProductReservation> {
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(10).Date, Resource = "" },
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(9).Date, Resource = "" },
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(8).Date, Resource = "" },
- new ProductReservation { Id = "1", Date = DateTime.UtcNow.AddDays(7).Date, Resource = "" } }
- ));
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(10).Date, Resource = "" },
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(9).Date, Resource = "" },
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(8).Date, Resource = "" },
+ new() { Id = "1", Date = DateTime.UtcNow.AddDays(7).Date, Resource = "" }
+ }
+ ));
- var product = new Product { Id = "1", ProductTypeId = ProductType.Reservation, IntervalUnitId = IntervalUnit.Day };
+ var product = new Product
+ { Id = "1", ProductTypeId = ProductType.Reservation, IntervalUnitId = IntervalUnit.Day };
- var customer = new Domain.Customers.Customer();
- customer.ShoppingCartItems.Add(new ShoppingCartItem { Id = "1", ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
- //Act
- var result = await shoppingCartReservationProductValidator.ValidateAsync(new ShoppingCartReservationProductValidatorRecord(
+ var customer = new Customer();
+ customer.ShoppingCartItems.Add(new ShoppingCartItem {
+ Id = "1", ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1"
+ });
+ //Act
+ var result = await shoppingCartReservationProductValidator.ValidateAsync(
+ new ShoppingCartReservationProductValidatorRecord(
customer,
product,
new ShoppingCartItem {
@@ -414,169 +494,209 @@ namespace Grand.Business.Checkout.Tests.Validators
RentalStartDateUtc = DateTime.UtcNow.AddDays(1).Date,
RentalEndDateUtc = DateTime.UtcNow.AddDays(2).Date
}
- ));
-
- //Assert
- Assert.IsFalse(result.IsValid);
- }
- [TestMethod]
- public async Task ShoppingCartCommonWarningsValidator_Success()
- {
- //Arrange
- var shoppingCartCommonWarningsValidator = new ShoppingCartCommonWarningsValidator(_translationServiceMock.Object, _permissionServiceMock.Object, new ShoppingCartSettings {
+ ));
+
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartCommonWarningsValidator_Success()
+ {
+ //Arrange
+ var shoppingCartCommonWarningsValidator = new ShoppingCartCommonWarningsValidator(
+ _translationServiceMock.Object, _permissionServiceMock.Object, new ShoppingCartSettings {
MiniCartProductNumber = 1,
MaximumShoppingCartItems = 100
});
- _permissionServiceMock.Setup(x => x.Authorize(It.IsAny<Permission>(), It.IsAny<Customer>())).Returns(async () => await Task.FromResult(true));
-
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock };
- var customer = new Domain.Customers.Customer();
- customer.ShoppingCartItems.Add(new ShoppingCartItem { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
- //Act
- var result = await shoppingCartCommonWarningsValidator.ValidateAsync(new ShoppingCartCommonWarningsValidatorRecord(
+ _permissionServiceMock.Setup(x => x.Authorize(It.IsAny<Permission>(), It.IsAny<Customer>()))
+ .Returns(async () => await Task.FromResult(true));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ };
+ var customer = new Customer();
+ customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
+ //Act
+ var result = await shoppingCartCommonWarningsValidator.ValidateAsync(
+ new ShoppingCartCommonWarningsValidatorRecord(
customer,
- new Domain.Stores.Store { Id = "1" },
+ new Store { Id = "1" },
new List<ShoppingCartItem> {
- new ShoppingCartItem { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
+ new() {
+ ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1"
+ }
},
product, ShoppingCartType.ShoppingCart, null, null, 1, "")
- );
-
- //Assert
- Assert.IsTrue(result.IsValid);
- }
- [TestMethod]
- public async Task ShoppingCartCommonWarningsValidator_Fail()
- {
- //Arrange
- var shoppingCartCommonWarningsValidator = new ShoppingCartCommonWarningsValidator(_translationServiceMock.Object, _permissionServiceMock.Object, new ShoppingCartSettings {
+ );
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
+
+ [TestMethod]
+ public async Task ShoppingCartCommonWarningsValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartCommonWarningsValidator = new ShoppingCartCommonWarningsValidator(
+ _translationServiceMock.Object, _permissionServiceMock.Object, new ShoppingCartSettings {
MiniCartProductNumber = 1,
MaximumShoppingCartItems = 100
});
- _permissionServiceMock.Setup(x => x.Authorize(It.IsAny<Permission>(), It.IsAny<Customer>())).Returns(async () => await Task.FromResult(false));
-
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock };
- var customer = new Domain.Customers.Customer();
- customer.ShoppingCartItems.Add(new ShoppingCartItem { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
- //Act
- var result = await shoppingCartCommonWarningsValidator.ValidateAsync(new ShoppingCartCommonWarningsValidatorRecord(
+ _permissionServiceMock.Setup(x => x.Authorize(It.IsAny<Permission>(), It.IsAny<Customer>()))
+ .Returns(async () => await Task.FromResult(false));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ };
+ var customer = new Customer();
+ customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { ProductId = "2", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" });
+ //Act
+ var result = await shoppingCartCommonWarningsValidator.ValidateAsync(
+ new ShoppingCartCommonWarningsValidatorRecord(
customer,
- new Domain.Stores.Store { Id = "1" },
+ new Store { Id = "1" },
new List<ShoppingCartItem> {
- new ShoppingCartItem { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
+ new() {
+ ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1"
+ }
},
product, ShoppingCartType.ShoppingCart, null, null, 1, "")
- );
-
- //Assert
- Assert.IsFalse(result.IsValid);
- }
-
- [TestMethod]
- public async Task ShoppingCartStandardValidator_Success()
- {
- //Arrange
- var shoppingCartStandardValidator = new ShoppingCartStandardValidator(_translationServiceMock.Object, _aclServiceMock.Object);
- _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<Customer>())).Returns(() => true);
- _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<string>())).Returns(() => true);
-
- var product = new Product {
- Id = "1",
- Published = true
- };
- var customer = new Domain.Customers.Customer();
- //Act
- var result = await shoppingCartStandardValidator.ValidateAsync(new ShoppingCartStandardValidatorRecord(
- customer,
- product,
- new ShoppingCartItem { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
- ));
-
- //Assert
- Assert.IsTrue(result.IsValid);
- }
- [TestMethod]
- public async Task ShoppingCartStandardValidator_Fail()
- {
- //Arrange
- var shoppingCartStandardValidator = new ShoppingCartStandardValidator(_translationServiceMock.Object, _aclServiceMock.Object);
- _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<Customer>())).Returns(() => false);
- _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<string>())).Returns(() => true);
-
- var product = new Product {
- Id = "1",
- Published = true
- };
- var customer = new Domain.Customers.Customer();
- //Act
- var result = await shoppingCartStandardValidator.ValidateAsync(new ShoppingCartStandardValidatorRecord(
- customer,
- product,
- new ShoppingCartItem { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
- ));
-
- //Assert
- Assert.IsFalse(result.IsValid);
- }
-
- [TestMethod]
- public async Task ShoppingCartWarningsValidator_Success()
- {
- //Arrange
- var shoppingCartWarningsValidator = new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object);
+ );
- _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
- .Returns(() => Task.FromResult(new Product()));
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock };
- var mapping = new ProductAttributeMapping { Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList, IsRequired = true };
- mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
- product.ProductAttributeMappings.Add(mapping);
+ [TestMethod]
+ public async Task ShoppingCartStandardValidator_Success()
+ {
+ //Arrange
+ var shoppingCartStandardValidator =
+ new ShoppingCartStandardValidator(_translationServiceMock.Object, _aclServiceMock.Object);
+ _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<Customer>())).Returns(() => true);
+ _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<string>())).Returns(() => true);
+
+ var product = new Product {
+ Id = "1",
+ Published = true
+ };
+ var customer = new Customer();
+ //Act
+ var result = await shoppingCartStandardValidator.ValidateAsync(new ShoppingCartStandardValidatorRecord(
+ customer,
+ product,
+ new ShoppingCartItem
+ { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
+ ));
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
- var attributes = new List<CustomAttribute> { new CustomAttribute { Key = "1", Value = "1" } };
+ [TestMethod]
+ public async Task ShoppingCartStandardValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartStandardValidator =
+ new ShoppingCartStandardValidator(_translationServiceMock.Object, _aclServiceMock.Object);
+ _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<Customer>())).Returns(() => false);
+ _aclServiceMock.Setup(x => x.Authorize(It.IsAny<Product>(), It.IsAny<string>())).Returns(() => true);
+
+ var product = new Product {
+ Id = "1",
+ Published = true
+ };
+ var customer = new Customer();
+ //Act
+ var result = await shoppingCartStandardValidator.ValidateAsync(new ShoppingCartStandardValidatorRecord(
+ customer,
+ product,
+ new ShoppingCartItem
+ { ProductId = "1", Quantity = 1, ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "1" }
+ ));
+
+ //Assert
+ Assert.IsFalse(result.IsValid);
+ }
- //Act
- var result = await shoppingCartWarningsValidator.ValidateAsync(new ShoppingCartWarningsValidatorRecord(
- new Domain.Customers.Customer(),
- new Domain.Stores.Store(),
- new List<ShoppingCartItem> {
- new ShoppingCartItem { ProductId = "1", Quantity = 1, Attributes = attributes }
- }
- ));
-
- //Assert
- Assert.IsTrue(result.IsValid);
- }
- [TestMethod]
- public async Task ShoppingCartWarningsValidator_Fail()
- {
- //Arrange
- var shoppingCartWarningsValidator = new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object);
-
- _productServiceMock.Setup(x => x.GetProductById("1", false))
- .Returns(() => Task.FromResult(new Product { IsRecurring = true, RecurringCyclePeriodId = RecurringCyclePeriod.Weeks }));
- _productServiceMock.Setup(x => x.GetProductById("2", false))
- .Returns(() => Task.FromResult(new Product { IsRecurring = false }));
-
- var product = new Product { Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10, ManageInventoryMethodId = ManageInventoryMethod.ManageStock };
- var mapping = new ProductAttributeMapping { Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList, IsRequired = true };
- mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
- product.ProductAttributeMappings.Add(mapping);
-
- var attributes = new List<CustomAttribute> { new CustomAttribute { Key = "1", Value = "1" } };
-
- //Act
- var result = await shoppingCartWarningsValidator.ValidateAsync(new ShoppingCartWarningsValidatorRecord(
- new Domain.Customers.Customer(),
- new Domain.Stores.Store(),
- new List<ShoppingCartItem> {
- new ShoppingCartItem { ProductId = "1", Quantity = 1, Attributes = attributes },
- new ShoppingCartItem { ProductId = "2", Quantity = 1, Attributes = attributes }
- }
- ));
+ [TestMethod]
+ public async Task ShoppingCartWarningsValidator_Success()
+ {
+ //Arrange
+ var shoppingCartWarningsValidator =
+ new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object);
+
+ _productServiceMock.Setup(x => x.GetProductById(It.IsAny<string>(), false))
+ .Returns(() => Task.FromResult(new Product()));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ };
+ var mapping = new ProductAttributeMapping {
+ Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList,
+ IsRequired = true
+ };
+ mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
+ product.ProductAttributeMappings.Add(mapping);
+
+ var attributes = new List<CustomAttribute> { new() { Key = "1", Value = "1" } };
+
+ //Act
+ var result = await shoppingCartWarningsValidator.ValidateAsync(new ShoppingCartWarningsValidatorRecord(
+ new Customer(),
+ new Store(),
+ new List<ShoppingCartItem> {
+ new() { ProductId = "1", Quantity = 1, Attributes = attributes }
+ }
+ ));
+
+ //Assert
+ Assert.IsTrue(result.IsValid);
+ }
- //Assert
- Assert.IsFalse(result.IsValid);
- }
+ [TestMethod]
+ public async Task ShoppingCartWarningsValidator_Fail()
+ {
+ //Arrange
+ var shoppingCartWarningsValidator =
+ new ShoppingCartWarningsValidator(_translationServiceMock.Object, _productServiceMock.Object);
+
+ _productServiceMock.Setup(x => x.GetProductById("1", false))
+ .Returns(() => Task.FromResult(new Product
+ { IsRecurring = true, RecurringCyclePeriodId = RecurringCyclePeriod.Weeks }));
+ _productServiceMock.Setup(x => x.GetProductById("2", false))
+ .Returns(() => Task.FromResult(new Product { IsRecurring = false }));
+
+ var product = new Product {
+ Id = "1", StockQuantity = 1, OrderMinimumQuantity = 1, OrderMaximumQuantity = 10,
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ };
+ var mapping = new ProductAttributeMapping {
+ Id = "1", ProductAttributeId = "1", AttributeControlTypeId = AttributeControlType.DropdownList,
+ IsRequired = true
+ };
+ mapping.ProductAttributeValues.Add(new ProductAttributeValue { Id = "1", Name = "a" });
+ product.ProductAttributeMappings.Add(mapping);
+
+ var attributes = new List<CustomAttribute> { new() { Key = "1", Value = "1" } };
+
+ //Act
+ var result = await shoppingCartWarningsValidator.ValidateAsync(new ShoppingCartWarningsValidatorRecord(
+ new Customer(),
+ new Store(),
+ new List<ShoppingCartItem> {
+ new() { ProductId = "1", Quantity = 1, Attributes = attributes },
+ new() { ProductId = "2", Quantity = 1, Attributes = attributes }
+ }
+ ));
+
+ //Assert
+ Assert.IsFalse(result.IsValid);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs
index c435ffcff..debb7eaa5 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs
@@ -6,26 +6,25 @@ using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Events
+namespace Grand.Business.Cms.Tests.Events;
+
+[TestClass]
+public class BlogPostDeletedEventHandlerTests
{
- [TestClass()]
- public class BlogPostDeletedEventHandlerTests
- {
- private Mock<ISlugService> _slugServiceMock;
- private BlogPostDeletedEventHandler _handler;
+ private BlogPostDeletedEventHandler _handler;
+ private Mock<ISlugService> _slugServiceMock;
- [TestInitialize()]
- public void Init()
- {
- _slugServiceMock = new Mock<ISlugService>();
- _handler = new BlogPostDeletedEventHandler(_slugServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _slugServiceMock = new Mock<ISlugService>();
+ _handler = new BlogPostDeletedEventHandler(_slugServiceMock.Object);
+ }
- [TestMethod()]
- public async Task Handle_InvokeSlugService()
- {
- await _handler.Handle(new EntityDeleted<BlogPost>(new BlogPost()), default);
- _slugServiceMock.Verify(c => c.DeleteEntityUrl(It.IsAny<EntityUrl>()), Times.Once);
- }
+ [TestMethod]
+ public async Task Handle_InvokeSlugService()
+ {
+ await _handler.Handle(new EntityDeleted<BlogPost>(new BlogPost()), default);
+ _slugServiceMock.Verify(c => c.DeleteEntityUrl(It.IsAny<EntityUrl>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Extensions/BlogExtensionsTests.cs b/src/Tests/Grand.Business.Cms.Tests/Extensions/BlogExtensionsTests.cs
index 5711418cb..5d52aef07 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Extensions/BlogExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Extensions/BlogExtensionsTests.cs
@@ -1,45 +1,44 @@
using Grand.Domain.Blogs;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Cms.Tests.Extensions
+namespace Grand.Business.Cms.Tests.Extensions;
+
+[TestClass]
+public class BlogExtensionsTests
{
- [TestClass()]
- public class BlogExtensionsTests
- {
- private List<BlogPost> _blogPosts;
+ private List<BlogPost> _blogPosts;
- [TestInitialize()]
- public void Init()
- {
- _blogPosts = [
- new BlogPost { StartDateUtc = DateTime.Now.AddDays(4), Id = "5" },
- new BlogPost { StartDateUtc = DateTime.Now.AddDays(3), Id = "4" },
- new BlogPost { StartDateUtc = DateTime.Now.AddDays(2), Id = "3" },
- new BlogPost { StartDateUtc = DateTime.Now.AddDays(1), Id = "2" },
- new BlogPost { StartDateUtc = DateTime.Now, Id = "1" }
- ];
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _blogPosts = [
+ new BlogPost { StartDateUtc = DateTime.Now.AddDays(4), Id = "5" },
+ new BlogPost { StartDateUtc = DateTime.Now.AddDays(3), Id = "4" },
+ new BlogPost { StartDateUtc = DateTime.Now.AddDays(2), Id = "3" },
+ new BlogPost { StartDateUtc = DateTime.Now.AddDays(1), Id = "2" },
+ new BlogPost { StartDateUtc = DateTime.Now, Id = "1" }
+ ];
+ }
- [TestMethod()]
- public void GetPostsByDate_BlogPostContainsInDateRange()
- {
- var from = DateTime.Now;
- var to = DateTime.Now.AddDays(3);
- var result = _blogPosts.GetPostsByDate(from, to);
- Assert.AreEqual(4, result.Count);
- Assert.IsTrue(result.Any(b => b.Id.Equals("1")));
- Assert.IsTrue(result.Any(b => b.Id.Equals("2")));
- Assert.IsTrue(result.Any(b => b.Id.Equals("3")));
- Assert.IsTrue(result.Any(b => b.Id.Equals("4")));
- }
+ [TestMethod]
+ public void GetPostsByDate_BlogPostContainsInDateRange()
+ {
+ var from = DateTime.Now;
+ var to = DateTime.Now.AddDays(3);
+ var result = _blogPosts.GetPostsByDate(from, to);
+ Assert.AreEqual(4, result.Count);
+ Assert.IsTrue(result.Any(b => b.Id.Equals("1")));
+ Assert.IsTrue(result.Any(b => b.Id.Equals("2")));
+ Assert.IsTrue(result.Any(b => b.Id.Equals("3")));
+ Assert.IsTrue(result.Any(b => b.Id.Equals("4")));
+ }
- [TestMethod()]
- public void GetPostsByDate_BlogPostsNotContainsInDateRange_ReturnEmptyList()
- {
- var from = DateTime.Now.AddDays(-3);
- var to = DateTime.Now.AddDays(-1);
- var result = _blogPosts.GetPostsByDate(from, to);
- Assert.AreEqual(0, result.Count);
- }
+ [TestMethod]
+ public void GetPostsByDate_BlogPostsNotContainsInDateRange_ReturnEmptyList()
+ {
+ var from = DateTime.Now.AddDays(-3);
+ var to = DateTime.Now.AddDays(-1);
+ var result = _blogPosts.GetPostsByDate(from, to);
+ Assert.AreEqual(0, result.Count);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/BlogServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/BlogServiceTests.cs
index add76b22c..f6581afe6 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/BlogServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/BlogServiceTests.cs
@@ -1,186 +1,195 @@
using Grand.Business.Cms.Services;
+using Grand.Data;
using Grand.Domain.Blogs;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class BlogServiceTests
{
- [TestClass()]
- public class BlogServiceTests
- {
- private Mock<IRepository<BlogPost>> _blogPostRepositoryMock;
- private Mock<IRepository<BlogComment>> _blogCommentRepositoryMock;
- private Mock<IRepository<BlogCategory>> _blogCategoryRepositoryMock;
- private Mock<IRepository<BlogProduct>> _blogProductRepositoryMock;
- private Mock<IMediator> _mediatorMock;
- private CatalogSettings _settings;
- private BlogService _blogService;
-
- [TestInitialize()]
- public void Init()
- {
- _blogPostRepositoryMock = new Mock<IRepository<BlogPost>>();
- _blogCommentRepositoryMock = new Mock<IRepository<BlogComment>>();
- _blogCategoryRepositoryMock = new Mock<IRepository<BlogCategory>>();
- _blogProductRepositoryMock = new Mock<IRepository<BlogProduct>>();
- _mediatorMock = new Mock<IMediator>();
- _settings = new CatalogSettings();
- _blogService = new BlogService(_blogPostRepositoryMock.Object, _blogCommentRepositoryMock.Object,
- _blogCategoryRepositoryMock.Object, _blogProductRepositoryMock.Object, _mediatorMock.Object, new AccessControlConfig());
- }
-
- [TestMethod()]
- public void DeleteBlogPost_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.DeleteBlogPost(null), "blogPost");
- }
-
- [TestMethod()]
- public async Task DeleteBlogPost_ValidArgument()
- {
- await _blogService.DeleteBlogPost(new BlogPost());
- _blogPostRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogPost>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogPost>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public async Task GetBlogPostById()
- {
- await _blogService.GetBlogPostById("id");
- _blogPostRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- }
-
- [TestMethod()]
- public void InsertBlogPost_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.InsertBlogPost(null), "blogPost");
- }
-
- [TestMethod()]
- public async Task InsertBlogPost_ValiArgument__InvokeRepository()
- {
- await _blogService.InsertBlogPost(new BlogPost());
- _blogPostRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogPost>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogPost>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public async Task UpdateBlogPost_ValiArgument_InvokeRepository()
- {
- await _blogService.UpdateBlogPost(new BlogPost());
- _blogPostRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<BlogPost>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<BlogPost>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void UpdateBlogPost_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.UpdateBlogPost(null), "blogPost");
- }
-
- [TestMethod()]
- public async Task InsertBlogProduct_ValiArgument__InvokeRepository()
- {
- await _blogService.InsertBlogProduct(new BlogProduct());
- _blogProductRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogProduct>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogProduct>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void InsertBlogProductInsertBlogProduct_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.InsertBlogProduct(null), "blogProduct");
- }
-
- [TestMethod()]
- public async Task UpdateBlogProduct_ValiArgument_InvokeRepository()
- {
- await _blogService.UpdateBlogProduct(new BlogProduct());
- _blogProductRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<BlogProduct>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<BlogProduct>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void UpdateBlogProduct_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.UpdateBlogProduct(null), "blogProduct");
- }
-
- [TestMethod()]
- public async Task DeleteBlogProduct_ValidArgument_InvokeRepository()
- {
- await _blogService.DeleteBlogProduct(new BlogProduct());
- _blogProductRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogProduct>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogProduct>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void DeleteBlogProduct_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.DeleteBlogProduct(null), "blogProduct");
- }
-
- [TestMethod()]
- public async Task InsertBlogCategory_ValiArgument__InvokeRepository()
- {
- await _blogService.InsertBlogCategory(new BlogCategory());
- _blogCategoryRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogCategory>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogCategory>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void InsertBlogCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.InsertBlogCategory(null), "blogCategory");
- }
-
- [TestMethod()]
- public async Task UpdateBlogCategory_ValiArgument_InvokeRepository()
- {
- await _blogService.UpdateBlogCategory(new BlogCategory());
- _blogCategoryRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<BlogCategory>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<BlogCategory>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void UpdateBlogCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.UpdateBlogCategory(null), "blogCategory");
- }
-
- [TestMethod()]
- public async Task DeleteBlogCategory_ValidArgument_InvokeRepository()
- {
- await _blogService.DeleteBlogCategory(new BlogCategory());
- _blogCategoryRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogCategory>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogCategory>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void DeleteBlogCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.DeleteBlogCategory(null), "blogCategory");
- }
-
- [TestMethod()]
- public async Task DeleteBlogComments_ValidArgument_InvokeRepository()
- {
- await _blogService.DeleteBlogComment(new BlogComment());
- _blogCommentRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogComment>()), Times.Once);
- // _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogComment>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public async Task InsertBlogComment_ValiArgument__InvokeRepository()
- {
- await _blogService.InsertBlogComment(new BlogComment());
- _blogCommentRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogComment>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogComment>>(), default(CancellationToken)), Times.Once);
- }
- }
-}
+ private Mock<IRepository<BlogCategory>> _blogCategoryRepositoryMock;
+ private Mock<IRepository<BlogComment>> _blogCommentRepositoryMock;
+ private Mock<IRepository<BlogPost>> _blogPostRepositoryMock;
+ private Mock<IRepository<BlogProduct>> _blogProductRepositoryMock;
+ private BlogService _blogService;
+ private Mock<IMediator> _mediatorMock;
+ private CatalogSettings _settings;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _blogPostRepositoryMock = new Mock<IRepository<BlogPost>>();
+ _blogCommentRepositoryMock = new Mock<IRepository<BlogComment>>();
+ _blogCategoryRepositoryMock = new Mock<IRepository<BlogCategory>>();
+ _blogProductRepositoryMock = new Mock<IRepository<BlogProduct>>();
+ _mediatorMock = new Mock<IMediator>();
+ _settings = new CatalogSettings();
+ _blogService = new BlogService(_blogPostRepositoryMock.Object, _blogCommentRepositoryMock.Object,
+ _blogCategoryRepositoryMock.Object, _blogProductRepositoryMock.Object, _mediatorMock.Object,
+ new AccessControlConfig());
+ }
+
+ [TestMethod]
+ public void DeleteBlogPost_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.DeleteBlogPost(null),
+ "blogPost");
+ }
+
+ [TestMethod]
+ public async Task DeleteBlogPost_ValidArgument()
+ {
+ await _blogService.DeleteBlogPost(new BlogPost());
+ _blogPostRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogPost>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogPost>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task GetBlogPostById()
+ {
+ await _blogService.GetBlogPostById("id");
+ _blogPostRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
+
+ [TestMethod]
+ public void InsertBlogPost_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.InsertBlogPost(null),
+ "blogPost");
+ }
+
+ [TestMethod]
+ public async Task InsertBlogPost_ValiArgument__InvokeRepository()
+ {
+ await _blogService.InsertBlogPost(new BlogPost());
+ _blogPostRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogPost>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogPost>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task UpdateBlogPost_ValiArgument_InvokeRepository()
+ {
+ await _blogService.UpdateBlogPost(new BlogPost());
+ _blogPostRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<BlogPost>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<BlogPost>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void UpdateBlogPost_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.UpdateBlogPost(null),
+ "blogPost");
+ }
+
+ [TestMethod]
+ public async Task InsertBlogProduct_ValiArgument__InvokeRepository()
+ {
+ await _blogService.InsertBlogProduct(new BlogProduct());
+ _blogProductRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogProduct>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogProduct>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void InsertBlogProductInsertBlogProduct_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.InsertBlogProduct(null),
+ "blogProduct");
+ }
+
+ [TestMethod]
+ public async Task UpdateBlogProduct_ValiArgument_InvokeRepository()
+ {
+ await _blogService.UpdateBlogProduct(new BlogProduct());
+ _blogProductRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<BlogProduct>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<BlogProduct>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void UpdateBlogProduct_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.UpdateBlogProduct(null),
+ "blogProduct");
+ }
+
+ [TestMethod]
+ public async Task DeleteBlogProduct_ValidArgument_InvokeRepository()
+ {
+ await _blogService.DeleteBlogProduct(new BlogProduct());
+ _blogProductRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogProduct>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogProduct>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void DeleteBlogProduct_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.DeleteBlogProduct(null),
+ "blogProduct");
+ }
+
+ [TestMethod]
+ public async Task InsertBlogCategory_ValiArgument__InvokeRepository()
+ {
+ await _blogService.InsertBlogCategory(new BlogCategory());
+ _blogCategoryRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogCategory>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogCategory>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void InsertBlogCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.InsertBlogCategory(null),
+ "blogCategory");
+ }
+
+ [TestMethod]
+ public async Task UpdateBlogCategory_ValiArgument_InvokeRepository()
+ {
+ await _blogService.UpdateBlogCategory(new BlogCategory());
+ _blogCategoryRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<BlogCategory>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<BlogCategory>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void UpdateBlogCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.UpdateBlogCategory(null),
+ "blogCategory");
+ }
+
+ [TestMethod]
+ public async Task DeleteBlogCategory_ValidArgument_InvokeRepository()
+ {
+ await _blogService.DeleteBlogCategory(new BlogCategory());
+ _blogCategoryRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogCategory>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogCategory>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void DeleteBlogCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _blogService.DeleteBlogCategory(null),
+ "blogCategory");
+ }
+
+ [TestMethod]
+ public async Task DeleteBlogComments_ValidArgument_InvokeRepository()
+ {
+ await _blogService.DeleteBlogComment(new BlogComment());
+ _blogCommentRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<BlogComment>()), Times.Once);
+ // _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<BlogComment>>(), default(CancellationToken)), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task InsertBlogComment_ValiArgument__InvokeRepository()
+ {
+ await _blogService.InsertBlogComment(new BlogComment());
+ _blogCommentRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<BlogComment>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<BlogComment>>(), default), Times.Once);
+ }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/CookiePreferenceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/CookiePreferenceTests.cs
index cf3a9cafe..2fbd0c613 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/CookiePreferenceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/CookiePreferenceTests.cs
@@ -1,5 +1,5 @@
-using Grand.Business.Core.Interfaces.Cms;
-using Grand.Business.Cms.Services;
+using Grand.Business.Cms.Services;
+using Grand.Business.Core.Interfaces.Cms;
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Domain;
using Grand.Domain.Customers;
@@ -7,49 +7,51 @@ using Grand.Domain.Stores;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class CookiePreferenceTests
{
- [TestClass()]
- public class CookiePreferenceTests
- {
- private Mock<IUserFieldService> _userFieldServiceMock;
- private CookiePreference _cookiePreferences;
+ private CookiePreference _cookiePreferences;
+ private Mock<IUserFieldService> _userFieldServiceMock;
- [TestInitialize()]
- public void Init()
- {
- var cookie1 = new Mock<IConsentCookie>();
- var cookie2 = new Mock<IConsentCookie>();
- cookie1.Setup(c => c.DisplayOrder).Returns(1);
- cookie1.Setup(c => c.SystemName).Returns("cookie1");
- cookie2.Setup(c => c.DisplayOrder).Returns(2);
- cookie2.Setup(c => c.SystemName).Returns("cookie2");
+ [TestInitialize]
+ public void Init()
+ {
+ var cookie1 = new Mock<IConsentCookie>();
+ var cookie2 = new Mock<IConsentCookie>();
+ cookie1.Setup(c => c.DisplayOrder).Returns(1);
+ cookie1.Setup(c => c.SystemName).Returns("cookie1");
+ cookie2.Setup(c => c.DisplayOrder).Returns(2);
+ cookie2.Setup(c => c.SystemName).Returns("cookie2");
- _userFieldServiceMock = new Mock<IUserFieldService>();
- _cookiePreferences = new CookiePreference(_userFieldServiceMock.Object, new List<IConsentCookie> { cookie1.Object, cookie2.Object });
- }
+ _userFieldServiceMock = new Mock<IUserFieldService>();
+ _cookiePreferences = new CookiePreference(_userFieldServiceMock.Object,
+ new List<IConsentCookie> { cookie1.Object, cookie2.Object });
+ }
- [TestMethod()]
- public void GetConsentCookies_ReturnCorectOrder()
- {
- var result = _cookiePreferences.GetConsentCookies();
- Assert.IsTrue(result.First().DisplayOrder == 1);
- Assert.IsTrue(result.Last().DisplayOrder == 2);
- }
+ [TestMethod]
+ public void GetConsentCookies_ReturnCorectOrder()
+ {
+ var result = _cookiePreferences.GetConsentCookies();
+ Assert.IsTrue(result.First().DisplayOrder == 1);
+ Assert.IsTrue(result.Last().DisplayOrder == 2);
+ }
- [TestMethod()]
- public async Task IsEnable_ReturnExpectedValue()
- {
- var dic = new Dictionary<string, bool>();
- dic.Add("cookie1", true);
- dic.Add("cookie2", false);
- _userFieldServiceMock.Setup(c => c.GetFieldsForEntity<Dictionary<string, bool>>(It.IsAny<BaseEntity>(), It.IsAny<string>(), It.IsAny<string>()))
- .Returns(Task.FromResult(dic));
+ [TestMethod]
+ public async Task IsEnable_ReturnExpectedValue()
+ {
+ var dic = new Dictionary<string, bool>();
+ dic.Add("cookie1", true);
+ dic.Add("cookie2", false);
+ _userFieldServiceMock.Setup(c =>
+ c.GetFieldsForEntity<Dictionary<string, bool>>(It.IsAny<BaseEntity>(), It.IsAny<string>(),
+ It.IsAny<string>()))
+ .Returns(Task.FromResult(dic));
- var result1 = await _cookiePreferences.IsEnable(new Customer(), new Store(), "cookie1");
- var result2 = await _cookiePreferences.IsEnable(new Customer(), new Store(), "cookie2");
- Assert.IsTrue(result1.Value);
- Assert.IsFalse(result2.Value);
- }
+ var result1 = await _cookiePreferences.IsEnable(new Customer(), new Store(), "cookie1");
+ var result2 = await _cookiePreferences.IsEnable(new Customer(), new Store(), "cookie2");
+ Assert.IsTrue(result1.Value);
+ Assert.IsFalse(result2.Value);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
index 3c5838ba4..58b9b211d 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/KnowledgebaseServiceTests.cs
@@ -1,8 +1,9 @@
using Grand.Business.Cms.Services;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Knowledgebase;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -11,366 +12,370 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class KnowledgebaseServiceTests
{
- [TestClass()]
- public class KnowledgebaseServiceTests
+ private MemoryCacheBase _cacheBase;
+
+ private KnowledgebaseService _knowledgebaseService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<KnowledgebaseArticle> _repositoryKnowledgebaseArticle;
+ private IRepository<KnowledgebaseArticleComment> _repositoryKnowledgebaseArticleComment;
+
+ private IRepository<KnowledgebaseCategory> _repositoryKnowledgebaseCategory;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
{
+ _repositoryKnowledgebaseCategory = new MongoDBRepositoryTest<KnowledgebaseCategory>();
+ _repositoryKnowledgebaseArticle = new MongoDBRepositoryTest<KnowledgebaseArticle>();
+ _repositoryKnowledgebaseArticleComment = new MongoDBRepositoryTest<KnowledgebaseArticleComment>();
- private KnowledgebaseService _knowledgebaseService;
-
- private IRepository<KnowledgebaseCategory> _repositoryKnowledgebaseCategory;
- private IRepository<KnowledgebaseArticle> _repositoryKnowledgebaseArticle;
- private IRepository<KnowledgebaseArticleComment> _repositoryKnowledgebaseArticleComment;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void Init()
- {
- _repositoryKnowledgebaseCategory = new MongoDBRepositoryTest<KnowledgebaseCategory>();
- _repositoryKnowledgebaseArticle = new MongoDBRepositoryTest<KnowledgebaseArticle>();
- _repositoryKnowledgebaseArticleComment = new MongoDBRepositoryTest<KnowledgebaseArticleComment>();
-
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
-
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _knowledgebaseService = new KnowledgebaseService(_repositoryKnowledgebaseCategory, _repositoryKnowledgebaseArticle, _repositoryKnowledgebaseArticleComment, _mediatorMock.Object,
- _workContextMock.Object, _cacheBase, new AccessControlConfig());
- }
-
- [TestMethod()]
- public async Task DeleteKnowledgebaseCategoryTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory();
- await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
- //Act
- await _knowledgebaseService.DeleteKnowledgebaseCategory(knowledgebaseCategory);
- //Assert
- Assert.IsFalse(_repositoryKnowledgebaseCategory.Table.Any());
-
- }
-
- [TestMethod()]
- public async Task UpdateKnowledgebaseCategoryTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory();
- await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
- //Act
- knowledgebaseCategory.Name = "test";
- await _knowledgebaseService.UpdateKnowledgebaseCategory(knowledgebaseCategory);
- //Assert
- Assert.IsTrue(_repositoryKnowledgebaseCategory.Table.FirstOrDefault(x => x.Id == knowledgebaseCategory.Id).Name == "test");
- }
-
- [TestMethod()]
- public async Task GetKnowledgebaseCategoryTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory();
- await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
- //Act
- var result = await _knowledgebaseService.GetKnowledgebaseCategory(knowledgebaseCategory.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetPublicKnowledgebaseCategoryTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory { Published = true };
- await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
- //Act
- var result = await _knowledgebaseService.GetPublicKnowledgebaseCategory(knowledgebaseCategory.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task InsertKnowledgebaseCategoryTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory();
- //Act
- await _knowledgebaseService.InsertKnowledgebaseCategory(knowledgebaseCategory);
- var result = await _knowledgebaseService.GetKnowledgebaseCategory(knowledgebaseCategory.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetKnowledgebaseCategoriesTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory { Published = true };
- await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
- //Act
- var result = await _knowledgebaseService.GetKnowledgebaseCategories();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetKnowledgebaseArticleTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
- await _repositoryKnowledgebaseArticle.InsertAsync(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetKnowledgebaseArticle(knowledgebaseArticle.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetKnowledgebaseArticlesTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
- await _repositoryKnowledgebaseArticle.InsertAsync(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetKnowledgebaseArticles();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task InsertKnowledgebaseArticleTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
- //Act
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Assert
- Assert.IsTrue(_repositoryKnowledgebaseArticle.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateKnowledgebaseArticleTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- knowledgebaseArticle.Name = "test";
- await _knowledgebaseService.UpdateKnowledgebaseArticle(knowledgebaseArticle);
- //Assert
- Assert.IsTrue(_repositoryKnowledgebaseArticle.Table.FirstOrDefault(x => x.Id == knowledgebaseArticle.Id).Name == "test");
- }
-
- [TestMethod()]
- public async Task DeleteKnowledgebaseArticleTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- await _knowledgebaseService.DeleteKnowledgebaseArticle(knowledgebaseArticle);
- //Assert
- Assert.IsNull(_repositoryKnowledgebaseArticle.Table.FirstOrDefault(x => x.Id == knowledgebaseArticle.Id));
- }
-
- [TestMethod()]
- public async Task GetKnowledgebaseArticlesByCategoryIdTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, ParentCategoryId = "1" };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetKnowledgebaseArticlesByCategoryId("1");
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetPublicKnowledgebaseCategoriesTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory { Published = true };
- await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
- //Act
- var result = await _knowledgebaseService.GetPublicKnowledgebaseCategories();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetPublicKnowledgebaseArticlesTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetPublicKnowledgebaseArticles();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetPublicKnowledgebaseArticleTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetPublicKnowledgebaseArticle(knowledgebaseArticle.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetPublicKnowledgebaseArticlesByCategoryTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, ParentCategoryId = "1" };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetPublicKnowledgebaseArticlesByCategory(knowledgebaseArticle.ParentCategoryId);
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetPublicKnowledgebaseArticlesByKeywordTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test" };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetPublicKnowledgebaseArticlesByKeyword("test");
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetPublicKnowledgebaseCategoriesByKeywordTest()
- {
- //Arrange
- var knowledgebaseCategory = new KnowledgebaseCategory { Published = true, Name = "test" };
- await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
- //Act
- var result = await _knowledgebaseService.GetPublicKnowledgebaseCategoriesByKeyword("test");
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetHomepageKnowledgebaseArticlesTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test", ShowOnHomepage = true };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetHomepageKnowledgebaseArticles();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetKnowledgebaseArticlesByNameTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test", ShowOnHomepage = true };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- //Act
- var result = await _knowledgebaseService.GetKnowledgebaseArticlesByName(knowledgebaseArticle.Name);
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetRelatedKnowledgebaseArticlesTest()
- {
- //Arrange
- var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test", ShowOnHomepage = true };
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
- var knowledgebaseArticle1 = new KnowledgebaseArticle();
- knowledgebaseArticle1.RelatedArticles.Add(knowledgebaseArticle.Id);
- await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle1);
- //Act
- var result = await _knowledgebaseService.GetRelatedKnowledgebaseArticles(knowledgebaseArticle1.Id);
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task InsertArticleCommentTest()
- {
- //Arrange
- var knowledgebaseArticleComment = new KnowledgebaseArticleComment();
- //Act
- await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
- //Assert
- Assert.IsTrue(_repositoryKnowledgebaseArticleComment.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetAllCommentsTest()
- {
- //Arrange
- var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
- await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
- //Act
- var result = await _knowledgebaseService.GetAllComments("1");
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task GetArticleCommentByIdTest()
- {
- //Arrange
- var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
- await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
- //Act
- var result = await _knowledgebaseService.GetArticleCommentById(knowledgebaseArticleComment.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetArticleCommentsByIdsTest()
- {
- //Arrange
- var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
- await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
- //Act
- var result = await _knowledgebaseService.GetArticleCommentsByIds([knowledgebaseArticleComment.Id]);
- //Assert
- Assert.IsTrue(result.Any());
-
- }
-
- [TestMethod()]
- public async Task GetArticleCommentsByArticleIdTest()
- {
- //Arrange
- var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1", ArticleId = "1" };
- await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
- //Act
- var result = await _knowledgebaseService.GetArticleCommentsByArticleId(knowledgebaseArticleComment.ArticleId);
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task DeleteArticleCommentTest()
- {
- //Arrange
- var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
- await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
- //Act
- await _knowledgebaseService.DeleteArticleComment(knowledgebaseArticleComment);
- //Assert
- Assert.IsNull(_repositoryKnowledgebaseArticleComment.Table.FirstOrDefault(x=>x.Id == knowledgebaseArticleComment.Id));
- }
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
+
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _knowledgebaseService = new KnowledgebaseService(_repositoryKnowledgebaseCategory,
+ _repositoryKnowledgebaseArticle, _repositoryKnowledgebaseArticleComment, _mediatorMock.Object,
+ _workContextMock.Object, _cacheBase, new AccessControlConfig());
+ }
+
+ [TestMethod]
+ public async Task DeleteKnowledgebaseCategoryTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory();
+ await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
+ //Act
+ await _knowledgebaseService.DeleteKnowledgebaseCategory(knowledgebaseCategory);
+ //Assert
+ Assert.IsFalse(_repositoryKnowledgebaseCategory.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateKnowledgebaseCategoryTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory();
+ await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
+ //Act
+ knowledgebaseCategory.Name = "test";
+ await _knowledgebaseService.UpdateKnowledgebaseCategory(knowledgebaseCategory);
+ //Assert
+ Assert.IsTrue(
+ _repositoryKnowledgebaseCategory.Table.FirstOrDefault(x => x.Id == knowledgebaseCategory.Id).Name ==
+ "test");
+ }
+
+ [TestMethod]
+ public async Task GetKnowledgebaseCategoryTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory();
+ await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
+ //Act
+ var result = await _knowledgebaseService.GetKnowledgebaseCategory(knowledgebaseCategory.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseCategoryTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory { Published = true };
+ await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
+ //Act
+ var result = await _knowledgebaseService.GetPublicKnowledgebaseCategory(knowledgebaseCategory.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task InsertKnowledgebaseCategoryTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory();
+ //Act
+ await _knowledgebaseService.InsertKnowledgebaseCategory(knowledgebaseCategory);
+ var result = await _knowledgebaseService.GetKnowledgebaseCategory(knowledgebaseCategory.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetKnowledgebaseCategoriesTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory { Published = true };
+ await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
+ //Act
+ var result = await _knowledgebaseService.GetKnowledgebaseCategories();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetKnowledgebaseArticleTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
+ await _repositoryKnowledgebaseArticle.InsertAsync(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetKnowledgebaseArticle(knowledgebaseArticle.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetKnowledgebaseArticlesTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
+ await _repositoryKnowledgebaseArticle.InsertAsync(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetKnowledgebaseArticles();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertKnowledgebaseArticleTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
+ //Act
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Assert
+ Assert.IsTrue(_repositoryKnowledgebaseArticle.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateKnowledgebaseArticleTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ knowledgebaseArticle.Name = "test";
+ await _knowledgebaseService.UpdateKnowledgebaseArticle(knowledgebaseArticle);
+ //Assert
+ Assert.IsTrue(_repositoryKnowledgebaseArticle.Table.FirstOrDefault(x => x.Id == knowledgebaseArticle.Id).Name ==
+ "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteKnowledgebaseArticleTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ await _knowledgebaseService.DeleteKnowledgebaseArticle(knowledgebaseArticle);
+ //Assert
+ Assert.IsNull(_repositoryKnowledgebaseArticle.Table.FirstOrDefault(x => x.Id == knowledgebaseArticle.Id));
+ }
+
+ [TestMethod]
+ public async Task GetKnowledgebaseArticlesByCategoryIdTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, ParentCategoryId = "1" };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetKnowledgebaseArticlesByCategoryId("1");
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseCategoriesTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory { Published = true };
+ await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
+ //Act
+ var result = await _knowledgebaseService.GetPublicKnowledgebaseCategories();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseArticlesTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetPublicKnowledgebaseArticles();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseArticleTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetPublicKnowledgebaseArticle(knowledgebaseArticle.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseArticlesByCategoryTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, ParentCategoryId = "1" };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ var result =
+ await _knowledgebaseService.GetPublicKnowledgebaseArticlesByCategory(knowledgebaseArticle.ParentCategoryId);
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseArticlesByKeywordTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test" };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetPublicKnowledgebaseArticlesByKeyword("test");
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetPublicKnowledgebaseCategoriesByKeywordTest()
+ {
+ //Arrange
+ var knowledgebaseCategory = new KnowledgebaseCategory { Published = true, Name = "test" };
+ await _repositoryKnowledgebaseCategory.InsertAsync(knowledgebaseCategory);
+ //Act
+ var result = await _knowledgebaseService.GetPublicKnowledgebaseCategoriesByKeyword("test");
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetHomepageKnowledgebaseArticlesTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test", ShowOnHomepage = true };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetHomepageKnowledgebaseArticles();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetKnowledgebaseArticlesByNameTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test", ShowOnHomepage = true };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ //Act
+ var result = await _knowledgebaseService.GetKnowledgebaseArticlesByName(knowledgebaseArticle.Name);
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetRelatedKnowledgebaseArticlesTest()
+ {
+ //Arrange
+ var knowledgebaseArticle = new KnowledgebaseArticle { Published = true, Name = "test", ShowOnHomepage = true };
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle);
+ var knowledgebaseArticle1 = new KnowledgebaseArticle();
+ knowledgebaseArticle1.RelatedArticles.Add(knowledgebaseArticle.Id);
+ await _knowledgebaseService.InsertKnowledgebaseArticle(knowledgebaseArticle1);
+ //Act
+ var result = await _knowledgebaseService.GetRelatedKnowledgebaseArticles(knowledgebaseArticle1.Id);
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertArticleCommentTest()
+ {
+ //Arrange
+ var knowledgebaseArticleComment = new KnowledgebaseArticleComment();
+ //Act
+ await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
+ //Assert
+ Assert.IsTrue(_repositoryKnowledgebaseArticleComment.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task GetAllCommentsTest()
+ {
+ //Arrange
+ var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
+ await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
+ //Act
+ var result = await _knowledgebaseService.GetAllComments("1");
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetArticleCommentByIdTest()
+ {
+ //Arrange
+ var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
+ await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
+ //Act
+ var result = await _knowledgebaseService.GetArticleCommentById(knowledgebaseArticleComment.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetArticleCommentsByIdsTest()
+ {
+ //Arrange
+ var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
+ await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
+ //Act
+ var result = await _knowledgebaseService.GetArticleCommentsByIds([knowledgebaseArticleComment.Id]);
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task GetArticleCommentsByArticleIdTest()
+ {
+ //Arrange
+ var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1", ArticleId = "1" };
+ await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
+ //Act
+ var result = await _knowledgebaseService.GetArticleCommentsByArticleId(knowledgebaseArticleComment.ArticleId);
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task DeleteArticleCommentTest()
+ {
+ //Arrange
+ var knowledgebaseArticleComment = new KnowledgebaseArticleComment { CustomerId = "1" };
+ await _knowledgebaseService.InsertArticleComment(knowledgebaseArticleComment);
+ //Act
+ await _knowledgebaseService.DeleteArticleComment(knowledgebaseArticleComment);
+ //Assert
+ Assert.IsNull(
+ _repositoryKnowledgebaseArticleComment.Table.FirstOrDefault(x => x.Id == knowledgebaseArticleComment.Id));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs
index f52dc831e..206d28c71 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/NewsServiceTests.cs
@@ -1,110 +1,111 @@
using Grand.Business.Cms.Services;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.News;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class NewsServiceTests
{
- [TestClass()]
- public class NewsServiceTests
- {
- private NewsService _newsService;
+ private Mock<IMediator> _mediatorMock;
+ private NewsService _newsService;
- private IRepository<NewsItem> _repository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
+ private IRepository<NewsItem> _repository;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<NewsItem>();
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<NewsItem>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _newsService = new NewsService(_repository, _mediatorMock.Object, _workContextMock.Object, new AccessControlConfig());
- }
+ _newsService = new NewsService(_repository, _mediatorMock.Object, _workContextMock.Object,
+ new AccessControlConfig());
+ }
- [TestMethod()]
- public async Task GetNewsByIdTest()
- {
- //Arrange
- var newsItem = new NewsItem();
- await _repository.InsertAsync(newsItem);
- //Act
- var result = await _newsService.GetNewsById(newsItem.Id);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetNewsByIdTest()
+ {
+ //Arrange
+ var newsItem = new NewsItem();
+ await _repository.InsertAsync(newsItem);
+ //Act
+ var result = await _newsService.GetNewsById(newsItem.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task GetAllNewsTest()
- {
- //Arrange
- var newsItem = new NewsItem { Published = true };
- await _repository.InsertAsync(newsItem);
- //Act
- var result = await _newsService.GetAllNews();
- //Assert
- Assert.IsTrue(result.Any());
- }
+ [TestMethod]
+ public async Task GetAllNewsTest()
+ {
+ //Arrange
+ var newsItem = new NewsItem { Published = true };
+ await _repository.InsertAsync(newsItem);
+ //Act
+ var result = await _newsService.GetAllNews();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
- [TestMethod()]
- public async Task InsertNewsTest()
- {
- //Arrange
- var newsItem = new NewsItem();
- //Act
- await _newsService.InsertNews(newsItem);
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == newsItem.Id));
- }
+ [TestMethod]
+ public async Task InsertNewsTest()
+ {
+ //Arrange
+ var newsItem = new NewsItem();
+ //Act
+ await _newsService.InsertNews(newsItem);
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == newsItem.Id));
+ }
- [TestMethod()]
- public async Task UpdateNewsTest()
- {
- //Arrange
- var newsItem = new NewsItem { Published = true };
- await _repository.InsertAsync(newsItem);
- //Act
- newsItem.Title = "test";
- await _newsService.UpdateNews(newsItem);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == newsItem.Id).Title == "test");
- }
+ [TestMethod]
+ public async Task UpdateNewsTest()
+ {
+ //Arrange
+ var newsItem = new NewsItem { Published = true };
+ await _repository.InsertAsync(newsItem);
+ //Act
+ newsItem.Title = "test";
+ await _newsService.UpdateNews(newsItem);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == newsItem.Id).Title == "test");
+ }
- [TestMethod()]
- public async Task DeleteNewsTest()
- {
- //Arrange
- var newsItem = new NewsItem { Published = true };
- await _repository.InsertAsync(newsItem);
- //Act
- await _newsService.DeleteNews(newsItem);
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == newsItem.Id));
- }
+ [TestMethod]
+ public async Task DeleteNewsTest()
+ {
+ //Arrange
+ var newsItem = new NewsItem { Published = true };
+ await _repository.InsertAsync(newsItem);
+ //Act
+ await _newsService.DeleteNews(newsItem);
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == newsItem.Id));
+ }
- [TestMethod()]
- public async Task GetAllCommentsTest()
- {
- //Arrange
- var newsItem = new NewsItem { Published = true };
- newsItem.NewsComments.Add(new NewsComment { CustomerId = "1" });
- await _repository.InsertAsync(newsItem);
- //Act
- var result = await _newsService.GetAllComments("1");
- //Assert
- Assert.IsTrue(result.Any());
- }
+ [TestMethod]
+ public async Task GetAllCommentsTest()
+ {
+ //Arrange
+ var newsItem = new NewsItem { Published = true };
+ newsItem.NewsComments.Add(new NewsComment { CustomerId = "1" });
+ await _repository.InsertAsync(newsItem);
+ //Act
+ var result = await _newsService.GetAllComments("1");
+ //Assert
+ Assert.IsTrue(result.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/PageLayoutServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/PageLayoutServiceTests.cs
index c15a5cccb..414f3fa59 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/PageLayoutServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/PageLayoutServiceTests.cs
@@ -1,8 +1,9 @@
using Grand.Business.Cms.Services;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Pages;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -11,92 +12,92 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class PageLayoutServiceTests
{
- [TestClass()]
- public class PageLayoutServiceTests
- {
- private PageLayoutService _pageLayoutService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private PageLayoutService _pageLayoutService;
- private IRepository<PageLayout> _repository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
+ private IRepository<PageLayout> _repository;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<PageLayout>();
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<PageLayout>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _pageLayoutService = new PageLayoutService(_repository, _cacheBase, _mediatorMock.Object);
- }
+ _pageLayoutService = new PageLayoutService(_repository, _cacheBase, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task GetAllPageLayoutsTest()
- {
- //Arrange
- var pageLayout = new PageLayout { };
- await _repository.InsertAsync(pageLayout);
- //Act
- var result = await _pageLayoutService.GetAllPageLayouts();
- //Assert
- Assert.IsTrue(result.Any());
- }
+ [TestMethod]
+ public async Task GetAllPageLayoutsTest()
+ {
+ //Arrange
+ var pageLayout = new PageLayout();
+ await _repository.InsertAsync(pageLayout);
+ //Act
+ var result = await _pageLayoutService.GetAllPageLayouts();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
- [TestMethod()]
- public async Task GetPageLayoutByIdTest()
- {
- //Arrange
- var pageLayout = new PageLayout { };
- await _repository.InsertAsync(pageLayout);
- //Act
- var result = await _pageLayoutService.GetPageLayoutById(pageLayout.Id);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetPageLayoutByIdTest()
+ {
+ //Arrange
+ var pageLayout = new PageLayout();
+ await _repository.InsertAsync(pageLayout);
+ //Act
+ var result = await _pageLayoutService.GetPageLayoutById(pageLayout.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task InsertPageLayoutTest()
- {
- //Arrange
- var pageLayout = new PageLayout { };
- //Act
- await _pageLayoutService.InsertPageLayout(pageLayout);
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == pageLayout.Id));
- }
+ [TestMethod]
+ public async Task InsertPageLayoutTest()
+ {
+ //Arrange
+ var pageLayout = new PageLayout();
+ //Act
+ await _pageLayoutService.InsertPageLayout(pageLayout);
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == pageLayout.Id));
+ }
- [TestMethod()]
- public async Task UpdatePageLayoutTest()
- {
- //Arrange
- var pageLayout = new PageLayout { };
- await _pageLayoutService.InsertPageLayout(pageLayout);
- //Act
- pageLayout.Name = "test";
- await _pageLayoutService.UpdatePageLayout(pageLayout);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == pageLayout.Id).Name == "test");
- }
+ [TestMethod]
+ public async Task UpdatePageLayoutTest()
+ {
+ //Arrange
+ var pageLayout = new PageLayout();
+ await _pageLayoutService.InsertPageLayout(pageLayout);
+ //Act
+ pageLayout.Name = "test";
+ await _pageLayoutService.UpdatePageLayout(pageLayout);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == pageLayout.Id).Name == "test");
+ }
- [TestMethod()]
- public async Task DeletePageLayoutTest()
- {
- //Arrange
- var pageLayout = new PageLayout { };
- await _pageLayoutService.InsertPageLayout(pageLayout);
- //Act
- await _pageLayoutService.DeletePageLayout(pageLayout);
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == pageLayout.Id));
- }
+ [TestMethod]
+ public async Task DeletePageLayoutTest()
+ {
+ //Arrange
+ var pageLayout = new PageLayout();
+ await _pageLayoutService.InsertPageLayout(pageLayout);
+ //Act
+ await _pageLayoutService.DeletePageLayout(pageLayout);
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == pageLayout.Id));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs
index 7926c2132..db97141f2 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/PageServiceTests.cs
@@ -1,10 +1,11 @@
using Grand.Business.Cms.Services;
using Grand.Business.Common.Services.Security;
using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Pages;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -13,107 +14,108 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class PageServiceTests
{
- [TestClass()]
- public class PageServiceTests
- {
- private PageService _pageService;
+ private IAclService _aclService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private PageService _pageService;
- private IRepository<Page> _repository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
- private IAclService _aclService;
+ private IRepository<Page> _repository;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Page>();
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Page>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _aclService = new AclService(new AccessControlConfig());
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _aclService = new AclService(new AccessControlConfig());
- _pageService = new PageService(_repository, _workContextMock.Object, _aclService, _mediatorMock.Object, _cacheBase, new AccessControlConfig());
- }
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- [TestMethod()]
- public async Task GetPageByIdTest()
- {
- //Arrange
- var page = new Page { };
- await _repository.InsertAsync(page);
- //Act
- var result = await _pageService.GetPageById(page.Id);
- //Assert
- Assert.IsNotNull(result);
- }
+ _pageService = new PageService(_repository, _workContextMock.Object, _aclService, _mediatorMock.Object,
+ _cacheBase, new AccessControlConfig());
+ }
+
+ [TestMethod]
+ public async Task GetPageByIdTest()
+ {
+ //Arrange
+ var page = new Page();
+ await _repository.InsertAsync(page);
+ //Act
+ var result = await _pageService.GetPageById(page.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task GetPageBySystemNameTest()
- {
- //Arrange
- var page = new Page { SystemName = "test" };
- await _repository.InsertAsync(page);
- //Act
- var result = await _pageService.GetPageBySystemName(page.SystemName);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetPageBySystemNameTest()
+ {
+ //Arrange
+ var page = new Page { SystemName = "test" };
+ await _repository.InsertAsync(page);
+ //Act
+ var result = await _pageService.GetPageBySystemName(page.SystemName);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task GetAllPagesTest()
- {
- //Arrange
- var page = new Page { SystemName = "test", Published = true };
- await _repository.InsertAsync(page);
- //Act
- var result = await _pageService.GetAllPages("");
- //Assert
- Assert.IsTrue(result.Any());
- }
+ [TestMethod]
+ public async Task GetAllPagesTest()
+ {
+ //Arrange
+ var page = new Page { SystemName = "test", Published = true };
+ await _repository.InsertAsync(page);
+ //Act
+ var result = await _pageService.GetAllPages("");
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
- [TestMethod()]
- public async Task InsertPageTest()
- {
- //Arrange
- var page = new Page { };
- //Act
- await _pageService.InsertPage(page);
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == page.Id));
- }
+ [TestMethod]
+ public async Task InsertPageTest()
+ {
+ //Arrange
+ var page = new Page();
+ //Act
+ await _pageService.InsertPage(page);
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == page.Id));
+ }
- [TestMethod()]
- public async Task UpdatePageTest()
- {
- //Arrange
- var page = new Page { };
- await _pageService.InsertPage(page);
- //Act
- page.SystemName = "test";
- await _pageService.UpdatePage(page);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == page.Id).SystemName == "test");
- }
+ [TestMethod]
+ public async Task UpdatePageTest()
+ {
+ //Arrange
+ var page = new Page();
+ await _pageService.InsertPage(page);
+ //Act
+ page.SystemName = "test";
+ await _pageService.UpdatePage(page);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == page.Id).SystemName == "test");
+ }
- [TestMethod()]
- public async Task DeletePageTest()
- {
- //Arrange
- var page = new Page { };
- await _pageService.InsertPage(page);
- //Act
- await _pageService.DeletePage(page);
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == page.Id));
- }
+ [TestMethod]
+ public async Task DeletePageTest()
+ {
+ //Arrange
+ var page = new Page();
+ await _pageService.InsertPage(page);
+ //Act
+ await _pageService.DeletePage(page);
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == page.Id));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/RobotsTxtServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/RobotsTxtServiceTests.cs
index 5d743864b..2ff1bd6cf 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/RobotsTxtServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/RobotsTxtServiceTests.cs
@@ -1,8 +1,9 @@
using Grand.Business.Cms.Services;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Common;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -11,80 +12,80 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class RobotsTxtServiceTests
{
- [TestClass()]
- public class RobotsTxtServiceTests
- {
- private RobotsTxtService _robotsTxtService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
- private IRepository<RobotsTxt> _repository;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
+ private IRepository<RobotsTxt> _repository;
+ private RobotsTxtService _robotsTxtService;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<RobotsTxt>();
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<RobotsTxt>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "", Name = "test store" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "", Name = "test store" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _robotsTxtService = new RobotsTxtService(_repository, _mediatorMock.Object, _cacheBase);
- }
+ _robotsTxtService = new RobotsTxtService(_repository, _mediatorMock.Object, _cacheBase);
+ }
- [TestMethod()]
- public async Task GetRobotsTxtTest()
- {
- //Arrange
- var robotsTxt = new RobotsTxt { StoreId = "1" };
- await _repository.InsertAsync(robotsTxt);
- //Act
- var result = await _robotsTxtService.GetRobotsTxt(robotsTxt.StoreId);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetRobotsTxtTest()
+ {
+ //Arrange
+ var robotsTxt = new RobotsTxt { StoreId = "1" };
+ await _repository.InsertAsync(robotsTxt);
+ //Act
+ var result = await _robotsTxtService.GetRobotsTxt(robotsTxt.StoreId);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task InsertRobotsTxtTest()
- {
- //Arrange
- var robotsTxt = new RobotsTxt { StoreId = "1" };
- //Act
- await _robotsTxtService.InsertRobotsTxt(robotsTxt);
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == robotsTxt.Id));
- }
+ [TestMethod]
+ public async Task InsertRobotsTxtTest()
+ {
+ //Arrange
+ var robotsTxt = new RobotsTxt { StoreId = "1" };
+ //Act
+ await _robotsTxtService.InsertRobotsTxt(robotsTxt);
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == robotsTxt.Id));
+ }
- [TestMethod()]
- public async Task UpdateRobotsTxtTest()
- {
- //Arrange
- var robotsTxt = new RobotsTxt { StoreId = "1" };
- await _robotsTxtService.InsertRobotsTxt(robotsTxt);
- //Act
- robotsTxt.Text = "test";
- await _robotsTxtService.UpdateRobotsTxt(robotsTxt);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == robotsTxt.Id).Text == "test");
- }
+ [TestMethod]
+ public async Task UpdateRobotsTxtTest()
+ {
+ //Arrange
+ var robotsTxt = new RobotsTxt { StoreId = "1" };
+ await _robotsTxtService.InsertRobotsTxt(robotsTxt);
+ //Act
+ robotsTxt.Text = "test";
+ await _robotsTxtService.UpdateRobotsTxt(robotsTxt);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == robotsTxt.Id).Text == "test");
+ }
- [TestMethod()]
- public async Task DeleteRobotsTxtTest()
- {
- //Arrange
- var robotsTxt = new RobotsTxt { StoreId = "1" };
- await _robotsTxtService.InsertRobotsTxt(robotsTxt);
- //Act
- await _robotsTxtService.DeleteRobotsTxt(robotsTxt);
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == robotsTxt.Id));
- }
+ [TestMethod]
+ public async Task DeleteRobotsTxtTest()
+ {
+ //Arrange
+ var robotsTxt = new RobotsTxt { StoreId = "1" };
+ await _robotsTxtService.InsertRobotsTxt(robotsTxt);
+ //Act
+ await _robotsTxtService.DeleteRobotsTxt(robotsTxt);
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == robotsTxt.Id));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Services/WidgetServiceTests.cs b/src/Tests/Grand.Business.Cms.Tests/Services/WidgetServiceTests.cs
index 7e8b0609a..4c0172440 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Services/WidgetServiceTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Services/WidgetServiceTests.cs
@@ -1,69 +1,68 @@
-using Grand.Business.Core.Interfaces.Cms;
-using Grand.Business.Cms.Services;
+using Grand.Business.Cms.Services;
+using Grand.Business.Core.Interfaces.Cms;
using Grand.Domain.Cms;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Cms.Tests.Services
+namespace Grand.Business.Cms.Tests.Services;
+
+[TestClass]
+public class WidgetServiceTests
{
- [TestClass()]
- public class WidgetServiceTests
- {
- private WidgetSettings _settings;
- private IWidgetService _widgedService;
- private Mock<IWidgetProvider> _widgetProvider1;
- private Mock<IWidgetProvider> _widgetProvider2;
+ private WidgetSettings _settings;
+ private IWidgetService _widgedService;
+ private Mock<IWidgetProvider> _widgetProvider1;
+ private Mock<IWidgetProvider> _widgetProvider2;
- [TestInitialize()]
- public void Init()
- {
- _widgetProvider1 = new Mock<IWidgetProvider>();
- _widgetProvider1.Setup(c => c.SystemName).Returns("name1");
- _widgetProvider1.Setup(c => c.GetWidgetZones().Result).Returns(new List<string> { "widgetzone1" });
- _widgetProvider2 = new Mock<IWidgetProvider>();
- _widgetProvider2.Setup(c => c.SystemName).Returns("name2");
- _widgetProvider2.Setup(c => c.GetWidgetZones().Result).Returns(new List<string> { "widgetzone2" });
- var providers = new List<IWidgetProvider> { _widgetProvider1.Object, _widgetProvider2.Object };
- _settings = new WidgetSettings();
- _widgedService = new WidgetService(providers, _settings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _widgetProvider1 = new Mock<IWidgetProvider>();
+ _widgetProvider1.Setup(c => c.SystemName).Returns("name1");
+ _widgetProvider1.Setup(c => c.GetWidgetZones().Result).Returns(new List<string> { "widgetzone1" });
+ _widgetProvider2 = new Mock<IWidgetProvider>();
+ _widgetProvider2.Setup(c => c.SystemName).Returns("name2");
+ _widgetProvider2.Setup(c => c.GetWidgetZones().Result).Returns(new List<string> { "widgetzone2" });
+ var providers = new List<IWidgetProvider> { _widgetProvider1.Object, _widgetProvider2.Object };
+ _settings = new WidgetSettings();
+ _widgedService = new WidgetService(providers, _settings);
+ }
- [TestMethod()]
- public void LoadActiveWidgets_SettingsNotContainsSystemName_ReturnEmptyList()
- {
- _settings.ActiveWidgetSystemNames = [];
- var result = _widgedService.LoadActiveWidgets();
- Assert.IsTrue(result.Count == 0);
- }
+ [TestMethod]
+ public void LoadActiveWidgets_SettingsNotContainsSystemName_ReturnEmptyList()
+ {
+ _settings.ActiveWidgetSystemNames = [];
+ var result = _widgedService.LoadActiveWidgets();
+ Assert.IsTrue(result.Count == 0);
+ }
- [TestMethod()]
- public void LoadActiveWidgets_SettingsContainsSystemName_ReturnList()
- {
- _settings.ActiveWidgetSystemNames = ["name1", "name2"];
- var result = _widgedService.LoadActiveWidgets();
- Assert.IsTrue(result.Count == _settings.ActiveWidgetSystemNames.Count);
- }
+ [TestMethod]
+ public void LoadActiveWidgets_SettingsContainsSystemName_ReturnList()
+ {
+ _settings.ActiveWidgetSystemNames = ["name1", "name2"];
+ var result = _widgedService.LoadActiveWidgets();
+ Assert.IsTrue(result.Count == _settings.ActiveWidgetSystemNames.Count);
+ }
- [TestMethod()]
- public async Task LoadActiveWidgetsByWidgetZone_EmptyWidgetZone_ReturnEmptyList()
- {
- var result = await _widgedService.LoadActiveWidgetsByWidgetZone("");
- Assert.IsTrue(result.Count == 0);
- }
+ [TestMethod]
+ public async Task LoadActiveWidgetsByWidgetZone_EmptyWidgetZone_ReturnEmptyList()
+ {
+ var result = await _widgedService.LoadActiveWidgetsByWidgetZone("");
+ Assert.IsTrue(result.Count == 0);
+ }
- [TestMethod()]
- public async Task LoadActiveWidgetsByWidgetZone()
- {
- _settings.ActiveWidgetSystemNames = ["name1", "name2"];
- var result = await _widgedService.LoadActiveWidgetsByWidgetZone("widgetZone1");
- Assert.IsTrue(result.Count == 1);
- }
+ [TestMethod]
+ public async Task LoadActiveWidgetsByWidgetZone()
+ {
+ _settings.ActiveWidgetSystemNames = ["name1", "name2"];
+ var result = await _widgedService.LoadActiveWidgetsByWidgetZone("widgetZone1");
+ Assert.IsTrue(result.Count == 1);
+ }
- [TestMethod()]
- public void LoadWidgetBySystemName_ReturnExpectedValue()
- {
- var result = _widgedService.LoadWidgetBySystemName("name1");
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public void LoadWidgetBySystemName_ReturnExpectedValue()
+ {
+ var result = _widgedService.LoadWidgetBySystemName("name1");
+ Assert.IsNotNull(result);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Cms.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Cms.Tests/Startup/StartupApplicationTests.cs
index d09fa4f9f..1f4a87f3b 100644
--- a/src/Tests/Grand.Business.Cms.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Cms.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Cms.Tests.Startup
+namespace Grand.Business.Cms.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Events/GroupDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Common.Tests/Events/GroupDeletedEventHandlerTests.cs
index 97cafdf62..e01969c9e 100644
--- a/src/Tests/Grand.Business.Common.Tests/Events/GroupDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Events/GroupDeletedEventHandlerTests.cs
@@ -1,56 +1,58 @@
using Grand.Business.Common.Events;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
+using Grand.Infrastructure.Events;
using Grand.Infrastructure.Tests.Caching;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Events
+namespace Grand.Business.Common.Tests.Events;
+
+[TestClass]
+public class GroupDeletedEventHandlerTests
{
- [TestClass()]
- public class GroupDeletedEventHandlerTests
- {
+ private MemoryCacheBase _cacheBase;
+ private GroupDeletedEventHandler _handler;
+ private IRepository<Product> _product;
- private IRepository<Customer> _repository;
- private IRepository<Product> _product;
- private GroupDeletedEventHandler _handler;
- private MemoryCacheBase _cacheBase;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Customer>();
- _product = new MongoDBRepositoryTest<Product>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), new Mock<IMediator>().Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
+ private IRepository<Customer> _repository;
- _handler = new GroupDeletedEventHandler(_repository, _product, _cacheBase);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Customer>();
+ _product = new MongoDBRepositoryTest<Product>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), new Mock<IMediator>().Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _handler = new GroupDeletedEventHandler(_repository, _product, _cacheBase);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var customer1 = new Customer();
- customer1.Groups.Add("1");
- customer1.Groups.Add("2");
- customer1.Groups.Add("3");
- await _repository.InsertAsync(customer1);
- var customer2 = new Customer();
- customer2.Groups.Add("1");
- customer2.Groups.Add("2");
- customer2.Groups.Add("3");
- await _repository.InsertAsync(customer2);
- //Act
- var notification = new Infrastructure.Events.EntityDeleted<CustomerGroup>(new CustomerGroup { Id = "1" });
- await _handler.Handle(notification, CancellationToken.None);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var customer1 = new Customer();
+ customer1.Groups.Add("1");
+ customer1.Groups.Add("2");
+ customer1.Groups.Add("3");
+ await _repository.InsertAsync(customer1);
+ var customer2 = new Customer();
+ customer2.Groups.Add("1");
+ customer2.Groups.Add("2");
+ customer2.Groups.Add("3");
+ await _repository.InsertAsync(customer2);
+ //Act
+ var notification = new EntityDeleted<CustomerGroup>(new CustomerGroup { Id = "1" });
+ await _handler.Handle(notification, CancellationToken.None);
- //Assert
- var count = _repository.Table.Where(x => x.Groups.Contains("1")).Count();
- Assert.AreEqual(0, count);
- }
+ //Assert
+ var count = _repository.Table.Where(x => x.Groups.Contains("1")).Count();
+ Assert.AreEqual(0, count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Events/LanguageDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Common.Tests/Events/LanguageDeletedEventHandlerTests.cs
index 45107d10f..a02d01098 100644
--- a/src/Tests/Grand.Business.Common.Tests/Events/LanguageDeletedEventHandlerTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Events/LanguageDeletedEventHandlerTests.cs
@@ -2,44 +2,44 @@
using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Domain.Localization;
+using Grand.Infrastructure.Events;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Events
-{
- [TestClass()]
- public class LanguageDeletedEventHandlerTests
- {
- private Mock<ILanguageService> _languageServiceMock;
- private Mock<ISettingService> _settingServiceMock;
+namespace Grand.Business.Common.Tests.Events;
- private LanguageSettings _languageSettings;
+[TestClass]
+public class LanguageDeletedEventHandlerTests
+{
+ private LanguageDeletedEventHandler _handler;
+ private Mock<ILanguageService> _languageServiceMock;
- private LanguageDeletedEventHandler _handler;
+ private LanguageSettings _languageSettings;
+ private Mock<ISettingService> _settingServiceMock;
- [TestInitialize()]
- public void Init()
- {
- _languageServiceMock = new Mock<ILanguageService>();
- _settingServiceMock = new Mock<ISettingService>();
- _languageSettings = new LanguageSettings { DefaultAdminLanguageId = "1" };
- _handler = new LanguageDeletedEventHandler(_languageServiceMock.Object, _settingServiceMock.Object,
- _languageSettings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _languageServiceMock = new Mock<ILanguageService>();
+ _settingServiceMock = new Mock<ISettingService>();
+ _languageSettings = new LanguageSettings { DefaultAdminLanguageId = "1" };
+ _handler = new LanguageDeletedEventHandler(_languageServiceMock.Object, _settingServiceMock.Object,
+ _languageSettings);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Assert
- _languageServiceMock.Setup(x => x.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult(
- new List<Language> { new Language { Name = "English" }, new Language { Name = "Polish" } } as IList<Language>));
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Assert
+ _languageServiceMock.Setup(x => x.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(
+ Task.FromResult(
+ new List<Language> { new() { Name = "English" }, new() { Name = "Polish" } } as IList<Language>));
- var notification = new Infrastructure.Events.EntityDeleted<Language>(new Language { Id = "1" });
- //Act
- await _handler.Handle(notification, CancellationToken.None);
+ var notification = new EntityDeleted<Language>(new Language { Id = "1" });
+ //Act
+ await _handler.Handle(notification, CancellationToken.None);
- //Assert
- _settingServiceMock.Verify(x => x.SaveSetting<LanguageSettings>(It.IsAny<LanguageSettings>(), ""), Times.Once());
- }
+ //Assert
+ _settingServiceMock.Verify(x => x.SaveSetting(It.IsAny<LanguageSettings>(), ""), Times.Once());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Extensions/SeoExtensionsTests.cs b/src/Tests/Grand.Business.Common.Tests/Extensions/SeoExtensionsTests.cs
index 3ae63670a..b6a94da58 100644
--- a/src/Tests/Grand.Business.Common.Tests/Extensions/SeoExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Extensions/SeoExtensionsTests.cs
@@ -1,54 +1,57 @@
using Grand.Business.Core.Extensions;
using Grand.Domain.Catalog;
+using Grand.Domain.Localization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Common.Tests.Extensions
+namespace Grand.Business.Common.Tests.Extensions;
+
+[TestClass]
+public class SeoExtensionsTests
{
- [TestClass()]
- public class SeoExtensionsTests
+ [TestMethod]
+ public void SeoExtensionsTest()
+ {
+ var charConversions = "ä:a;ö:o;ü:u;т:t;е:e;с:s;т:t";
+
+ //german letters with diacritics
+ Assert.AreEqual("testaou", SeoExtensions.GenerateSlug("testäöü", true, false, false, charConversions));
+ Assert.AreEqual("test", SeoExtensions.GenerateSlug("testäöü", false, false, false));
+ //russian letters
+ Assert.AreEqual("testtest", SeoExtensions.GenerateSlug("testтест", true, false, false, charConversions));
+ Assert.AreEqual("test", SeoExtensions.GenerateSlug("testтест", false, false, false));
+
+ Assert.AreEqual("test", SeoExtensions.GenerateSlug("testтест", false, false, false));
+ Assert.AreEqual("testтест", SeoExtensions.GenerateSlug("testтест", false, true, false));
+
+ //other
+ Assert.AreEqual("abcdefghijklmnopqrstuvwxyz1234567890",
+ SeoExtensions.GenerateSlug("abcdefghijklmnopqrstuvwxyz1234567890", false, false, false));
+
+ Assert.AreEqual("test-test", SeoExtensions.GenerateSlug("test test", false, false, false));
+ Assert.AreEqual("test-test", SeoExtensions.GenerateSlug("test test", false, false, false));
+ }
+
+ [TestMethod]
+ public void GetSeName_ReturnExpectedValue()
+ {
+ var product = new Product {
+ SeName = "se-name"
+ };
+ //if lang id null , return global se name
+ Assert.AreEqual("se-name", product.GetSeName(null));
+ product.Locales.Add(new TranslationEntity
+ { LocaleKey = "SeName", LocaleValue = "se-name-1", LanguageId = "1" });
+ product.Locales.Add(new TranslationEntity
+ { LocaleKey = "SeName", LocaleValue = "se-name-2", LanguageId = "2" });
+ Assert.AreEqual("se-name-1", product.GetSeName("1"));
+ Assert.AreEqual("se-name-2", product.GetSeName("2"));
+ }
+
+ [TestMethod]
+ public void GenerateSlug_ReturnExpectedResult()
{
- [TestMethod()]
- public void SeoExtensionsTest()
- {
- var charConversions = "ä:a;ö:o;ü:u;т:t;е:e;с:s;т:t";
-
- //german letters with diacritics
- Assert.AreEqual("testaou", SeoExtensions.GenerateSlug("testäöü", true, false, false, charConversions));
- Assert.AreEqual("test", SeoExtensions.GenerateSlug("testäöü", false, false, false));
- //russian letters
- Assert.AreEqual("testtest", SeoExtensions.GenerateSlug("testтест", true, false, false, charConversions));
- Assert.AreEqual("test", SeoExtensions.GenerateSlug("testтест", false, false, false));
-
- Assert.AreEqual("test", SeoExtensions.GenerateSlug("testтест", false, false, false));
- Assert.AreEqual("testтест", SeoExtensions.GenerateSlug("testтест", false, true, false));
-
- //other
- Assert.AreEqual("abcdefghijklmnopqrstuvwxyz1234567890", SeoExtensions.GenerateSlug("abcdefghijklmnopqrstuvwxyz1234567890", false, false, false));
-
- Assert.AreEqual("test-test", SeoExtensions.GenerateSlug("test test", false, false, false));
- Assert.AreEqual("test-test", SeoExtensions.GenerateSlug("test test", false, false, false));
- }
-
- [TestMethod()]
- public void GetSeName_ReturnExpectedValue()
- {
- var product = new Product {
- SeName = "se-name"
- };
- //if lang id null , return global se name
- Assert.AreEqual("se-name", product.GetSeName<Product>(null));
- product.Locales.Add(new Domain.Localization.TranslationEntity { LocaleKey = "SeName", LocaleValue = "se-name-1", LanguageId = "1" });
- product.Locales.Add(new Domain.Localization.TranslationEntity { LocaleKey = "SeName", LocaleValue = "se-name-2", LanguageId = "2" });
- Assert.AreEqual("se-name-1", product.GetSeName<Product>("1"));
- Assert.AreEqual("se-name-2", product.GetSeName<Product>("2"));
- }
-
- [TestMethod()]
- public void GenerateSlug_ReturnExpectedResult()
- {
- Assert.AreEqual(SeoExtensions.GenerateSlug("iphone10plus", false, false, false), "iphone10plus");
- Assert.AreEqual(SeoExtensions.GenerateSlug("iphone 10 plus", false, false, false), "iphone-10-plus");
- Assert.AreEqual(SeoExtensions.GenerateSlug("iphOnE 10 Plus", false, false, false), "iphone-10-plus");
- }
+ Assert.AreEqual(SeoExtensions.GenerateSlug("iphone10plus", false, false, false), "iphone10plus");
+ Assert.AreEqual(SeoExtensions.GenerateSlug("iphone 10 plus", false, false, false), "iphone-10-plus");
+ Assert.AreEqual(SeoExtensions.GenerateSlug("iphOnE 10 Plus", false, false, false), "iphone-10-plus");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Extensions/TranslateExtensionsTests.cs b/src/Tests/Grand.Business.Common.Tests/Extensions/TranslateExtensionsTests.cs
index ed0211b2b..8b55eef9d 100644
--- a/src/Tests/Grand.Business.Common.Tests/Extensions/TranslateExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Extensions/TranslateExtensionsTests.cs
@@ -1,91 +1,98 @@
using Grand.Business.Core.Extensions;
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Domain.Catalog;
+using Grand.Domain.Localization;
using Grand.Domain.Permissions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Extensions
+namespace Grand.Business.Common.Tests.Extensions;
+
+[TestClass]
+public class TranslateExtensionsTests
{
- [TestClass()]
- public class TranslateExtensionsTests
+ [TestMethod]
+ public void GetTranslation_ReturnExpectedValue()
{
- [TestMethod()]
- public void GetTranslation_ReturnExpectedValue()
- {
- //prepare ITranslationEntity
- var product = new Product {
- Name = "stname"
- };
- product.Locales.Add(new Domain.Localization.TranslationEntity { LanguageId = "PL", LocaleKey = "Name", LocaleValue = "PLName" });
- product.Locales.Add(new Domain.Localization.TranslationEntity { LanguageId = "UK", LocaleKey = "Name", LocaleValue = "UKName" });
-
- Assert.AreEqual(product.GetTranslation(c => c.Name, "PL"), "PLName");
- Assert.AreEqual(product.GetTranslation(c => c.Name, "UK"), "UKName");
- //if language dont exist return property value
- Assert.AreEqual(product.GetTranslation(c => c.Name, "US"), "stname");
- }
+ //prepare ITranslationEntity
+ var product = new Product {
+ Name = "stname"
+ };
+ product.Locales.Add(new TranslationEntity { LanguageId = "PL", LocaleKey = "Name", LocaleValue = "PLName" });
+ product.Locales.Add(new TranslationEntity { LanguageId = "UK", LocaleKey = "Name", LocaleValue = "UKName" });
- [TestMethod()]
- public void GetTranslation_NullArgument_ThrowException()
- {
- Product product = null;
- Assert.ThrowsException<ArgumentNullException>(() => product.GetTranslation(c => c.Name, "PL"));
- }
+ Assert.AreEqual(product.GetTranslation(c => c.Name, "PL"), "PLName");
+ Assert.AreEqual(product.GetTranslation(c => c.Name, "UK"), "UKName");
+ //if language dont exist return property value
+ Assert.AreEqual(product.GetTranslation(c => c.Name, "US"), "stname");
+ }
- [TestMethod()]
- public void GetTranslation_ExpressionUseMethod_ThrowException()
- {
- Product product = new Product();
- Assert.ThrowsException<ArgumentException>(() => product.GetTranslation(c => c.ParseRequiredProductIds().First(), "PL"));
- }
+ [TestMethod]
+ public void GetTranslation_NullArgument_ThrowException()
+ {
+ Product product = null;
+ Assert.ThrowsException<ArgumentNullException>(() => product.GetTranslation(c => c.Name, "PL"));
+ }
- [TestMethod()]
- public void GetTranslationEnum_ReturnExpectedValue()
- {
- var translationServiceMock = new Mock<ITranslationService>();
- translationServiceMock.Setup(c => c.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns("PLenum");
- Product product = new Product {
- ManageInventoryMethodId = ManageInventoryMethod.ManageStock
- };
- var result = product.ManageInventoryMethodId.GetTranslationEnum(translationServiceMock.Object, "PL");
- Assert.AreEqual(result, "PLenum");
- }
+ [TestMethod]
+ public void GetTranslation_ExpressionUseMethod_ThrowException()
+ {
+ var product = new Product();
+ Assert.ThrowsException<ArgumentException>(() =>
+ product.GetTranslation(c => c.ParseRequiredProductIds().First(), "PL"));
+ }
- [TestMethod()]
- public void GetTranslationEnum_UseNotEnum_ThrowException()
- {
- var translationServiceMock = new Mock<ITranslationService>();
- var fake = new FakeStruct();
- Assert.ThrowsException<ArgumentException>(() => fake.GetTranslationEnum(translationServiceMock.Object, "PL"));
- }
+ [TestMethod]
+ public void GetTranslationEnum_ReturnExpectedValue()
+ {
+ var translationServiceMock = new Mock<ITranslationService>();
+ translationServiceMock
+ .Setup(c => c.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
+ .Returns("PLenum");
+ var product = new Product {
+ ManageInventoryMethodId = ManageInventoryMethod.ManageStock
+ };
+ var result = product.ManageInventoryMethodId.GetTranslationEnum(translationServiceMock.Object, "PL");
+ Assert.AreEqual(result, "PLenum");
+ }
- [TestMethod()]
- public void GetTranslationPermissionName_ReturnExpectedValue()
- {
- var expectedValue = "PLpermision";
- var translationServiceMock = new Mock<ITranslationService>();
- translationServiceMock.Setup(c => c.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(expectedValue);
- Permission record = new Permission {
- SystemName = "sysname"
- };
- var result = record.GetTranslationPermissionName(translationServiceMock.Object, "PL");
- Assert.AreEqual(result, expectedValue);
- }
+ [TestMethod]
+ public void GetTranslationEnum_UseNotEnum_ThrowException()
+ {
+ var translationServiceMock = new Mock<ITranslationService>();
+ var fake = new FakeStruct();
+ Assert.ThrowsException<ArgumentException>(() => fake.GetTranslationEnum(translationServiceMock.Object, "PL"));
+ }
- [TestMethod()]
- public void GetTranslationPermissionName_NullArgument_ThrowException()
- {
- var expectedValue = "PLpermision";
- var translationServiceMock = new Mock<ITranslationService>();
- translationServiceMock.Setup(c => c.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(expectedValue);
- Permission record = null;
- Assert.ThrowsException<ArgumentNullException>(() => record.GetTranslationPermissionName(translationServiceMock.Object, "PL"));
- }
+ [TestMethod]
+ public void GetTranslationPermissionName_ReturnExpectedValue()
+ {
+ var expectedValue = "PLpermision";
+ var translationServiceMock = new Mock<ITranslationService>();
+ translationServiceMock
+ .Setup(c => c.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
+ .Returns(expectedValue);
+ var record = new Permission {
+ SystemName = "sysname"
+ };
+ var result = record.GetTranslationPermissionName(translationServiceMock.Object, "PL");
+ Assert.AreEqual(result, expectedValue);
+ }
- private struct FakeStruct
- {
+ [TestMethod]
+ public void GetTranslationPermissionName_NullArgument_ThrowException()
+ {
+ var expectedValue = "PLpermision";
+ var translationServiceMock = new Mock<ITranslationService>();
+ translationServiceMock
+ .Setup(c => c.GetResource(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()))
+ .Returns(expectedValue);
+ Permission record = null;
+ Assert.ThrowsException<ArgumentNullException>(() =>
+ record.GetTranslationPermissionName(translationServiceMock.Object, "PL"));
+ }
- }
+ private struct FakeStruct
+ {
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeParserTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeParserTests.cs
index 2d535fe31..6b132aa68 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeParserTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeParserTests.cs
@@ -1,51 +1,52 @@
-using Grand.Business.Core.Interfaces.Common.Addresses;
+using Grand.Business.Common.Services.Addresses;
+using Grand.Business.Core.Interfaces.Common.Addresses;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Business.Common.Services.Addresses;
using Grand.Domain.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Addresses
+namespace Grand.Business.Common.Tests.Services.Addresses;
+
+[TestClass]
+public class AddressAttributeParserTests
{
- [TestClass()]
- public class AddressAttributeParserTests
- {
- private Mock<IAddressAttributeService> _atrService;
- private Mock<ITranslationService> _translationService;
- private AddressAttributeParser _parser;
- private List<CustomAttribute> customAtr;
+ private Mock<IAddressAttributeService> _atrService;
+ private AddressAttributeParser _parser;
+ private Mock<ITranslationService> _translationService;
+ private List<CustomAttribute> customAtr;
- [TestInitialize()]
- public void Init()
- {
- _atrService = new Mock<IAddressAttributeService>();
- _translationService = new Mock<ITranslationService>();
- _parser = new AddressAttributeParser(_atrService.Object);
- customAtr = [
- new CustomAttribute { Key = "key1", Value = "value1" },
- new CustomAttribute { Key = "key2", Value = "value2" },
- new CustomAttribute { Key = "key3", Value = "value3" },
- new CustomAttribute { Key = "key4", Value = "value4" }
- ];
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _atrService = new Mock<IAddressAttributeService>();
+ _translationService = new Mock<ITranslationService>();
+ _parser = new AddressAttributeParser(_atrService.Object);
+ customAtr = [
+ new CustomAttribute { Key = "key1", Value = "value1" },
+ new CustomAttribute { Key = "key2", Value = "value2" },
+ new CustomAttribute { Key = "key3", Value = "value3" },
+ new CustomAttribute { Key = "key4", Value = "value4" }
+ ];
+ }
- [TestMethod()]
- public async Task ParseAddressAttributes_ReturnExpectedValues()
- {
- _atrService.Setup(c => c.GetAddressAttributeById("key1")).Returns(Task.FromResult(new AddressAttribute { Id = "key1" }));
- _atrService.Setup(c => c.GetAddressAttributeById("key2")).Returns(Task.FromResult(new AddressAttribute { Id = "key2" }));
- var result = await _parser.ParseAddressAttributes(customAtr);
- Assert.IsTrue(result.Count == 2);
- Assert.IsTrue(result.First().Id.Equals("key1"));
- }
+ [TestMethod]
+ public async Task ParseAddressAttributes_ReturnExpectedValues()
+ {
+ _atrService.Setup(c => c.GetAddressAttributeById("key1"))
+ .Returns(Task.FromResult(new AddressAttribute { Id = "key1" }));
+ _atrService.Setup(c => c.GetAddressAttributeById("key2"))
+ .Returns(Task.FromResult(new AddressAttribute { Id = "key2" }));
+ var result = await _parser.ParseAddressAttributes(customAtr);
+ Assert.IsTrue(result.Count == 2);
+ Assert.IsTrue(result.First().Id.Equals("key1"));
+ }
- [TestMethod()]
- public void AddAddressAttribute_ReturnExpectedValues()
- {
- var atr = new AddressAttribute { Id = "added" };
- var result = _parser.AddAddressAttribute(customAtr, atr, "new-added-value");
- Assert.IsTrue(result.Count == 5);
- Assert.IsTrue(result.Any(c => c.Key.Equals("added")));
- }
+ [TestMethod]
+ public void AddAddressAttribute_ReturnExpectedValues()
+ {
+ var atr = new AddressAttribute { Id = "added" };
+ var result = _parser.AddAddressAttribute(customAtr, atr, "new-added-value");
+ Assert.IsTrue(result.Count == 5);
+ Assert.IsTrue(result.Any(c => c.Key.Equals("added")));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeServiceTests.cs
index 0e702f586..ce603a4a2 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Addresses/AddressAttributeServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Common.Services.Addresses;
-using Grand.Domain.Common;
using Grand.Data;
using Grand.Data.Mongo;
+using Grand.Domain.Common;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Events;
using Grand.SharedKernel.Extensions;
@@ -9,75 +9,74 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Addresses
+namespace Grand.Business.Common.Tests.Services.Addresses;
+
+[TestClass]
+public class AddressAttributeServiceTests
{
- [TestClass()]
- public class AddressAttributeServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<MongoRepository<AddressAttribute>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private AddressAttributeService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<MongoRepository<AddressAttribute>> _repositoryMock;
+ private AddressAttributeService _service;
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "";
- _cacheMock = new Mock<ICacheBase>();
- _repositoryMock = new Mock<MongoRepository<AddressAttribute>>(Mock.Of<IAuditInfoProvider>());
- _mediatorMock = new Mock<IMediator>();
- _service = new AddressAttributeService(_cacheMock.Object, _repositoryMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = "";
+ _cacheMock = new Mock<ICacheBase>();
+ _repositoryMock = new Mock<MongoRepository<AddressAttribute>>(Mock.Of<IAuditInfoProvider>());
+ _mediatorMock = new Mock<IMediator>();
+ _service = new AddressAttributeService(_cacheMock.Object, _repositoryMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task InsertAddressAttribute_ValidArgument_InvokeExpectedMethod()
- {
- await _service.InsertAddressAttribute(new AddressAttribute());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<AddressAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<AddressAttribute>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
- }
+ [TestMethod]
+ public async Task InsertAddressAttribute_ValidArgument_InvokeExpectedMethod()
+ {
+ await _service.InsertAddressAttribute(new AddressAttribute());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<AddressAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<AddressAttribute>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
+ }
- [TestMethod()]
- public async Task DeleteAddressAttribute_ValidArgument_InvokeExpectedMethod()
- {
- await _service.DeleteAddressAttribute(new AddressAttribute());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<AddressAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<AddressAttribute>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
- }
+ [TestMethod]
+ public async Task DeleteAddressAttribute_ValidArgument_InvokeExpectedMethod()
+ {
+ await _service.DeleteAddressAttribute(new AddressAttribute());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<AddressAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<AddressAttribute>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
+ }
- [TestMethod()]
- public async Task UpdateAddressAttribute_ValidArgument_InvokeExpectedMethod()
- {
- await _service.UpdateAddressAttribute(new AddressAttribute());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<AddressAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<AddressAttribute>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
- }
+ [TestMethod]
+ public async Task UpdateAddressAttribute_ValidArgument_InvokeExpectedMethod()
+ {
+ await _service.UpdateAddressAttribute(new AddressAttribute());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<AddressAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<AddressAttribute>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
+ }
- [TestMethod()]
- public async Task InsertAddressAttributeValue_ValidArgument_InvokeExpectedMethod()
- {
- await _service.InsertAddressAttributeValue(new AddressAttributeValue { AddressAttributeId = "id" });
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<AddressAttributeValue>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
- }
+ [TestMethod]
+ public async Task InsertAddressAttributeValue_ValidArgument_InvokeExpectedMethod()
+ {
+ await _service.InsertAddressAttributeValue(new AddressAttributeValue { AddressAttributeId = "id" });
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<AddressAttributeValue>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
+ }
- [TestMethod()]
- public async Task DeleteAddressAttributeValue_ValidArgument_InvokeExpectedMethod()
- {
- await _service.DeleteAddressAttributeValue(new AddressAttributeValue { AddressAttributeId = "id" });
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<AddressAttributeValue>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
- }
+ [TestMethod]
+ public async Task DeleteAddressAttributeValue_ValidArgument_InvokeExpectedMethod()
+ {
+ await _service.DeleteAddressAttributeValue(new AddressAttributeValue { AddressAttributeId = "id" });
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<AddressAttributeValue>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
+ }
- [TestMethod()]
- public async Task UpdateAddressAttributeValue_ValidArgument_InvokeExpectedMethod()
- {
- await _service.UpdateAddressAttributeValue(new AddressAttributeValue { AddressAttributeId = "id" });
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<AddressAttributeValue>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
- }
+ [TestMethod]
+ public async Task UpdateAddressAttributeValue_ValidArgument_InvokeExpectedMethod()
+ {
+ await _service.UpdateAddressAttributeValue(new AddressAttributeValue { AddressAttributeId = "id" });
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<AddressAttributeValue>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Configuration/SettingServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Configuration/SettingServiceTests.cs
index 9217dd473..674bf0571 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Configuration/SettingServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Configuration/SettingServiceTests.cs
@@ -1,67 +1,66 @@
using Grand.Business.Common.Services.Configuration;
-using Grand.Domain.Configuration;
using Grand.Data;
+using Grand.Domain.Configuration;
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Configuration
+namespace Grand.Business.Common.Tests.Services.Configuration;
+
+[TestClass]
+public class SettingServiceTests
{
- [TestClass()]
- public class SettingServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<IRepository<Setting>> _repositoryMock;
- private SettingService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IRepository<Setting>> _repositoryMock;
+ private SettingService _service;
- [TestInitialize()]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _repositoryMock = new Mock<IRepository<Setting>>();
- _service = new SettingService(_cacheMock.Object, _repositoryMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _repositoryMock = new Mock<IRepository<Setting>>();
+ _service = new SettingService(_cacheMock.Object, _repositoryMock.Object);
+ }
- [TestMethod()]
- public async Task InsertSetting_InvokeExpectedMethods()
- {
- await _service.InsertSetting(new Setting(), true);
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Setting>()), Times.Once);
- _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertSetting_InvokeExpectedMethods()
+ {
+ await _service.InsertSetting(new Setting());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Setting>()), Times.Once);
+ _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod()]
- public void InsertSetting_NullArgument_TrhowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertSetting(null, true));
- }
+ [TestMethod]
+ public void InsertSetting_NullArgument_TrhowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertSetting(null));
+ }
- [TestMethod()]
- public async Task UpdateSetting_InvokeExpectedMethods()
- {
- await _service.UpdateSetting(new Setting(), true);
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Setting>()), Times.Once);
- _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateSetting_InvokeExpectedMethods()
+ {
+ await _service.UpdateSetting(new Setting());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Setting>()), Times.Once);
+ _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod()]
- public void UpdateSetting_NullArgument_TrhowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateSetting(null, true));
- }
+ [TestMethod]
+ public void UpdateSetting_NullArgument_TrhowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateSetting(null));
+ }
- [TestMethod()]
- public async Task DeleteSetting_InvokeExpectedMethods()
- {
- await _service.DeleteSetting(new Setting());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Setting>()), Times.Once);
- _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteSetting_InvokeExpectedMethods()
+ {
+ await _service.DeleteSetting(new Setting());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Setting>()), Times.Once);
+ _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod()]
- public void DeleteSetting_NullArgument_TrhowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteSetting(null));
- }
+ [TestMethod]
+ public void DeleteSetting_NullArgument_TrhowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteSetting(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Directory/CountryServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Directory/CountryServiceTests.cs
index 9785a7bdc..a775b3d31 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Directory/CountryServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Directory/CountryServiceTests.cs
@@ -1,6 +1,6 @@
using Grand.Business.Common.Services.Directory;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Directory;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -9,208 +9,209 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Directory
+namespace Grand.Business.Common.Tests.Services.Directory;
+
+[TestClass]
+public class CountryServiceTests
{
- [TestClass()]
- public class CountryServiceTests
+ private MemoryCacheBase _cacheBase;
+
+ private CountryService _countryService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Country> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Country>();
+
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _countryService = new CountryService(_repository, _mediatorMock.Object, _cacheBase, new AccessControlConfig());
+ }
+
+ [TestMethod]
+ public async Task GetAllCountriesTest()
+ {
+ //Arrange
+ await _countryService.InsertCountry(new Country { Published = true });
+ await _countryService.InsertCountry(new Country { Published = true });
+ //Act
+ var result = await _countryService.GetAllCountries();
+ //Assert
+ Assert.IsTrue(result.Count > 0);
+ }
+
+ [TestMethod]
+ public async Task GetAllCountriesForBillingTest()
+ {
+ //Arrange
+ await _countryService.InsertCountry(new Country { Published = true, AllowsBilling = true });
+ await _countryService.InsertCountry(new Country { Published = true });
+ //Act
+ var result = await _countryService.GetAllCountriesForBilling();
+ //Assert
+ Assert.IsTrue(result.Count == 1);
+ }
+
+ [TestMethod]
+ public async Task GetAllCountriesForShippingTest()
+ {
+ //Arrange
+ await _countryService.InsertCountry(new Country { Published = true, AllowsShipping = true });
+ await _countryService.InsertCountry(new Country { Published = true });
+ //Act
+ var result = await _countryService.GetAllCountriesForShipping();
+ //Assert
+ Assert.IsTrue(result.Count == 1);
+ }
+
+ [TestMethod]
+ public async Task GetCountryByIdTest()
+ {
+ //Arrange
+ var country = new Country();
+ await _repository.InsertAsync(country);
+ await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
+ await _repository.InsertAsync(new Country { Published = true });
+ //Act
+ var result = await _countryService.GetCountryById(country.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCountriesByIdsTest()
+ {
+ //Arrange
+ var country = new Country();
+ await _repository.InsertAsync(country);
+ await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
+ await _repository.InsertAsync(new Country { Published = true });
+ //Act
+ var result = await _countryService.GetCountriesByIds([country.Id]);
+ //Assert
+ Assert.IsTrue(result.Count == 1);
+ }
+
+ [TestMethod]
+ public async Task GetCountryByTwoLetterIsoCodeTest()
+ {
+ //Arrange
+ var country = new Country { TwoLetterIsoCode = "US" };
+ await _repository.InsertAsync(country);
+ await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
+ await _repository.InsertAsync(new Country { Published = true });
+ //Act
+ var result = await _countryService.GetCountryByTwoLetterIsoCode(country.TwoLetterIsoCode);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCountryByThreeLetterIsoCodeTest()
+ {
+ //Arrange
+ var country = new Country { ThreeLetterIsoCode = "USA" };
+ await _repository.InsertAsync(country);
+ await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
+ await _repository.InsertAsync(new Country { Published = true });
+ //Act
+ var result = await _countryService.GetCountryByThreeLetterIsoCode(country.ThreeLetterIsoCode);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task InsertCountryTest()
+ {
+ //Act
+ await _countryService.InsertCountry(new Country());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCountryTest()
+ {
+ //Arrange
+ var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
+ await _repository.InsertAsync(country);
+ //Act
+ country.Name = "USA";
+ await _countryService.UpdateCountry(country);
+ //Assert
+ Assert.AreEqual("USA", _repository.Table.FirstOrDefault(x => x.Id == country.Id).Name);
+ }
+
+ [TestMethod]
+ public async Task DeleteCountryTest()
+ {
+ //Arrange
+ var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
+ await _repository.InsertAsync(country);
+ //Act
+ await _countryService.DeleteCountry(country);
+ //Assert
+ Assert.IsFalse(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task GetStateProvincesByCountryIdTest()
+ {
+ //Arrange
+ var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
+ country.StateProvinces.Add(new StateProvince());
+ await _repository.InsertAsync(country);
+ //Act
+ var result = await _countryService.GetStateProvincesByCountryId(country.Id);
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertStateProvinceTest()
+ {
+ //Arrange
+ var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
+ await _repository.InsertAsync(country);
+ //Act
+ await _countryService.InsertStateProvince(new StateProvince(), country.Id);
+ //Assert
+ var result = await _countryService.GetStateProvincesByCountryId(country.Id);
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateStateProvinceTest()
+ {
+ //Arrange
+ var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
+ await _repository.InsertAsync(country);
+ var state = new StateProvince();
+ await _countryService.InsertStateProvince(state, country.Id);
+ //Act
+ state.Name = "TEST";
+ await _countryService.UpdateStateProvince(state, country.Id);
+ //Assert
+ var result = await _countryService.GetStateProvincesByCountryId(country.Id);
+ Assert.IsTrue(result.Any());
+ Assert.AreEqual("TEST", result.FirstOrDefault().Name);
+ }
+
+ [TestMethod]
+ public async Task DeleteStateProvinceTest()
{
- private IRepository<Country> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- private CountryService _countryService;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Country>();
-
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _countryService = new CountryService(_repository, _mediatorMock.Object, _cacheBase, new AccessControlConfig());
- }
-
- [TestMethod()]
- public async Task GetAllCountriesTest()
- {
- //Arrange
- await _countryService.InsertCountry(new Country { Published = true });
- await _countryService.InsertCountry(new Country { Published = true });
- //Act
- var result = await _countryService.GetAllCountries();
- //Assert
- Assert.IsTrue(result.Count > 0);
- }
-
- [TestMethod()]
- public async Task GetAllCountriesForBillingTest()
- {
- //Arrange
- await _countryService.InsertCountry(new Country { Published = true, AllowsBilling = true });
- await _countryService.InsertCountry(new Country { Published = true });
- //Act
- var result = await _countryService.GetAllCountriesForBilling();
- //Assert
- Assert.IsTrue(result.Count == 1);
- }
-
- [TestMethod()]
- public async Task GetAllCountriesForShippingTest()
- {
- //Arrange
- await _countryService.InsertCountry(new Country { Published = true, AllowsShipping = true });
- await _countryService.InsertCountry(new Country { Published = true });
- //Act
- var result = await _countryService.GetAllCountriesForShipping();
- //Assert
- Assert.IsTrue(result.Count == 1);
- }
-
- [TestMethod()]
- public async Task GetCountryByIdTest()
- {
- //Arrange
- var country = new Country();
- await _repository.InsertAsync(country);
- await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
- await _repository.InsertAsync(new Country { Published = true });
- //Act
- var result = await _countryService.GetCountryById(country.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCountriesByIdsTest()
- {
- //Arrange
- var country = new Country();
- await _repository.InsertAsync(country);
- await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
- await _repository.InsertAsync(new Country { Published = true });
- //Act
- var result = await _countryService.GetCountriesByIds([country.Id]);
- //Assert
- Assert.IsTrue(result.Count == 1);
- }
-
- [TestMethod()]
- public async Task GetCountryByTwoLetterIsoCodeTest()
- {
- //Arrange
- var country = new Country { TwoLetterIsoCode = "US" };
- await _repository.InsertAsync(country);
- await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
- await _repository.InsertAsync(new Country { Published = true });
- //Act
- var result = await _countryService.GetCountryByTwoLetterIsoCode(country.TwoLetterIsoCode);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCountryByThreeLetterIsoCodeTest()
- {
- //Arrange
- var country = new Country { ThreeLetterIsoCode = "USA" };
- await _repository.InsertAsync(country);
- await _repository.InsertAsync(new Country { Published = true, AllowsShipping = true });
- await _repository.InsertAsync(new Country { Published = true });
- //Act
- var result = await _countryService.GetCountryByThreeLetterIsoCode(country.ThreeLetterIsoCode);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task InsertCountryTest()
- {
- //Act
- await _countryService.InsertCountry(new Country());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCountryTest()
- {
- //Arrange
- var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
- await _repository.InsertAsync(country);
- //Act
- country.Name = "USA";
- await _countryService.UpdateCountry(country);
- //Assert
- Assert.AreEqual("USA", _repository.Table.FirstOrDefault(x => x.Id == country.Id).Name);
- }
-
- [TestMethod()]
- public async Task DeleteCountryTest()
- {
- //Arrange
- var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
- await _repository.InsertAsync(country);
- //Act
- await _countryService.DeleteCountry(country);
- //Assert
- Assert.IsFalse(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetStateProvincesByCountryIdTest()
- {
- //Arrange
- var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
- country.StateProvinces.Add(new StateProvince());
- await _repository.InsertAsync(country);
- //Act
- var result = await _countryService.GetStateProvincesByCountryId(country.Id);
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task InsertStateProvinceTest()
- {
- //Arrange
- var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
- await _repository.InsertAsync(country);
- //Act
- await _countryService.InsertStateProvince(new StateProvince(), country.Id);
- //Assert
- var result = await _countryService.GetStateProvincesByCountryId(country.Id);
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task UpdateStateProvinceTest()
- {
- //Arrange
- var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
- await _repository.InsertAsync(country);
- var state = new StateProvince();
- await _countryService.InsertStateProvince(state, country.Id);
- //Act
- state.Name = "TEST";
- await _countryService.UpdateStateProvince(state, country.Id);
- //Assert
- var result = await _countryService.GetStateProvincesByCountryId(country.Id);
- Assert.IsTrue(result.Any());
- Assert.AreEqual("TEST", result.FirstOrDefault().Name);
- }
-
- [TestMethod()]
- public async Task DeleteStateProvinceTest()
- {
- //Arrange
- var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
- await _repository.InsertAsync(country);
- var state = new StateProvince();
- await _countryService.InsertStateProvince(state, country.Id);
- //Act
- await _countryService.DeleteStateProvince(state, country.Id);
- //Assert
- var result = await _countryService.GetStateProvincesByCountryId(country.Id);
- Assert.IsFalse(result.Any());
- }
+ //Arrange
+ var country = new Country { ThreeLetterIsoCode = "USA", Name = "United States" };
+ await _repository.InsertAsync(country);
+ var state = new StateProvince();
+ await _countryService.InsertStateProvince(state, country.Id);
+ //Act
+ await _countryService.DeleteStateProvince(state, country.Id);
+ //Assert
+ var result = await _countryService.GetStateProvincesByCountryId(country.Id);
+ Assert.IsFalse(result.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Directory/CurrencyServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Directory/CurrencyServiceTests.cs
index d7658cd79..a9eb9dc3b 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Directory/CurrencyServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Directory/CurrencyServiceTests.cs
@@ -1,6 +1,6 @@
-using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Common.Services.Directory;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
-using Grand.Business.Common.Services.Directory;
using Grand.Data;
using Grand.Data.Mongo;
using Grand.Domain.Directory;
@@ -12,175 +12,181 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Directory
+namespace Grand.Business.Common.Tests.Services.Directory;
+
+[TestClass]
+public class CurrencyServiceTests
{
- [TestClass()]
- public class CurrencyServiceTests
+ private Mock<IAclService> _aclService;
+ private Mock<ICacheBase> _cacheManager;
+ private IRepository<Currency> _currencyRepository;
+ private ICurrencyService _currencyService;
+ private CurrencySettings _currencySettings;
+ private IMediator _eventPublisher;
+ private IServiceProvider _serviceProvider;
+
+ private Currency currencyUSD, currencyRUR, currencyEUR;
+ private Mock<IRepository<Currency>> tempCurrencyRepository;
+ private Mock<IMediator> tempEventPublisher;
+
+ [TestInitialize]
+ public void TestInitialize()
{
- private IRepository<Currency> _currencyRepository;
- private CurrencySettings _currencySettings;
- private IMediator _eventPublisher;
- private ICurrencyService _currencyService;
- private Mock<ICacheBase> _cacheManager;
- private Mock<IAclService> _aclService;
- private IServiceProvider _serviceProvider;
-
- private Currency currencyUSD, currencyRUR, currencyEUR;
- private Mock<IRepository<Currency>> tempCurrencyRepository;
- private Mock<IMediator> tempEventPublisher;
-
- [TestInitialize()]
- public void TestInitialize()
+ CommonPath.BaseDirectory = "";
+
+ currencyUSD = new Currency {
+ Id = "1",
+ Name = "US Dollar",
+ CurrencyCode = "USD",
+ Rate = 1.2,
+ DisplayLocale = "en-US",
+ CustomFormatting = "",
+ Published = true,
+ DisplayOrder = 1
+ };
+ currencyEUR = new Currency {
+ Id = "2",
+ Name = "Euro",
+ CurrencyCode = "EUR",
+ Rate = 1,
+ DisplayLocale = "",
+ CustomFormatting = "€0.00",
+ Published = true,
+ DisplayOrder = 2
+ };
+ currencyRUR = new Currency {
+ Id = "3",
+ Name = "Russian Rouble",
+ CurrencyCode = "RUB",
+ Rate = 34.5,
+ DisplayLocale = "ru-RU",
+ CustomFormatting = "",
+ Published = true,
+ DisplayOrder = 3
+ };
+
+ tempCurrencyRepository = new Mock<IRepository<Currency>>();
{
- CommonPath.BaseDirectory = "";
-
- currencyUSD = new Currency {
- Id = "1",
- Name = "US Dollar",
- CurrencyCode = "USD",
- Rate = 1.2,
- DisplayLocale = "en-US",
- CustomFormatting = "",
- Published = true,
- DisplayOrder = 1
- };
- currencyEUR = new Currency {
- Id = "2",
- Name = "Euro",
- CurrencyCode = "EUR",
- Rate = 1,
- DisplayLocale = "",
- CustomFormatting = "€0.00",
- Published = true,
- DisplayOrder = 2
- };
- currencyRUR = new Currency {
- Id = "3",
- Name = "Russian Rouble",
- CurrencyCode = "RUB",
- Rate = 34.5,
- DisplayLocale = "ru-RU",
- CustomFormatting = "",
- Published = true,
- DisplayOrder = 3
- };
-
- tempCurrencyRepository = new Mock<IRepository<Currency>>();
- {
- var IMongoCollection = new Mock<MongoRepository<Currency>>(Mock.Of<IAuditInfoProvider>()).Object;
- IMongoCollection.Insert(currencyUSD);
- IMongoCollection.Insert(currencyEUR);
- IMongoCollection.Insert(currencyRUR);
-
- tempCurrencyRepository.Setup(x => x.Table).Returns(IMongoCollection.Table);
- tempCurrencyRepository.Setup(x => x.GetByIdAsync(currencyUSD.Id)).ReturnsAsync(currencyUSD);
- tempCurrencyRepository.Setup(x => x.GetByIdAsync(currencyEUR.Id)).ReturnsAsync(currencyEUR);
- tempCurrencyRepository.Setup(x => x.GetByIdAsync(currencyRUR.Id)).ReturnsAsync(currencyRUR);
- _currencyRepository = tempCurrencyRepository.Object;
- }
- tempEventPublisher = new Mock<IMediator>();
- {
- //tempEventPublisher.Setup(x => x.PublishAsync(It.IsAny<object>()));
- _eventPublisher = tempEventPublisher.Object;
- }
-
- _cacheManager = new Mock<ICacheBase>();
- _aclService = new Mock<IAclService>();
- _serviceProvider = new Mock<IServiceProvider>().Object;
-
- _currencySettings = new CurrencySettings {
- PrimaryStoreCurrencyId = currencyUSD.Id,
- PrimaryExchangeRateCurrencyId = currencyEUR.Id
- };
-
-
- _currencyService = new CurrencyService(
- _cacheManager.Object, _currencyRepository, _aclService.Object,
- _currencySettings, _eventPublisher);
-
- //tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCategories, "", "", false)).ReturnsAsync(new List<Discount>());
+ var IMongoCollection = new Mock<MongoRepository<Currency>>(Mock.Of<IAuditInfoProvider>()).Object;
+ IMongoCollection.Insert(currencyUSD);
+ IMongoCollection.Insert(currencyEUR);
+ IMongoCollection.Insert(currencyRUR);
+
+ tempCurrencyRepository.Setup(x => x.Table).Returns(IMongoCollection.Table);
+ tempCurrencyRepository.Setup(x => x.GetByIdAsync(currencyUSD.Id)).ReturnsAsync(currencyUSD);
+ tempCurrencyRepository.Setup(x => x.GetByIdAsync(currencyEUR.Id)).ReturnsAsync(currencyEUR);
+ tempCurrencyRepository.Setup(x => x.GetByIdAsync(currencyRUR.Id)).ReturnsAsync(currencyRUR);
+ _currencyRepository = tempCurrencyRepository.Object;
}
-
- [TestMethod()]
- public void Can_convert_currency_1()
+ tempEventPublisher = new Mock<IMediator>();
{
- //e.g.
- //10.1 * 1.5 = 15.15
- Assert.AreEqual(15.15, _currencyService.ConvertCurrency(10.1, 1.5));
- Assert.AreEqual(10.122, _currencyService.ConvertCurrency(10.122, 1));
- Assert.AreEqual(34.4148, _currencyService.ConvertCurrency(10.122, 3.4));
- Assert.AreEqual(0, _currencyService.ConvertCurrency(10.1, 0));
- Assert.AreEqual(0, _currencyService.ConvertCurrency(0, 5));
+ //tempEventPublisher.Setup(x => x.PublishAsync(It.IsAny<object>()));
+ _eventPublisher = tempEventPublisher.Object;
}
- [TestMethod()]
- public async Task ConvertFromPrimaryExchangeRateCurrency_ReturnExpectedResult()
- {
- //set primary exchange rate
- _cacheManager.Setup(c => c.GetAsync<Currency>(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>())).Returns(Task.FromResult(currencyUSD));
- var result = await _currencyService.ConvertFromPrimaryExchangeRateCurrency(100, currencyEUR);
- Assert.AreEqual(100, result);
- currencyEUR.Rate = 2;
- Assert.AreEqual(200, await _currencyService.ConvertFromPrimaryExchangeRateCurrency(100, currencyEUR));
- }
+ _cacheManager = new Mock<ICacheBase>();
+ _aclService = new Mock<IAclService>();
+ _serviceProvider = new Mock<IServiceProvider>().Object;
- [TestMethod()]
- public async Task ConvertToPrimaryExchangeRateCurrency_ReturnExpectedResult()
- {
- //set primary exchange rate
- _cacheManager.Setup(c => c.GetAsync<Currency>(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>())).Returns(Task.FromResult(currencyUSD));
- var result = await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR);
- Assert.AreEqual(100, result);
- currencyEUR.Rate = 2;
- Assert.AreEqual(50, await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR));
- }
+ _currencySettings = new CurrencySettings {
+ PrimaryStoreCurrencyId = currencyUSD.Id,
+ PrimaryExchangeRateCurrencyId = currencyEUR.Id
+ };
- [TestMethod()]
- public void ConvertToPrimaryExchangeRateCurrency_ZeroExchangeRate_ThrowException()
- {
- _cacheManager.Setup(c => c.GetAsync<Currency>(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>())).Returns(Task.FromResult(currencyUSD));
- currencyEUR.Rate = 0;
- Assert.ThrowsExceptionAsync<GrandException>(async () => await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR));
- }
- [TestMethod()]
- public void ConvertToPrimaryExchangeRateCurrency_CannotLoadPrimaryExchange_ThrowException()
- {
- _cacheManager.Setup(c => c.GetAsync<Currency>(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>())).Returns(Task.FromResult<Currency>(null));
- Assert.ThrowsExceptionAsync<Exception>(async () => await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR));
- }
+ _currencyService = new CurrencyService(
+ _cacheManager.Object, _currencyRepository, _aclService.Object,
+ _currencySettings, _eventPublisher);
- [TestMethod()]
- public async Task GetPrimaryStoreCurrency_ReturnExpectedValue()
- {
- _currencySettings.PrimaryStoreCurrencyId = currencyUSD.Id;
- _cacheManager.Setup(c => c.GetAsync<Currency>(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>())).Returns(Task.FromResult(currencyUSD));
- var result = await _currencyService.GetPrimaryStoreCurrency();
- Assert.AreEqual(result.Id, currencyUSD.Id);
- }
+ //tempDiscountServiceMock.Setup(x => x.GetAllDiscounts(DiscountType.AssignedToCategories, "", "", false)).ReturnsAsync(new List<Discount>());
+ }
- [TestMethod()]
- public async Task InsertCurrency_ValidArgument()
- {
- await _currencyService.InsertCurrency(new Currency());
- tempCurrencyRepository.Verify(c => c.InsertAsync(It.IsAny<Currency>()), Times.Once);
- tempEventPublisher.Verify(c => c.Publish(It.IsAny<EntityInserted<Currency>>(), default), Times.Once);
- }
+ [TestMethod]
+ public void Can_convert_currency_1()
+ {
+ //e.g.
+ //10.1 * 1.5 = 15.15
+ Assert.AreEqual(15.15, _currencyService.ConvertCurrency(10.1, 1.5));
+ Assert.AreEqual(10.122, _currencyService.ConvertCurrency(10.122, 1));
+ Assert.AreEqual(34.4148, _currencyService.ConvertCurrency(10.122, 3.4));
+ Assert.AreEqual(0, _currencyService.ConvertCurrency(10.1, 0));
+ Assert.AreEqual(0, _currencyService.ConvertCurrency(0, 5));
+ }
- [TestMethod()]
- public async Task UpdateCurrency_ValidArgument()
- {
- await _currencyService.UpdateCurrency(new Currency());
- tempCurrencyRepository.Verify(c => c.UpdateAsync(It.IsAny<Currency>()), Times.Once);
- tempEventPublisher.Verify(c => c.Publish(It.IsAny<EntityUpdated<Currency>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task ConvertFromPrimaryExchangeRateCurrency_ReturnExpectedResult()
+ {
+ //set primary exchange rate
+ _cacheManager.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>()))
+ .Returns(Task.FromResult(currencyUSD));
+ var result = await _currencyService.ConvertFromPrimaryExchangeRateCurrency(100, currencyEUR);
+ Assert.AreEqual(100, result);
+ currencyEUR.Rate = 2;
+ Assert.AreEqual(200, await _currencyService.ConvertFromPrimaryExchangeRateCurrency(100, currencyEUR));
+ }
- [TestMethod()]
- public async Task DeleteCurrency_ValidArgument()
- {
- await _currencyService.DeleteCurrency(new Currency());
- tempCurrencyRepository.Verify(c => c.DeleteAsync(It.IsAny<Currency>()), Times.Once);
- tempEventPublisher.Verify(c => c.Publish(It.IsAny<EntityDeleted<Currency>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task ConvertToPrimaryExchangeRateCurrency_ReturnExpectedResult()
+ {
+ //set primary exchange rate
+ _cacheManager.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>()))
+ .Returns(Task.FromResult(currencyUSD));
+ var result = await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR);
+ Assert.AreEqual(100, result);
+ currencyEUR.Rate = 2;
+ Assert.AreEqual(50, await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR));
+ }
+
+ [TestMethod]
+ public void ConvertToPrimaryExchangeRateCurrency_ZeroExchangeRate_ThrowException()
+ {
+ _cacheManager.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>()))
+ .Returns(Task.FromResult(currencyUSD));
+ currencyEUR.Rate = 0;
+ Assert.ThrowsExceptionAsync<GrandException>(async () =>
+ await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR));
+ }
+
+ [TestMethod]
+ public void ConvertToPrimaryExchangeRateCurrency_CannotLoadPrimaryExchange_ThrowException()
+ {
+ _cacheManager.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>()))
+ .Returns(Task.FromResult<Currency>(null));
+ Assert.ThrowsExceptionAsync<Exception>(async () =>
+ await _currencyService.ConvertToPrimaryExchangeRateCurrency(100, currencyEUR));
+ }
+
+ [TestMethod]
+ public async Task GetPrimaryStoreCurrency_ReturnExpectedValue()
+ {
+ _currencySettings.PrimaryStoreCurrencyId = currencyUSD.Id;
+ _cacheManager.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Currency>>>()))
+ .Returns(Task.FromResult(currencyUSD));
+ var result = await _currencyService.GetPrimaryStoreCurrency();
+ Assert.AreEqual(result.Id, currencyUSD.Id);
+ }
+
+ [TestMethod]
+ public async Task InsertCurrency_ValidArgument()
+ {
+ await _currencyService.InsertCurrency(new Currency());
+ tempCurrencyRepository.Verify(c => c.InsertAsync(It.IsAny<Currency>()), Times.Once);
+ tempEventPublisher.Verify(c => c.Publish(It.IsAny<EntityInserted<Currency>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task UpdateCurrency_ValidArgument()
+ {
+ await _currencyService.UpdateCurrency(new Currency());
+ tempCurrencyRepository.Verify(c => c.UpdateAsync(It.IsAny<Currency>()), Times.Once);
+ tempEventPublisher.Verify(c => c.Publish(It.IsAny<EntityUpdated<Currency>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteCurrency_ValidArgument()
+ {
+ await _currencyService.DeleteCurrency(new Currency());
+ tempCurrencyRepository.Verify(c => c.DeleteAsync(It.IsAny<Currency>()), Times.Once);
+ tempEventPublisher.Verify(c => c.Publish(It.IsAny<EntityDeleted<Currency>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Directory/DateTimeServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Directory/DateTimeServiceTests.cs
index 235acf3a3..e40359492 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Directory/DateTimeServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Directory/DateTimeServiceTests.cs
@@ -2,57 +2,55 @@
using Grand.Domain.Directory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Common.Tests.Services.Directory
+namespace Grand.Business.Common.Tests.Services.Directory;
+
+[TestClass]
+public class DateTimeServiceTests
{
- [TestClass()]
- public class DateTimeServiceTests
+ private DateTimeService _dateTimeService;
+ private DateTimeSettings _dateTimeSettings;
+ private TimeZoneInfo _timeZone;
+
+ [TestInitialize]
+ public void TestInitialize()
+ {
+ _timeZone = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(x => x.BaseUtcOffset.Hours == 1);
+
+ _dateTimeSettings = new DateTimeSettings {
+ DefaultStoreTimeZoneId = _timeZone.Id
+ };
+ _dateTimeService = new DateTimeService(_dateTimeSettings);
+ }
+
+ [TestMethod]
+ public void FindTimeZoneByIdTest()
+ {
+ var timezone = _dateTimeService.FindTimeZoneById(_dateTimeSettings.DefaultStoreTimeZoneId);
+ Assert.IsNotNull(timezone);
+ }
+
+ [TestMethod]
+ public void GetSystemTimeZonesTest()
{
- private DateTimeService _dateTimeService;
- private DateTimeSettings _dateTimeSettings;
- private TimeZoneInfo _timeZone;
- [TestInitialize()]
- public void TestInitialize()
- {
-
- _timeZone = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(x => x.BaseUtcOffset.Hours == 1);
-
- _dateTimeSettings = new DateTimeSettings {
- DefaultStoreTimeZoneId = _timeZone.Id
- };
- _dateTimeService = new DateTimeService(_dateTimeSettings);
- }
-
- [TestMethod()]
- public void FindTimeZoneByIdTest()
- {
- var timezone = _dateTimeService.FindTimeZoneById(_dateTimeSettings.DefaultStoreTimeZoneId);
- Assert.IsNotNull(timezone);
- }
-
- [TestMethod()]
- public void GetSystemTimeZonesTest()
- {
- var timezones = _dateTimeService.GetSystemTimeZones();
- Assert.IsTrue(timezones.Any());
- }
-
- [TestMethod()]
- [Ignore]
- public void ConvertToUserTimeTest()
- {
- var usertime = _dateTimeService.ConvertToUserTime(new DateTime(01, 01, 01, 01, 00, 00, DateTimeKind.Utc));
- Assert.IsNotNull(usertime);
- //TODO Assert.AreEqual(new DateTime(01, 01, 01, 02, 00, 00), usertime);
- }
-
- [TestMethod()]
- [Ignore]
- public void ConvertToUtcTimeTest()
- {
- var usertime = _dateTimeService.ConvertToUtcTime(new DateTime(01, 01, 01, 02, 00, 00), _timeZone);
- Assert.IsNotNull(usertime);
- //TODO Assert.AreEqual(new DateTime(01, 01, 01, 01, 00, 00), usertime);
- }
+ var timezones = _dateTimeService.GetSystemTimeZones();
+ Assert.IsTrue(timezones.Any());
+ }
+ [TestMethod]
+ [Ignore]
+ public void ConvertToUserTimeTest()
+ {
+ var usertime = _dateTimeService.ConvertToUserTime(new DateTime(01, 01, 01, 01, 00, 00, DateTimeKind.Utc));
+ Assert.IsNotNull(usertime);
+ //TODO Assert.AreEqual(new DateTime(01, 01, 01, 02, 00, 00), usertime);
+ }
+
+ [TestMethod]
+ [Ignore]
+ public void ConvertToUtcTimeTest()
+ {
+ var usertime = _dateTimeService.ConvertToUtcTime(new DateTime(01, 01, 01, 02, 00, 00), _timeZone);
+ Assert.IsNotNull(usertime);
+ //TODO Assert.AreEqual(new DateTime(01, 01, 01, 01, 00, 00), usertime);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Directory/ExchangeRateServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Directory/ExchangeRateServiceTests.cs
index 3f328185a..01ed8a007 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Directory/ExchangeRateServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Directory/ExchangeRateServiceTests.cs
@@ -1,42 +1,43 @@
-using Grand.Business.Core.Interfaces.Common.Providers;
-using Grand.Business.Common.Services.Directory;
+using Grand.Business.Common.Services.Directory;
+using Grand.Business.Core.Interfaces.Common.Providers;
using Grand.Domain.Directory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Directory
+namespace Grand.Business.Common.Tests.Services.Directory;
+
+[TestClass]
+public class ExchangeRateServiceTests
{
- [TestClass()]
- public class ExchangeRateServiceTests
- {
- private CurrencySettings _settings;
+ private CurrencySettings _settings;
- [TestInitialize()]
- public void Init()
- {
- _settings = new CurrencySettings();
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _settings = new CurrencySettings();
+ }
- [TestMethod()]
- public async Task GetCurrencyLiveRates_InvokeExpectedMethod()
- {
- var provider = new Mock<IExchangeRateProvider>();
- provider.Setup(c => c.SystemName).Returns("sysname");
- _settings.ActiveExchangeRateProviderSystemName = "sysname";
- var exchangeRateService = new ExchangeRateService(new List<IExchangeRateProvider> { provider.Object }, _settings);
- await exchangeRateService.GetCurrencyLiveRates("rate");
- provider.Verify(c => c.GetCurrencyLiveRates(It.IsAny<string>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GetCurrencyLiveRates_InvokeExpectedMethod()
+ {
+ var provider = new Mock<IExchangeRateProvider>();
+ provider.Setup(c => c.SystemName).Returns("sysname");
+ _settings.ActiveExchangeRateProviderSystemName = "sysname";
+ var exchangeRateService =
+ new ExchangeRateService(new List<IExchangeRateProvider> { provider.Object }, _settings);
+ await exchangeRateService.GetCurrencyLiveRates("rate");
+ provider.Verify(c => c.GetCurrencyLiveRates(It.IsAny<string>()), Times.Once);
+ }
- [TestMethod()]
- public void LoadBySystemName_ReturnExpectedValue()
- {
- var provider = new Mock<IExchangeRateProvider>();
- provider.Setup(c => c.SystemName).Returns("sysname");
- var exchangeRateService = new ExchangeRateService(new List<IExchangeRateProvider> { provider.Object }, _settings);
- var result = exchangeRateService.LoadExchangeRateProviderBySystemName("sysname");
- Assert.IsNotNull(result);
- Assert.AreEqual(result.SystemName, "sysname");
- }
+ [TestMethod]
+ public void LoadBySystemName_ReturnExpectedValue()
+ {
+ var provider = new Mock<IExchangeRateProvider>();
+ provider.Setup(c => c.SystemName).Returns("sysname");
+ var exchangeRateService =
+ new ExchangeRateService(new List<IExchangeRateProvider> { provider.Object }, _settings);
+ var result = exchangeRateService.LoadExchangeRateProviderBySystemName("sysname");
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.SystemName, "sysname");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Directory/GroupServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Directory/GroupServiceTests.cs
index db8ee436d..eb69d74ca 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Directory/GroupServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Directory/GroupServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Common.Services.Directory;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,208 +9,213 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Directory
+namespace Grand.Business.Common.Tests.Services.Directory;
+
+[TestClass]
+public class GroupServiceTests
{
- [TestClass()]
- public class GroupServiceTests
+ private MemoryCacheBase _cacheBase;
+
+ private GroupService _groupService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CustomerGroup> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<CustomerGroup>();
+
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _groupService = new GroupService(_repository, _cacheBase, _mediatorMock.Object);
+ }
+
+
+ [TestMethod]
+ public async Task GetCustomerGroupByIdTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup();
+ await _repository.InsertAsync(customerGroup);
+ //Act
+ var result = await _groupService.GetCustomerGroupById(customerGroup.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerGroupBySystemNameTest()
+ {
+ //Arrange
+ const string systemName = "system";
+ var customerGroup = new CustomerGroup { SystemName = systemName };
+ await _repository.InsertAsync(customerGroup);
+ //Act
+ var result = await _groupService.GetCustomerGroupBySystemName(systemName);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetAllCustomerGroupsTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup { Active = true };
+ await _repository.InsertAsync(customerGroup);
+ //Act
+ var result = await _groupService.GetAllCustomerGroups();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerGroupTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup();
+ //Act
+ await _groupService.InsertCustomerGroup(customerGroup);
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerGroupTest()
+ {
+ //Arrange
+ const string systemName = "system";
+ var customerGroup = new CustomerGroup();
+ await _groupService.InsertCustomerGroup(customerGroup);
+ //Act
+ customerGroup.SystemName = systemName;
+ await _groupService.UpdateCustomerGroup(customerGroup);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == customerGroup.Id).SystemName == systemName);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerGroupTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup();
+ await _groupService.InsertCustomerGroup(customerGroup);
+ //Act
+ await _groupService.DeleteCustomerGroup(customerGroup);
+ //Assert
+ Assert.IsFalse(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task IsStaffTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup
+ { IsSystem = true, SystemName = SystemCustomerGroupNames.Staff, Active = true };
+ await _groupService.InsertCustomerGroup(customerGroup);
+ var customer = new Customer();
+ customer.Groups.Add(customerGroup.Id);
+ //Act
+ var result = await _groupService.IsStaff(customer);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task IsAdminTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup
+ { IsSystem = true, SystemName = SystemCustomerGroupNames.Administrators, Active = true };
+ await _groupService.InsertCustomerGroup(customerGroup);
+ var customer = new Customer();
+ customer.Groups.Add(customerGroup.Id);
+ //Act
+ var result = await _groupService.IsAdmin(customer);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task IsSalesManagerTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup
+ { IsSystem = true, SystemName = SystemCustomerGroupNames.SalesManager, Active = true };
+ await _groupService.InsertCustomerGroup(customerGroup);
+ var customer = new Customer();
+ customer.Groups.Add(customerGroup.Id);
+ //Act
+ var result = await _groupService.IsSalesManager(customer);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task IsVendorTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup
+ { IsSystem = true, SystemName = SystemCustomerGroupNames.Vendors, Active = true };
+ await _groupService.InsertCustomerGroup(customerGroup);
+ var customer = new Customer();
+ customer.Groups.Add(customerGroup.Id);
+ //Act
+ var result = await _groupService.IsVendor(customer);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task IsOwnerTest()
+ {
+ //Arrange
+ var customer = new Customer { OwnerId = "" };
+ //Act
+ var result = await _groupService.IsOwner(customer);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task IsGuestTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup
+ { IsSystem = true, SystemName = SystemCustomerGroupNames.Guests, Active = true };
+ await _groupService.InsertCustomerGroup(customerGroup);
+ var customer = new Customer();
+ customer.Groups.Add(customerGroup.Id);
+ //Act
+ var result = await _groupService.IsGuest(customer);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task IsRegisteredTest()
+ {
+ //Arrange
+ var customerGroup = new CustomerGroup
+ { IsSystem = true, SystemName = SystemCustomerGroupNames.Registered, Active = true };
+ await _groupService.InsertCustomerGroup(customerGroup);
+ var customer = new Customer();
+ customer.Groups.Add(customerGroup.Id);
+ //Act
+ var result = await _groupService.IsRegistered(customer);
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task GetAllByIdsTest()
{
- private IRepository<CustomerGroup> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- private GroupService _groupService;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<CustomerGroup>();
-
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _groupService = new GroupService(_repository, _cacheBase, _mediatorMock.Object);
- }
-
-
- [TestMethod()]
- public async Task GetCustomerGroupByIdTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup();
- await _repository.InsertAsync(customerGroup);
- //Act
- var result = await _groupService.GetCustomerGroupById(customerGroup.Id);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCustomerGroupBySystemNameTest()
- {
- //Arrange
- const string systemName = "system";
- var customerGroup = new CustomerGroup { SystemName = systemName };
- await _repository.InsertAsync(customerGroup);
- //Act
- var result = await _groupService.GetCustomerGroupBySystemName(systemName);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetAllCustomerGroupsTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup { Active = true };
- await _repository.InsertAsync(customerGroup);
- //Act
- var result = await _groupService.GetAllCustomerGroups();
- //Assert
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public async Task InsertCustomerGroupTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup();
- //Act
- await _groupService.InsertCustomerGroup(customerGroup);
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCustomerGroupTest()
- {
- //Arrange
- const string systemName = "system";
- var customerGroup = new CustomerGroup();
- await _groupService.InsertCustomerGroup(customerGroup);
- //Act
- customerGroup.SystemName = systemName;
- await _groupService.UpdateCustomerGroup(customerGroup);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x=>x.Id == customerGroup.Id).SystemName == systemName);
- }
-
- [TestMethod()]
- public async Task DeleteCustomerGroupTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup();
- await _groupService.InsertCustomerGroup(customerGroup);
- //Act
- await _groupService.DeleteCustomerGroup(customerGroup);
- //Assert
- Assert.IsFalse(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task IsStaffTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup { IsSystem = true, SystemName = SystemCustomerGroupNames.Staff, Active = true };
- await _groupService.InsertCustomerGroup(customerGroup);
- var customer = new Customer();
- customer.Groups.Add(customerGroup.Id);
- //Act
- var result = await _groupService.IsStaff(customer);
- //Assert
- Assert.IsTrue(result);
-
- }
-
- [TestMethod()]
- public async Task IsAdminTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup { IsSystem = true, SystemName = SystemCustomerGroupNames.Administrators, Active = true };
- await _groupService.InsertCustomerGroup(customerGroup);
- var customer = new Customer();
- customer.Groups.Add(customerGroup.Id);
- //Act
- var result = await _groupService.IsAdmin(customer);
- //Assert
- Assert.IsTrue(result);
-
- }
-
- [TestMethod()]
- public async Task IsSalesManagerTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup { IsSystem = true, SystemName = SystemCustomerGroupNames.SalesManager, Active = true };
- await _groupService.InsertCustomerGroup(customerGroup);
- var customer = new Customer();
- customer.Groups.Add(customerGroup.Id);
- //Act
- var result = await _groupService.IsSalesManager(customer);
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task IsVendorTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup { IsSystem = true, SystemName = SystemCustomerGroupNames.Vendors, Active = true };
- await _groupService.InsertCustomerGroup(customerGroup);
- var customer = new Customer();
- customer.Groups.Add(customerGroup.Id);
- //Act
- var result = await _groupService.IsVendor(customer);
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task IsOwnerTest()
- {
- //Arrange
- var customer = new Customer { OwnerId = ""};
- //Act
- var result = await _groupService.IsOwner(customer);
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task IsGuestTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup { IsSystem = true, SystemName = SystemCustomerGroupNames.Guests, Active = true };
- await _groupService.InsertCustomerGroup(customerGroup);
- var customer = new Customer();
- customer.Groups.Add(customerGroup.Id);
- //Act
- var result = await _groupService.IsGuest(customer);
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task IsRegisteredTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup { IsSystem = true, SystemName = SystemCustomerGroupNames.Registered, Active = true };
- await _groupService.InsertCustomerGroup(customerGroup);
- var customer = new Customer();
- customer.Groups.Add(customerGroup.Id);
- //Act
- var result = await _groupService.IsRegistered(customer);
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task GetAllByIdsTest()
- {
- //Arrange
- var customerGroup = new CustomerGroup();
- await _repository.InsertAsync(customerGroup);
- //Act
- var result = await _groupService.GetAllByIds([customerGroup.Id]);
- //Assert
- Assert.AreEqual(1, result.Count);
- }
+ //Arrange
+ var customerGroup = new CustomerGroup();
+ await _repository.InsertAsync(customerGroup);
+ //Act
+ var result = await _groupService.GetAllByIds([customerGroup.Id]);
+ //Assert
+ Assert.AreEqual(1, result.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Directory/HistoryServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Directory/HistoryServiceTests.cs
index d93fc6a5b..e3fa5197d 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Directory/HistoryServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Directory/HistoryServiceTests.cs
@@ -1,39 +1,39 @@
-using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Common.Services.Directory;
-using Grand.Domain.Catalog;
+using Grand.Business.Common.Services.Directory;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.History;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Directory
-{
- [TestClass()]
- public class HistoryServiceTests
- {
- private Mock<IRepository<HistoryObject>> _mockHistoryRepository;
- private IHistoryService _historyService;
+namespace Grand.Business.Common.Tests.Services.Directory;
- [TestInitialize()]
- public void Init()
- {
- _mockHistoryRepository = new Mock<IRepository<HistoryObject>>();
- _historyService = new HistoryService(_mockHistoryRepository.Object);
- }
+[TestClass]
+public class HistoryServiceTests
+{
+ private IHistoryService _historyService;
+ private Mock<IRepository<HistoryObject>> _mockHistoryRepository;
- [TestMethod()]
- public void SaveObject_NullObject_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _historyService.SaveObject<Product>(null), "entity");
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _mockHistoryRepository = new Mock<IRepository<HistoryObject>>();
+ _historyService = new HistoryService(_mockHistoryRepository.Object);
+ }
- [TestMethod()]
- public async Task SaveObject_InvokeRepositoryWithCorrectObject()
- {
- var product = new Product { Id = "1" };
- await _historyService.SaveObject<Product>(product);
- _mockHistoryRepository.Verify(c => c.InsertAsync(It.Is<HistoryObject>(h => h.Object.Id.Equals(product.Id))), Times.Once);
- }
+ [TestMethod]
+ public void SaveObject_NullObject_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _historyService.SaveObject<Product>(null),
+ "entity");
+ }
+ [TestMethod]
+ public async Task SaveObject_InvokeRepositoryWithCorrectObject()
+ {
+ var product = new Product { Id = "1" };
+ await _historyService.SaveObject(product);
+ _mockHistoryRepository.Verify(c => c.InsertAsync(It.Is<HistoryObject>(h => h.Object.Id.Equals(product.Id))),
+ Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Directory/UserFieldServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Directory/UserFieldServiceTests.cs
index f1c554a73..7795d28d3 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Directory/UserFieldServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Directory/UserFieldServiceTests.cs
@@ -1,73 +1,73 @@
using Grand.Business.Common.Services.Directory;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Common;
using Grand.Domain.Customers;
-using Grand.Data;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongoDB.Bson.Serialization.Conventions;
-namespace Grand.Business.Common.Tests.Services.Directory
+namespace Grand.Business.Common.Tests.Services.Directory;
+
+[TestClass]
+public class UserFieldServiceTests
{
- [TestClass()]
- public class UserFieldServiceTests
+ private IRepository<UserFieldBaseEntity> _repository;
+ private IRepository<Customer> _repositoryCustomer;
+ private UserFieldService _userFieldService;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<UserFieldBaseEntity> _repository;
- private IRepository<Customer> _repositoryCustomer;
- private UserFieldService _userFieldService;
+ //global set an equivalent of [BsonIgnoreExtraElements] for every Domain Model
+ var cp = new ConventionPack {
+ new IgnoreExtraElementsConvention(true)
+ };
+ ConventionRegistry.Register("ApplicationConventions", cp, t => true);
- [TestInitialize()]
- public void Init()
- {
- //global set an equivalent of [BsonIgnoreExtraElements] for every Domain Model
- var cp = new ConventionPack {
- new IgnoreExtraElementsConvention(true)
- };
- ConventionRegistry.Register("ApplicationConventions", cp, t => true);
+ _repository = new MongoDBRepositoryTest<UserFieldBaseEntity>();
+ _repositoryCustomer = new MongoDBRepositoryTest<Customer>();
+ _userFieldService = new UserFieldService(_repository);
+ }
- _repository = new MongoDBRepositoryTest<UserFieldBaseEntity>();
- _repositoryCustomer = new MongoDBRepositoryTest<Customer>();
- _userFieldService = new UserFieldService(_repository);
- }
+ [TestMethod]
+ public async Task SaveFieldTest_Insert()
+ {
+ //Arrange
+ var customer = new Customer();
+ _repositoryCustomer.Insert(customer);
+ //Act
+ await _userFieldService.SaveField(customer, "Field", "Value");
+ //Assert
+ var userFields = _repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).UserFields;
+ Assert.IsNotNull(userFields.FirstOrDefault(x => x.Key == "Field"));
+ }
- [TestMethod()]
- public async Task SaveFieldTest_Insert()
- {
- //Arrange
- var customer = new Customer();
- _repositoryCustomer.Insert(customer);
- //Act
- await _userFieldService.SaveField(customer, "Field", "Value");
- //Assert
- var userFields = _repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).UserFields;
- Assert.IsNotNull(userFields.FirstOrDefault(x => x.Key == "Field"));
- }
- [TestMethod()]
- public async Task SaveFieldTest_Update()
- {
- //Arrange
- var customer = new Customer();
- customer.UserFields.Add(new UserField { Key = "Field", Value = "empty", StoreId = "" });
- _repositoryCustomer.Insert(customer);
- //Act
- await _userFieldService.SaveField(customer, "Field", "Value");
- //Assert
- var userFields = _repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).UserFields;
- Assert.IsNotNull(userFields.FirstOrDefault(x => x.Key == "Field"));
- Assert.AreEqual("Value", userFields.FirstOrDefault(x => x.Key == "Field").Value);
- }
- [TestMethod()]
- public async Task SaveFieldTest_Delete()
- {
- //Arrange
- var customer = new Customer();
- customer.UserFields.Add(new UserField { Key = "Field", Value = "Value", StoreId = "" });
- _repositoryCustomer.Insert(customer);
- //Act
- await _userFieldService.SaveField(customer, "Field", String.Empty);
- //Assert
- var userFields = _repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).UserFields;
- Assert.IsNull(userFields.FirstOrDefault(x => x.Key == "Field"));
- }
-
+ [TestMethod]
+ public async Task SaveFieldTest_Update()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.UserFields.Add(new UserField { Key = "Field", Value = "empty", StoreId = "" });
+ _repositoryCustomer.Insert(customer);
+ //Act
+ await _userFieldService.SaveField(customer, "Field", "Value");
+ //Assert
+ var userFields = _repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).UserFields;
+ Assert.IsNotNull(userFields.FirstOrDefault(x => x.Key == "Field"));
+ Assert.AreEqual("Value", userFields.FirstOrDefault(x => x.Key == "Field").Value);
+ }
+
+ [TestMethod]
+ public async Task SaveFieldTest_Delete()
+ {
+ //Arrange
+ var customer = new Customer();
+ customer.UserFields.Add(new UserField { Key = "Field", Value = "Value", StoreId = "" });
+ _repositoryCustomer.Insert(customer);
+ //Act
+ await _userFieldService.SaveField(customer, "Field", string.Empty);
+ //Assert
+ var userFields = _repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).UserFields;
+ Assert.IsNull(userFields.FirstOrDefault(x => x.Key == "Field"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/ExportImport/CountryImportDataObjectTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/ExportImport/CountryImportDataObjectTests.cs
index cb3138a5a..f0676c454 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/ExportImport/CountryImportDataObjectTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/ExportImport/CountryImportDataObjectTests.cs
@@ -2,8 +2,8 @@
using Grand.Business.Common.Services.ExportImport;
using Grand.Business.Core.Dto;
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Directory;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -12,89 +12,105 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.ExportImport
-{
- [TestClass()]
- public class CountryImportDataObjectTests
- {
- private CountryImportDataObject _countryImportDataObject;
- private ICountryService _countryService;
+namespace Grand.Business.Common.Tests.Services.ExportImport;
- private IRepository<Country> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Country>();
+[TestClass]
+public class CountryImportDataObjectTests
+{
+ private MemoryCacheBase _cacheBase;
+ private CountryImportDataObject _countryImportDataObject;
+ private ICountryService _countryService;
+ private Mock<IMediator> _mediatorMock;
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- var accessControlConfig = new AccessControlConfig();
- _countryService = new CountryService(_repository, _mediatorMock.Object, _cacheBase, accessControlConfig);
- _countryImportDataObject = new CountryImportDataObject(_countryService);
- }
+ private IRepository<Country> _repository;
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert_NewStates()
- {
- //Arrange
- var country = new Country { TwoLetterIsoCode = "US", Name = "USA" };
- await _repository.InsertAsync(country);
- var states = new List<CountryStatesDto> {
- new CountryStatesDto { Country = country.TwoLetterIsoCode, Abbreviation = "AK", StateProvinceName = "Alaska", Published = true },
- new CountryStatesDto { Country = country.TwoLetterIsoCode, Abbreviation = "CA", StateProvinceName = "California", Published = true, DisplayOrder = 1 }
- };
- //Act
- await _countryImportDataObject.Execute(states);
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Country>();
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Any());
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ var accessControlConfig = new AccessControlConfig();
+ _countryService = new CountryService(_repository, _mediatorMock.Object, _cacheBase, accessControlConfig);
+ _countryImportDataObject = new CountryImportDataObject(_countryService);
+ }
- }
- [TestMethod()]
- public async Task ExecuteTest_Import_Update_States()
- {
- //Arrange
- var country = new Country { TwoLetterIsoCode = "US", Name = "USA" };
- country.StateProvinces.Add(new StateProvince { Abbreviation = "AK" });
- country.StateProvinces.Add(new StateProvince { Abbreviation = "CA" });
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert_NewStates()
+ {
+ //Arrange
+ var country = new Country { TwoLetterIsoCode = "US", Name = "USA" };
+ await _repository.InsertAsync(country);
+ var states = new List<CountryStatesDto> {
+ new() {
+ Country = country.TwoLetterIsoCode, Abbreviation = "AK", StateProvinceName = "Alaska", Published = true
+ },
+ new() {
+ Country = country.TwoLetterIsoCode, Abbreviation = "CA", StateProvinceName = "California",
+ Published = true, DisplayOrder = 1
+ }
+ };
+ //Act
+ await _countryImportDataObject.Execute(states);
- await _repository.InsertAsync(country);
- var states = new List<CountryStatesDto> {
- new CountryStatesDto { Country = country.TwoLetterIsoCode, Abbreviation = "AK", StateProvinceName = "Alaska", Published = true },
- new CountryStatesDto { Country = country.TwoLetterIsoCode, Abbreviation = "CA", StateProvinceName = "California", Published = true, DisplayOrder = 1 }
- };
- //Act
- await _countryImportDataObject.Execute(states);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Any());
+ }
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Any(x=>x.Published));
+ [TestMethod]
+ public async Task ExecuteTest_Import_Update_States()
+ {
+ //Arrange
+ var country = new Country { TwoLetterIsoCode = "US", Name = "USA" };
+ country.StateProvinces.Add(new StateProvince { Abbreviation = "AK" });
+ country.StateProvinces.Add(new StateProvince { Abbreviation = "CA" });
- }
+ await _repository.InsertAsync(country);
+ var states = new List<CountryStatesDto> {
+ new() {
+ Country = country.TwoLetterIsoCode, Abbreviation = "AK", StateProvinceName = "Alaska", Published = true
+ },
+ new() {
+ Country = country.TwoLetterIsoCode, Abbreviation = "CA", StateProvinceName = "California",
+ Published = true, DisplayOrder = 1
+ }
+ };
+ //Act
+ await _countryImportDataObject.Execute(states);
- [TestMethod()]
- public async Task ExecuteTest_Import_Insert_Update_States()
- {
- //Arrange
- var country = new Country { TwoLetterIsoCode = "US", Name = "USA" };
- country.StateProvinces.Add(new StateProvince { Abbreviation = "AK" });
- country.StateProvinces.Add(new StateProvince { Abbreviation = "CA" });
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Any(x => x.Published));
+ }
- await _repository.InsertAsync(country);
- var states = new List<CountryStatesDto> {
- new CountryStatesDto { Country = country.TwoLetterIsoCode, Abbreviation = "AK", StateProvinceName = "Alaska", Published = true },
- new CountryStatesDto { Country = country.TwoLetterIsoCode, Abbreviation = "CA", StateProvinceName = "California", Published = true, DisplayOrder = 1 },
- new CountryStatesDto { Country = country.TwoLetterIsoCode, Abbreviation = "HI", StateProvinceName = "Hawaii", Published = true, DisplayOrder = 1 }
- };
- //Act
- await _countryImportDataObject.Execute(states);
+ [TestMethod]
+ public async Task ExecuteTest_Import_Insert_Update_States()
+ {
+ //Arrange
+ var country = new Country { TwoLetterIsoCode = "US", Name = "USA" };
+ country.StateProvinces.Add(new StateProvince { Abbreviation = "AK" });
+ country.StateProvinces.Add(new StateProvince { Abbreviation = "CA" });
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Any(x => x.Published));
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Count == 3);
+ await _repository.InsertAsync(country);
+ var states = new List<CountryStatesDto> {
+ new() {
+ Country = country.TwoLetterIsoCode, Abbreviation = "AK", StateProvinceName = "Alaska", Published = true
+ },
+ new() {
+ Country = country.TwoLetterIsoCode, Abbreviation = "CA", StateProvinceName = "California",
+ Published = true, DisplayOrder = 1
+ },
+ new() {
+ Country = country.TwoLetterIsoCode, Abbreviation = "HI", StateProvinceName = "Hawaii", Published = true,
+ DisplayOrder = 1
+ }
+ };
+ //Act
+ await _countryImportDataObject.Execute(states);
- }
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Any(x => x.Published));
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == country.Id).StateProvinces.Count == 3);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Localization/LanguageServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Localization/LanguageServiceTests.cs
index 7556e971f..73822d204 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Localization/LanguageServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Localization/LanguageServiceTests.cs
@@ -1,6 +1,6 @@
using Grand.Business.Common.Services.Localization;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Localization;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -9,103 +9,102 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Localization
-{
- [TestClass()]
- public class LanguageServiceTests
- {
- private IRepository<Language> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
+namespace Grand.Business.Common.Tests.Services.Localization;
- private LanguageService _languageService;
+[TestClass]
+public class LanguageServiceTests
+{
+ private MemoryCacheBase _cacheBase;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Language>();
+ private LanguageService _languageService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Language> _repository;
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _languageService = new LanguageService(_cacheBase, _repository, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<Language>();
- [TestMethod()]
- public async Task GetAllLanguagesTest()
- {
- //Arrange
- await _repository.InsertAsync(new Language { Published = true });
- await _repository.InsertAsync(new Language { Published = true });
- await _repository.InsertAsync(new Language { Published = true });
- //Act
- var result = await _languageService.GetAllLanguages();
- //Assert
- Assert.AreEqual(3, result.Count);
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _languageService = new LanguageService(_cacheBase, _repository, _mediatorMock.Object);
+ }
- }
+ [TestMethod]
+ public async Task GetAllLanguagesTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new Language { Published = true });
+ await _repository.InsertAsync(new Language { Published = true });
+ await _repository.InsertAsync(new Language { Published = true });
+ //Act
+ var result = await _languageService.GetAllLanguages();
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
- [TestMethod()]
- public async Task GetLanguageByIdTest()
- {
- //Arrange
- var language = new Language { Published = true, Id = "1" };
- await _repository.InsertAsync(language);
- await _repository.InsertAsync(new Language { Published = true });
- await _repository.InsertAsync(new Language { Published = true });
- //Act
- var result = await _languageService.GetLanguageById(language.Id);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetLanguageByIdTest()
+ {
+ //Arrange
+ var language = new Language { Published = true, Id = "1" };
+ await _repository.InsertAsync(language);
+ await _repository.InsertAsync(new Language { Published = true });
+ await _repository.InsertAsync(new Language { Published = true });
+ //Act
+ var result = await _languageService.GetLanguageById(language.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task GetLanguageByCodeTest()
- {
- //Arrange
- var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
- await _repository.InsertAsync(language);
- await _repository.InsertAsync(new Language { Published = true });
- await _repository.InsertAsync(new Language { Published = true });
- //Act
- var result = await _languageService.GetLanguageByCode(language.UniqueSeoCode);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetLanguageByCodeTest()
+ {
+ //Arrange
+ var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
+ await _repository.InsertAsync(language);
+ await _repository.InsertAsync(new Language { Published = true });
+ await _repository.InsertAsync(new Language { Published = true });
+ //Act
+ var result = await _languageService.GetLanguageByCode(language.UniqueSeoCode);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task InsertLanguageTest()
- {
- //Arrange
- var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
- //Act
- await _languageService.InsertLanguage(language);
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == language.Id));
- }
+ [TestMethod]
+ public async Task InsertLanguageTest()
+ {
+ //Arrange
+ var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
+ //Act
+ await _languageService.InsertLanguage(language);
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Id == language.Id));
+ }
- [TestMethod()]
- public async Task UpdateLanguageTest()
- {
- //Arrange
- var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
- await _languageService.InsertLanguage(language);
- //Act
- language.FlagImageFileName = "en.png";
- await _languageService.UpdateLanguage(language);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == language.Id).FlagImageFileName == "en.png");
- }
+ [TestMethod]
+ public async Task UpdateLanguageTest()
+ {
+ //Arrange
+ var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
+ await _languageService.InsertLanguage(language);
+ //Act
+ language.FlagImageFileName = "en.png";
+ await _languageService.UpdateLanguage(language);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == language.Id).FlagImageFileName == "en.png");
+ }
- [TestMethod()]
- public async Task DeleteLanguageTest()
- {
- //Arrange
- var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
- await _languageService.InsertLanguage(language);
- //Act
- await _languageService.DeleteLanguage(language);
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == language.Id));
- }
+ [TestMethod]
+ public async Task DeleteLanguageTest()
+ {
+ //Arrange
+ var language = new Language { Published = true, Id = "1", UniqueSeoCode = "en" };
+ await _languageService.InsertLanguage(language);
+ //Act
+ await _languageService.DeleteLanguage(language);
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == language.Id));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs
index 4f44d5ddd..cdd0751f5 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Localization/TranslationServiceTests.cs
@@ -1,173 +1,184 @@
using Grand.Business.Common.Services.Localization;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Localization;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
-using Grand.Infrastructure.Caching;
-using Grand.Infrastructure.Configuration;
-using Grand.Infrastructure.Tests.Caching;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Localization
+namespace Grand.Business.Common.Tests.Services.Localization;
+
+[TestClass]
+public class TranslationServiceTests
{
- [TestClass()]
- public class TranslationServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<TranslationResource> _repository;
+
+ private TranslationService _translationService;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<TranslationResource>();
+
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store());
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ _workContextMock.Setup(c => c.WorkingLanguage).Returns(() => new Language { Id = "1" });
+
+ _translationService = new TranslationService(_workContextMock.Object, _repository, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetTranslateResourceByIdTest()
+ {
+ //Arrange
+ var translationResource = new TranslationResource { Name = "name", LanguageId = "1", Value = "value" };
+ await _translationService.InsertTranslateResource(translationResource);
+
+ //Act
+ var result = await _translationService.GetTranslateResourceById(translationResource.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetTranslateResourceByNameTest()
+ {
+ //Arrange
+ var translationResource = new TranslationResource { Name = "name", LanguageId = "1" };
+ await _translationService.InsertTranslateResource(translationResource);
+
+ //Act
+ var result =
+ await _translationService.GetTranslateResourceByName(translationResource.Name,
+ translationResource.LanguageId);
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetAllResourcesTest()
+ {
+ //Arrange
+ await _translationService.InsertTranslateResource(new TranslationResource
+ { LanguageId = "1", Name = "test1", Value = "val1" });
+ await _translationService.InsertTranslateResource(new TranslationResource
+ { LanguageId = "1", Name = "test2", Value = "val2" });
+ await _translationService.InsertTranslateResource(new TranslationResource
+ { LanguageId = "2", Name = "test3", Value = "val3" });
+
+ //Act
+ var result = _translationService.GetAllResources("1");
+
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertTranslateResourceTest()
+ {
+ //Arrange
+ var translationResource = new TranslationResource { Name = "name", LanguageId = "1" };
+
+ //Act
+ await _translationService.InsertTranslateResource(translationResource);
+
+ //Assert
+ Assert.AreEqual(1, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task UpdateTranslateResourceTest()
+ {
+ //Arrange
+ var translationResource = new TranslationResource { Name = "name", Value = "value", LanguageId = "1" };
+ await _translationService.InsertTranslateResource(translationResource);
+
+ //Act
+ translationResource.Name = "name2";
+ await _translationService.UpdateTranslateResource(translationResource);
+
+ //Assert
+ Assert.AreEqual(translationResource.Name,
+ _repository.Table.FirstOrDefault(x => x.Id == translationResource.Id).Name);
+ }
+
+ [TestMethod]
+ public async Task DeleteTranslateResourceTest()
+ {
+ //Arrange
+ var translationResource = new TranslationResource { Name = "name", Value = "value", LanguageId = "1" };
+ await _translationService.InsertTranslateResource(translationResource);
+
+ //Act
+ await _translationService.DeleteTranslateResource(translationResource);
+
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetResourceTest()
+ {
+ //Arrange
+ await _translationService.InsertTranslateResource(new TranslationResource
+ { Name = "name1", Value = "value1", LanguageId = "1" });
+ await _translationService.InsertTranslateResource(new TranslationResource
+ { Name = "name2", Value = "value2", LanguageId = "1" });
+ await _translationService.InsertTranslateResource(new TranslationResource
+ { Name = "name3", Value = "value3", LanguageId = "2" });
+
+ //Act
+ var result = _translationService.GetResource("name1");
+
+ //Assert
+ Assert.AreEqual("value1", result);
+ }
+
+
+ [TestMethod]
+ public async Task ExportResourcesToXmlTest()
{
- private IRepository<TranslationResource> _repository;
- private Mock<IMediator> _mediatorMock;
- private Mock<IWorkContext> _workContextMock;
-
- private TranslationService _translationService;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<TranslationResource>();
-
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store());
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- _workContextMock.Setup(c => c.WorkingLanguage).Returns(() => new Language { Id = "1" });
-
- _translationService = new TranslationService(_workContextMock.Object, _repository, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetTranslateResourceByIdTest()
- {
- //Arrange
- var translationResource = new TranslationResource() { Name = "name", LanguageId = "1", Value = "value" };
- await _translationService.InsertTranslateResource(translationResource);
-
- //Act
- var result = await _translationService.GetTranslateResourceById(translationResource.Id);
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetTranslateResourceByNameTest()
- {
- //Arrange
- var translationResource = new TranslationResource { Name = "name", LanguageId = "1" };
- await _translationService.InsertTranslateResource(translationResource);
-
- //Act
- var result = await _translationService.GetTranslateResourceByName(translationResource.Name, translationResource.LanguageId);
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetAllResourcesTest()
- {
- //Arrange
- await _translationService.InsertTranslateResource(new TranslationResource { LanguageId = "1", Name = "test1", Value = "val1"});
- await _translationService.InsertTranslateResource(new TranslationResource { LanguageId = "1", Name = "test2", Value = "val2" });
- await _translationService.InsertTranslateResource(new TranslationResource { LanguageId = "2", Name = "test3", Value = "val3" });
-
- //Act
- var result = _translationService.GetAllResources("1");
-
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task InsertTranslateResourceTest()
- {
- //Arrange
- var translationResource = new TranslationResource { Name = "name", LanguageId = "1" };
-
- //Act
- await _translationService.InsertTranslateResource(translationResource);
-
- //Assert
- Assert.AreEqual(1, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task UpdateTranslateResourceTest()
- {
- //Arrange
- var translationResource = new TranslationResource { Name = "name", Value = "value", LanguageId = "1" };
- await _translationService.InsertTranslateResource(translationResource);
-
- //Act
- translationResource.Name = "name2";
- await _translationService.UpdateTranslateResource(translationResource);
-
- //Assert
- Assert.AreEqual(translationResource.Name, _repository.Table.FirstOrDefault(x=>x.Id == translationResource.Id).Name);
- }
-
- [TestMethod()]
- public async Task DeleteTranslateResourceTest()
- {
- //Arrange
- var translationResource = new TranslationResource { Name = "name", Value = "value", LanguageId = "1" };
- await _translationService.InsertTranslateResource(translationResource);
-
- //Act
- await _translationService.DeleteTranslateResource(translationResource);
-
- //Assert
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetResourceTest()
- {
- //Arrange
- await _translationService.InsertTranslateResource(new TranslationResource { Name = "name1", Value = "value1", LanguageId = "1" });
- await _translationService.InsertTranslateResource(new TranslationResource { Name = "name2", Value = "value2", LanguageId = "1" });
- await _translationService.InsertTranslateResource(new TranslationResource { Name = "name3", Value = "value3", LanguageId = "2" });
-
- //Act
- var result = _translationService.GetResource("name1");
-
- //Assert
- Assert.AreEqual("value1", result);
- }
-
-
- [TestMethod()]
- public async Task ExportResourcesToXmlTest()
- {
- //Arrange
- await _translationService.InsertTranslateResource(new TranslationResource { Name = "name1", Value = "value1", LanguageId = "1" });
-
- //Act
- var result = await _translationService.ExportResourcesToXml(new Language { Id = "1", Name = "en"});
-
- //Assert
- Assert.AreEqual("<?xml version=\"1.0\" encoding=\"utf-16\"?><Language Name=\"en\"><Resource Name=\"name1\" Area=\"Common\"><Value>value1</Value></Resource></Language>", result);
- }
-
- [TestMethod()]
- public async Task ImportResourcesFromXmlTest()
- {
- //Act
- await _translationService.ImportResourcesFromXml(new Language { Id = "1", Name = "en" }, "<?xml version=\"1.0\" encoding=\"utf-16\"?><Language Name=\"en\"><Resource Name=\"name1\" Area=\"Common\"><Value>value1</Value></Resource></Language>");
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task ImportResourcesFromXmlInstallTest()
- {
- //Act
- await _translationService.ImportResourcesFromXmlInstall(new Language { Id = "1", Name = "en" }, "<?xml version=\"1.0\" encoding=\"utf-16\"?><Language Name=\"en\"><Resource Name=\"name1\" Area=\"Common\"><Value>value1</Value></Resource></Language>");
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
+ //Arrange
+ await _translationService.InsertTranslateResource(new TranslationResource
+ { Name = "name1", Value = "value1", LanguageId = "1" });
+
+ //Act
+ var result = await _translationService.ExportResourcesToXml(new Language { Id = "1", Name = "en" });
+
+ //Assert
+ Assert.AreEqual(
+ "<?xml version=\"1.0\" encoding=\"utf-16\"?><Language Name=\"en\"><Resource Name=\"name1\" Area=\"Common\"><Value>value1</Value></Resource></Language>",
+ result);
+ }
+
+ [TestMethod]
+ public async Task ImportResourcesFromXmlTest()
+ {
+ //Act
+ await _translationService.ImportResourcesFromXml(new Language { Id = "1", Name = "en" },
+ "<?xml version=\"1.0\" encoding=\"utf-16\"?><Language Name=\"en\"><Resource Name=\"name1\" Area=\"Common\"><Value>value1</Value></Resource></Language>");
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task ImportResourcesFromXmlInstallTest()
+ {
+ //Act
+ await _translationService.ImportResourcesFromXmlInstall(new Language { Id = "1", Name = "en" },
+ "<?xml version=\"1.0\" encoding=\"utf-16\"?><Language Name=\"en\"><Resource Name=\"name1\" Area=\"Common\"><Value>value1</Value></Resource></Language>");
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Security/AclServiceTest.cs b/src/Tests/Grand.Business.Common.Tests/Services/Security/AclServiceTest.cs
index 87952d8c6..6d48b43ec 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Security/AclServiceTest.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Security/AclServiceTest.cs
@@ -3,43 +3,43 @@ using Grand.Domain.Catalog;
using Grand.Infrastructure.Configuration;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Common.Tests.Services.Security
+namespace Grand.Business.Common.Tests.Services.Security;
+
+[TestClass]
+public class AclServiceTest
{
- [TestClass]
- public class AclServiceTest
+ private AccessControlConfig _accessControlConfig;
+ private AclService _aclService;
+ private CatalogSettings _settings;
+
+ [TestInitialize]
+ public void Init()
{
- private CatalogSettings _settings;
- private AclService _aclService;
- private AccessControlConfig _accessControlConfig;
- [TestInitialize]
- public void Init()
- {
- _settings = new CatalogSettings();
- _accessControlConfig = new AccessControlConfig();
- _aclService = new AclService(_accessControlConfig);
- }
+ _settings = new CatalogSettings();
+ _accessControlConfig = new AccessControlConfig();
+ _aclService = new AclService(_accessControlConfig);
+ }
- [TestMethod]
- public void Authorize_ReturnFalse()
- {
- Product product = null;
- Assert.IsFalse(_aclService.Authorize(product, "id"));
- product = new Product {
- LimitedToStores = true
- };
- Assert.IsFalse(_aclService.Authorize(product, "id"));
- }
+ [TestMethod]
+ public void Authorize_ReturnFalse()
+ {
+ Product product = null;
+ Assert.IsFalse(_aclService.Authorize(product, "id"));
+ product = new Product {
+ LimitedToStores = true
+ };
+ Assert.IsFalse(_aclService.Authorize(product, "id"));
+ }
- [TestMethod]
- public void Authorize_ReturnTrue()
- {
- Product product = new Product {
- LimitedToStores = false
- };
- Assert.IsTrue(_aclService.Authorize(product, "id"));
- Assert.IsTrue(_aclService.Authorize(product, ""));
- _accessControlConfig.IgnoreStoreLimitations = true;
- Assert.IsTrue(_aclService.Authorize(product, "id"));
- }
+ [TestMethod]
+ public void Authorize_ReturnTrue()
+ {
+ var product = new Product {
+ LimitedToStores = false
+ };
+ Assert.IsTrue(_aclService.Authorize(product, "id"));
+ Assert.IsTrue(_aclService.Authorize(product, ""));
+ _accessControlConfig.IgnoreStoreLimitations = true;
+ Assert.IsTrue(_aclService.Authorize(product, "id"));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Security/EncryptionServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Security/EncryptionServiceTests.cs
index 86f0a650b..143fce1cd 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Security/EncryptionServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Security/EncryptionServiceTests.cs
@@ -1,81 +1,81 @@
using Grand.Business.Common.Services.Security;
+using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Common.Tests.Services.Security
+namespace Grand.Business.Common.Tests.Services.Security;
+
+[TestClass]
+public class EncryptionServiceTests
{
- [TestClass()]
- public class EncryptionServiceTests
- {
- private EncryptionService _encryptionService;
+ private EncryptionService _encryptionService;
- [TestInitialize]
- public void Init()
- {
- _encryptionService = new EncryptionService();
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _encryptionService = new EncryptionService();
+ }
- [TestMethod()]
- public void CreateSaltKey_ReturnOthersSaltWithSpecificSize()
- {
- var size = 32;
- var salt1 = _encryptionService.CreateSaltKey(size);
- var salt2 = _encryptionService.CreateSaltKey(size);
- Assert.AreNotEqual(salt1, salt2);
- Assert.IsTrue(Convert.FromBase64String(salt1).Length.Equals(size));
- Assert.IsTrue(Convert.FromBase64String(salt2).Length.Equals(size));
- }
+ [TestMethod]
+ public void CreateSaltKey_ReturnOthersSaltWithSpecificSize()
+ {
+ var size = 32;
+ var salt1 = _encryptionService.CreateSaltKey(size);
+ var salt2 = _encryptionService.CreateSaltKey(size);
+ Assert.AreNotEqual(salt1, salt2);
+ Assert.IsTrue(Convert.FromBase64String(salt1).Length.Equals(size));
+ Assert.IsTrue(Convert.FromBase64String(salt2).Length.Equals(size));
+ }
- [TestMethod]
- public void CreatePasswordHash_InvokeWithTheSameArguemtns_ReturnTheSameValue()
- {
- var password = "password";
- var salt = _encryptionService.CreateSaltKey(32);
- var hash1 = _encryptionService.CreatePasswordHash(password, salt);
- var hash2 = _encryptionService.CreatePasswordHash(password, salt);
- var hash3 = _encryptionService.CreatePasswordHash(password, salt, Domain.Customers.HashedPasswordFormat.SHA384);
- var hash4 = _encryptionService.CreatePasswordHash(password, salt, Domain.Customers.HashedPasswordFormat.SHA384);
- var hash5 = _encryptionService.CreatePasswordHash(password, salt, Domain.Customers.HashedPasswordFormat.SHA512);
- Assert.AreEqual(hash1, hash2);
- Assert.AreEqual(hash3, hash4);
- Assert.AreNotEqual(hash4, hash5);
- }
+ [TestMethod]
+ public void CreatePasswordHash_InvokeWithTheSameArguemtns_ReturnTheSameValue()
+ {
+ var password = "password";
+ var salt = _encryptionService.CreateSaltKey(32);
+ var hash1 = _encryptionService.CreatePasswordHash(password, salt);
+ var hash2 = _encryptionService.CreatePasswordHash(password, salt);
+ var hash3 = _encryptionService.CreatePasswordHash(password, salt, HashedPasswordFormat.SHA384);
+ var hash4 = _encryptionService.CreatePasswordHash(password, salt, HashedPasswordFormat.SHA384);
+ var hash5 = _encryptionService.CreatePasswordHash(password, salt, HashedPasswordFormat.SHA512);
+ Assert.AreEqual(hash1, hash2);
+ Assert.AreEqual(hash3, hash4);
+ Assert.AreNotEqual(hash4, hash5);
+ }
- [TestMethod()]
- public void EncryptText_TheSameKeyAndText_ReturnTheSameValues()
- {
- var privateKey = "secure key..............";
- var toEncrypte = "text to encrypte...";
- var encrypted1 = _encryptionService.EncryptText(toEncrypte, privateKey);
- var encrypted2 = _encryptionService.EncryptText(toEncrypte, privateKey);
- var encrypted3 = _encryptionService.EncryptText(toEncrypte, "7ecure key..............");
- Assert.AreEqual(encrypted2, encrypted1);
- Assert.AreNotEqual(encrypted2, encrypted3);
- }
+ [TestMethod]
+ public void EncryptText_TheSameKeyAndText_ReturnTheSameValues()
+ {
+ var privateKey = "secure key..............";
+ var toEncrypte = "text to encrypte...";
+ var encrypted1 = _encryptionService.EncryptText(toEncrypte, privateKey);
+ var encrypted2 = _encryptionService.EncryptText(toEncrypte, privateKey);
+ var encrypted3 = _encryptionService.EncryptText(toEncrypte, "7ecure key..............");
+ Assert.AreEqual(encrypted2, encrypted1);
+ Assert.AreNotEqual(encrypted2, encrypted3);
+ }
- [TestMethod()]
- public void EncryptText_InvalidPrivateKeyLength_ThrowException()
- {
- var privateKey = "secure key.";
- var toEncrypte = "text to encrypte...";
- Assert.ThrowsException<Exception>(() => _encryptionService.EncryptText(toEncrypte, privateKey));
- }
+ [TestMethod]
+ public void EncryptText_InvalidPrivateKeyLength_ThrowException()
+ {
+ var privateKey = "secure key.";
+ var toEncrypte = "text to encrypte...";
+ Assert.ThrowsException<Exception>(() => _encryptionService.EncryptText(toEncrypte, privateKey));
+ }
- [TestMethod()]
- public void DecryptText_ReturnExpectedResult()
- {
- var privateKey = "secure key..............";
- var toEncrypte = "text to encrypte...";
- var encrypted1 = _encryptionService.EncryptText(toEncrypte, privateKey);
- var decrypt = _encryptionService.DecryptText(encrypted1, privateKey);
- Assert.AreEqual(decrypt, toEncrypte);
- }
+ [TestMethod]
+ public void DecryptText_ReturnExpectedResult()
+ {
+ var privateKey = "secure key..............";
+ var toEncrypte = "text to encrypte...";
+ var encrypted1 = _encryptionService.EncryptText(toEncrypte, privateKey);
+ var decrypt = _encryptionService.DecryptText(encrypted1, privateKey);
+ Assert.AreEqual(decrypt, toEncrypte);
+ }
- [TestMethod()]
- public void DecryptText_InvalidPrivateKeyLength_ThrowException()
- {
- var privateKey = "secure key.";
- var toDescrypt = "gdfgdfgt45gfdfg";
- Assert.ThrowsException<Exception>(() => _encryptionService.DecryptText(toDescrypt, privateKey));
- }
+ [TestMethod]
+ public void DecryptText_InvalidPrivateKeyLength_ThrowException()
+ {
+ var privateKey = "secure key.";
+ var toDescrypt = "gdfgdfgt45gfdfg";
+ Assert.ThrowsException<Exception>(() => _encryptionService.DecryptText(toDescrypt, privateKey));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs
index 18b8353ca..b92003dc7 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Security/PermissionServiceTests.cs
@@ -1,100 +1,104 @@
using Grand.Business.Common.Services.Security;
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Domain.Permissions;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Security
+namespace Grand.Business.Common.Tests.Services.Security;
+
+[TestClass]
+public class PermissionServiceTests
{
- [TestClass()]
- public class PermissionServiceTests
- {
- private Mock<IRepository<Permission>> _permissionRepositoryMock;
- private Mock<IRepository<PermissionAction>> _permissionActionRepositoryMock;
- private Mock<IWorkContext> _workContextMock;
- private Mock<IGroupService> _groupServiceMock;
- private Mock<ICacheBase> _cacheMock;
- private PermissionService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IGroupService> _groupServiceMock;
+ private Mock<IRepository<PermissionAction>> _permissionActionRepositoryMock;
+ private Mock<IRepository<Permission>> _permissionRepositoryMock;
+ private PermissionService _service;
+ private Mock<IWorkContext> _workContextMock;
- [TestInitialize()]
- public void Init()
- {
- _permissionRepositoryMock = new Mock<IRepository<Permission>>();
- _permissionActionRepositoryMock = new Mock<IRepository<PermissionAction>>();
- _workContextMock = new Mock<IWorkContext>();
- _groupServiceMock = new Mock<IGroupService>();
- _cacheMock = new Mock<ICacheBase>();
- _service = new PermissionService(_permissionRepositoryMock.Object, _permissionActionRepositoryMock.Object, _workContextMock.Object,
- _groupServiceMock.Object, _cacheMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _permissionRepositoryMock = new Mock<IRepository<Permission>>();
+ _permissionActionRepositoryMock = new Mock<IRepository<PermissionAction>>();
+ _workContextMock = new Mock<IWorkContext>();
+ _groupServiceMock = new Mock<IGroupService>();
+ _cacheMock = new Mock<ICacheBase>();
+ _service = new PermissionService(_permissionRepositoryMock.Object, _permissionActionRepositoryMock.Object,
+ _workContextMock.Object,
+ _groupServiceMock.Object, _cacheMock.Object);
+ }
- [TestMethod]
- public async Task Authorize_ReturnTrue()
- {
- Permission permission = new Permission { SystemName = "permistion" };
- var fakeCustomer = new Customer();
- fakeCustomer.Groups.Add("group1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(fakeCustomer);
- _cacheMock.Setup(c => c.GetAsync<bool>(It.IsAny<string>(), It.IsAny<Func<Task<bool>>>())).Returns(Task.FromResult(true));
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>())).Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup> { new CustomerGroup() }));
- Assert.IsTrue(await _service.Authorize(permission));
- }
+ [TestMethod]
+ public async Task Authorize_ReturnTrue()
+ {
+ var permission = new Permission { SystemName = "permistion" };
+ var fakeCustomer = new Customer();
+ fakeCustomer.Groups.Add("group1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(fakeCustomer);
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<bool>>>()))
+ .Returns(Task.FromResult(true));
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup> { new() }));
+ Assert.IsTrue(await _service.Authorize(permission));
+ }
- [TestMethod()]
- public async Task Authorize_NullPermission_ReturnFalse()
- {
- Permission permission = null;
- var fakeCustomer = new Customer();
- fakeCustomer.Groups.Add("group1");
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(fakeCustomer);
- _cacheMock.Setup(c => c.GetAsync<bool>(It.IsAny<string>(), It.IsAny<Func<Task<bool>>>())).Returns(Task.FromResult(true));
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>())).Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup> { new CustomerGroup() }));
- Assert.IsFalse(await _service.Authorize(permission));
- }
+ [TestMethod]
+ public async Task Authorize_NullPermission_ReturnFalse()
+ {
+ Permission permission = null;
+ var fakeCustomer = new Customer();
+ fakeCustomer.Groups.Add("group1");
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(fakeCustomer);
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<bool>>>()))
+ .Returns(Task.FromResult(true));
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(new List<CustomerGroup> { new() }));
+ Assert.IsFalse(await _service.Authorize(permission));
+ }
- [TestMethod]
- public async Task InsertPermission_InovokeMethods()
- {
- await _service.InsertPermission(new Permission());
- _permissionRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Permission>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertPermission_InovokeMethods()
+ {
+ await _service.InsertPermission(new Permission());
+ _permissionRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Permission>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public async Task DeletePermission_InovokeMethods()
- {
- await _service.DeletePermission(new Permission());
- _permissionRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Permission>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task DeletePermission_InovokeMethods()
+ {
+ await _service.DeletePermission(new Permission());
+ _permissionRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Permission>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public async Task UpdatePermission_InovokeMethods()
- {
- await _service.UpdatePermission(new Permission());
- _permissionRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Permission>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdatePermission_InovokeMethods()
+ {
+ await _service.UpdatePermission(new Permission());
+ _permissionRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Permission>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public async Task InsertPermissionAction_InovokeMethods()
- {
- await _service.InsertPermissionAction(new PermissionAction());
- _permissionActionRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<PermissionAction>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertPermissionAction_InovokeMethods()
+ {
+ await _service.InsertPermissionAction(new PermissionAction());
+ _permissionActionRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<PermissionAction>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public async Task DeletePermissionAction_InovokeMethods()
- {
- await _service.DeletePermissionAction(new PermissionAction());
- _permissionActionRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<PermissionAction>()), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task DeletePermissionAction_InovokeMethods()
+ {
+ await _service.DeletePermissionAction(new PermissionAction());
+ _permissionActionRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<PermissionAction>()), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Seo/SlugServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Seo/SlugServiceTests.cs
index 2f23e9291..054d9095c 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Seo/SlugServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Seo/SlugServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Common.Services.Seo;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
-using Grand.Data;
using Grand.Domain.Seo;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -10,130 +10,130 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Seo
+namespace Grand.Business.Common.Tests.Services.Seo;
+
+[TestClass]
+public class SlugServiceTests
{
- [TestClass()]
- public class SlugServiceTests
- {
- private IRepository<EntityUrl> _repository;
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _cacheBase;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<EntityUrl> _repository;
- private SlugService _slugService;
+ private SlugService _slugService;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<EntityUrl>();
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<EntityUrl>();
- _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _slugService = new SlugService(_cacheBase, _repository);
- }
+ _mediatorMock = new Mock<IMediator>();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _slugService = new SlugService(_cacheBase, _repository);
+ }
- [TestMethod()]
- public async Task GetEntityUrlByIdTest()
- {
- //Arrange
- var entity = new EntityUrl { Slug = "slug" };
- await _repository.InsertAsync(entity);
- //Act
- var result = _slugService.GetEntityUrlById(entity.Id);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetEntityUrlByIdTest()
+ {
+ //Arrange
+ var entity = new EntityUrl { Slug = "slug" };
+ await _repository.InsertAsync(entity);
+ //Act
+ var result = _slugService.GetEntityUrlById(entity.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task InsertEntityUrlTest()
- {
- //Arrange
- var entity = new EntityUrl { Slug = "slug" };
- //Act
- await _slugService.InsertEntityUrl(entity);
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
+ [TestMethod]
+ public async Task InsertEntityUrlTest()
+ {
+ //Arrange
+ var entity = new EntityUrl { Slug = "slug" };
+ //Act
+ await _slugService.InsertEntityUrl(entity);
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
- [TestMethod()]
- public async Task UpdateEntityUrlTest()
- {
- //Arrange
- var entity = new EntityUrl { Slug = "slug" };
- await _slugService.InsertEntityUrl(entity);
- //Act
- entity.Slug = "slug2";
- await _slugService.UpdateEntityUrl(entity);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == entity.Id).Slug == entity.Slug);
- }
+ [TestMethod]
+ public async Task UpdateEntityUrlTest()
+ {
+ //Arrange
+ var entity = new EntityUrl { Slug = "slug" };
+ await _slugService.InsertEntityUrl(entity);
+ //Act
+ entity.Slug = "slug2";
+ await _slugService.UpdateEntityUrl(entity);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == entity.Id).Slug == entity.Slug);
+ }
- [TestMethod()]
- public async Task DeleteEntityUrlTest()
- {
- //Arrange
- var entity = new EntityUrl { Slug = "slug" };
- await _slugService.InsertEntityUrl(entity);
- //Act
- await _slugService.DeleteEntityUrl(entity);
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == entity.Id));
- }
+ [TestMethod]
+ public async Task DeleteEntityUrlTest()
+ {
+ //Arrange
+ var entity = new EntityUrl { Slug = "slug" };
+ await _slugService.InsertEntityUrl(entity);
+ //Act
+ await _slugService.DeleteEntityUrl(entity);
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Id == entity.Id));
+ }
- [TestMethod()]
- public async Task GetBySlugTest()
- {
- //Arrange
- var entity = new EntityUrl { Slug = "slug" };
- await _slugService.InsertEntityUrl(entity);
- //Act
- var result = await _slugService.GetBySlug(entity.Slug);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetBySlugTest()
+ {
+ //Arrange
+ var entity = new EntityUrl { Slug = "slug" };
+ await _slugService.InsertEntityUrl(entity);
+ //Act
+ var result = await _slugService.GetBySlug(entity.Slug);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task GetBySlugCachedTest()
- {
- //Arrange
- var entity = new EntityUrl { Slug = "slug" };
- await _slugService.InsertEntityUrl(entity);
- //Act
- var result = await _slugService.GetBySlugCached(entity.Slug);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetBySlugCachedTest()
+ {
+ //Arrange
+ var entity = new EntityUrl { Slug = "slug" };
+ await _slugService.InsertEntityUrl(entity);
+ //Act
+ var result = await _slugService.GetBySlugCached(entity.Slug);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task GetAllEntityUrlTest()
- {
- //Arrange
- await _slugService.InsertEntityUrl(new EntityUrl());
- await _slugService.InsertEntityUrl(new EntityUrl());
- await _slugService.InsertEntityUrl(new EntityUrl());
- //Act
- var result = await _slugService.GetAllEntityUrl();
- //Assert
- Assert.IsTrue(result.Any());
- }
+ [TestMethod]
+ public async Task GetAllEntityUrlTest()
+ {
+ //Arrange
+ await _slugService.InsertEntityUrl(new EntityUrl());
+ await _slugService.InsertEntityUrl(new EntityUrl());
+ await _slugService.InsertEntityUrl(new EntityUrl());
+ //Act
+ var result = await _slugService.GetAllEntityUrl();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
- [TestMethod()]
- public async Task GetActiveSlugTest()
- {
- //Arrange
- await _slugService.InsertEntityUrl(new EntityUrl { IsActive = true });
- //Act
- var result = await _slugService.GetAllEntityUrl();
- //Assert
- Assert.IsTrue(result.Any());
- }
+ [TestMethod]
+ public async Task GetActiveSlugTest()
+ {
+ //Arrange
+ await _slugService.InsertEntityUrl(new EntityUrl { IsActive = true });
+ //Act
+ var result = await _slugService.GetAllEntityUrl();
+ //Assert
+ Assert.IsTrue(result.Any());
+ }
- [TestMethod()]
- public async Task SaveSlugTest()
- {
- //Act
- await _slugService.SaveSlug<Category>(new Category(), "slug", "1");
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
+ [TestMethod]
+ public async Task SaveSlugTest()
+ {
+ //Act
+ await _slugService.SaveSlug(new Category(), "slug", "1");
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs
index ea3d68f4c..31b5a0ba3 100644
--- a/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs
@@ -7,61 +7,60 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Common.Tests.Services.Stores
+namespace Grand.Business.Common.Tests.Services.Stores;
+
+[TestClass]
+public class StoreServiceTests
{
- [TestClass()]
- public class StoreServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IRepository<Store>> _repository;
- private StoreService _service;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Store>> _repository;
+ private StoreService _service;
- [TestInitialize]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _mediatorMock = new Mock<IMediator>();
- _repository = new Mock<IRepository<Store>>();
- _service = new StoreService(_cacheMock.Object, _repository.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _mediatorMock = new Mock<IMediator>();
+ _repository = new Mock<IRepository<Store>>();
+ _service = new StoreService(_cacheMock.Object, _repository.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task InsertStore_ValidArgument_InvokeExpectedMethods()
- {
- await _service.InsertStore(new Store());
- _repository.Verify(c => c.InsertAsync(It.IsAny<Store>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Store>>(), default), Times.Once);
- _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertStore_ValidArgument_InvokeExpectedMethods()
+ {
+ await _service.InsertStore(new Store());
+ _repository.Verify(c => c.InsertAsync(It.IsAny<Store>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Store>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateStore_ValidArgument_InvokeExpectedMethods()
- {
- await _service.UpdateStore(new Store());
- _repository.Verify(c => c.UpdateAsync(It.IsAny<Store>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Store>>(), default), Times.Once);
- _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateStore_ValidArgument_InvokeExpectedMethods()
+ {
+ await _service.UpdateStore(new Store());
+ _repository.Verify(c => c.UpdateAsync(It.IsAny<Store>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Store>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteStore_ValidArgument_InvokeExpectedMethods()
- {
- _cacheMock.Setup(c => c.GetAsync<List<Store>>(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>()))
- .Returns(Task.FromResult(new List<Store> { new Store(), new Store() }));
- await _service.DeleteStore(new Store());
- _repository.Verify(c => c.DeleteAsync(It.IsAny<Store>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Store>>(), default), Times.Once);
- _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteStore_ValidArgument_InvokeExpectedMethods()
+ {
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>()))
+ .Returns(Task.FromResult(new List<Store> { new(), new() }));
+ await _service.DeleteStore(new Store());
+ _repository.Verify(c => c.DeleteAsync(It.IsAny<Store>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Store>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod()]
- public void DeleteStore_OnlyOneStore_ThrowException()
- {
- //can not remove store if it is only one
- _cacheMock.Setup(c => c.GetAsync<List<Store>>(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>()))
- .Returns(Task.FromResult(new List<Store> { new Store() }));
- Assert.ThrowsExceptionAsync<Exception>(async () => await _service.DeleteStore(new Store()));
- }
+ [TestMethod]
+ public void DeleteStore_OnlyOneStore_ThrowException()
+ {
+ //can not remove store if it is only one
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<Store>>>>()))
+ .Returns(Task.FromResult(new List<Store> { new() }));
+ Assert.ThrowsExceptionAsync<Exception>(async () => await _service.DeleteStore(new Store()));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Common.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Common.Tests/Startup/StartupApplicationTests.cs
index 7e25e0fda..6f88ad794 100644
--- a/src/Tests/Grand.Business.Common.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Common.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Common.Tests.Startup
+namespace Grand.Business.Common.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Extensions/AffiliateExtensionsTests.cs b/src/Tests/Grand.Business.Customers.Tests/Extensions/AffiliateExtensionsTests.cs
index 3d321acc6..9bdda8948 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Extensions/AffiliateExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Extensions/AffiliateExtensionsTests.cs
@@ -1,135 +1,138 @@
-using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Extensions;
+using Grand.Business.Core.Interfaces.Customers;
using Grand.Domain.Affiliates;
+using Grand.Domain.Common;
+using Grand.Domain.Seo;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-using Grand.Business.Core.Extensions;
-namespace Grand.Business.Customers.Tests.Extensions
-{
- [TestClass()]
- public class AffiliateExtensionsTests
- {
- private const string _fakeStoreUrl = "http://localhost/";
- private string _expectedFormat = _fakeStoreUrl + "?{0}={1}";
- private Mock<IWorkContext> _workContextMock;
- private Mock<IAffiliateService> _affiliateServiceMock;
+namespace Grand.Business.Customers.Tests.Extensions;
- [TestInitialize()]
- public void TestInitialize()
- {
-
- _workContextMock = new Mock<IWorkContext>();
- _affiliateServiceMock = new Mock<IAffiliateService>();
- }
+[TestClass]
+public class AffiliateExtensionsTests
+{
+ private const string _fakeStoreUrl = "http://localhost/";
+ private readonly string _expectedFormat = _fakeStoreUrl + "?{0}={1}";
+ private Mock<IAffiliateService> _affiliateServiceMock;
+ private Mock<IWorkContext> _workContextMock;
+ [TestInitialize]
+ public void TestInitialize()
+ {
+ _workContextMock = new Mock<IWorkContext>();
+ _affiliateServiceMock = new Mock<IAffiliateService>();
+ }
- [TestMethod()]
- public void GetFullName_NullParameter_ThrowException()
- {
- Affiliate affiliate = null;
- Assert.ThrowsException<ArgumentNullException>(() => affiliate.GetFullName());
- }
- [TestMethod()]
- public void GetFullName_NullLastName_ReturnFirstName()
- {
- var firstName = "Test name";
- Affiliate affiliate = new Affiliate {
- Address = new Domain.Common.Address { FirstName = firstName }
- };
- Assert.AreEqual(firstName, affiliate.GetFullName());
- }
+ [TestMethod]
+ public void GetFullName_NullParameter_ThrowException()
+ {
+ Affiliate affiliate = null;
+ Assert.ThrowsException<ArgumentNullException>(() => affiliate.GetFullName());
+ }
- [TestMethod()]
- public void GetFullName_NullFirstName_ReturnLastName()
- {
- var lastName = "Test name";
- Affiliate affiliate = new Affiliate {
- Address = new Domain.Common.Address { LastName = lastName }
- };
- Assert.AreEqual(lastName, affiliate.GetFullName());
- }
+ [TestMethod]
+ public void GetFullName_NullLastName_ReturnFirstName()
+ {
+ var firstName = "Test name";
+ var affiliate = new Affiliate {
+ Address = new Address { FirstName = firstName }
+ };
+ Assert.AreEqual(firstName, affiliate.GetFullName());
+ }
- [TestMethod()]
- public void GetFullName_ValidParameter_ReturnLastName()
- {
- var fullName = $"{"first name"} {"lastName"}";
- Affiliate affiliate = new Affiliate {
- Address = new Domain.Common.Address { LastName = "lastName", FirstName = "first name" }
- };
- Assert.AreEqual(fullName, affiliate.GetFullName());
- }
+ [TestMethod]
+ public void GetFullName_NullFirstName_ReturnLastName()
+ {
+ var lastName = "Test name";
+ var affiliate = new Affiliate {
+ Address = new Address { LastName = lastName }
+ };
+ Assert.AreEqual(lastName, affiliate.GetFullName());
+ }
- [TestMethod()]
- public void GenerateUrl_NullAffiliate_ThrowException()
- {
- Affiliate affiliate = null;
- Assert.ThrowsException<ArgumentNullException>(() => affiliate.GenerateUrl(null), "affiliate");
- }
+ [TestMethod]
+ public void GetFullName_ValidParameter_ReturnLastName()
+ {
+ var fullName = $"{"first name"} {"lastName"}";
+ var affiliate = new Affiliate {
+ Address = new Address { LastName = "lastName", FirstName = "first name" }
+ };
+ Assert.AreEqual(fullName, affiliate.GetFullName());
+ }
- [TestMethod()]
- public void GenerateUrl_NullWebHelper_ThrowException()
- {
- Affiliate affiliate = new Affiliate();
- Assert.ThrowsException<ArgumentNullException>(() => affiliate.GenerateUrl(null), "webHelper");
- }
+ [TestMethod]
+ public void GenerateUrl_NullAffiliate_ThrowException()
+ {
+ Affiliate affiliate = null;
+ Assert.ThrowsException<ArgumentNullException>(() => affiliate.GenerateUrl(null), "affiliate");
+ }
- [TestMethod()]
- public void GenerateUrl_NullFriendlyUrlName_UseId()
- {
- var id = "id";
- Affiliate affiliate = new Affiliate {
- Id = id
- };
- _workContextMock.Setup(c => c.CurrentStore).Returns(new Domain.Stores.Store { Url = _fakeStoreUrl });
- Assert.AreEqual(string.Format(_expectedFormat, "affiliateid", id), affiliate.GenerateUrl("http://localhost/"));
- //_webHelperMock.Verify(c => c.ModifyQueryString(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
- }
+ [TestMethod]
+ public void GenerateUrl_NullWebHelper_ThrowException()
+ {
+ var affiliate = new Affiliate();
+ Assert.ThrowsException<ArgumentNullException>(() => affiliate.GenerateUrl(null), "webHelper");
+ }
- [TestMethod()]
- public void GenerateUrl_ValideParameters()
- {
- var friendlyUrl = "friendlyurl";
- Affiliate affiliate = new Affiliate {
- FriendlyUrlName = friendlyUrl
- };
- _workContextMock.Setup(c => c.CurrentStore).Returns(new Domain.Stores.Store { Url = _fakeStoreUrl });
- Assert.AreEqual(string.Format(_expectedFormat, "affiliate", friendlyUrl), affiliate.GenerateUrl("http://localhost/"));
- }
+ [TestMethod]
+ public void GenerateUrl_NullFriendlyUrlName_UseId()
+ {
+ var id = "id";
+ var affiliate = new Affiliate {
+ Id = id
+ };
+ _workContextMock.Setup(c => c.CurrentStore).Returns(new Store { Url = _fakeStoreUrl });
+ Assert.AreEqual(string.Format(_expectedFormat, "affiliateid", id), affiliate.GenerateUrl("http://localhost/"));
+ //_webHelperMock.Verify(c => c.ModifyQueryString(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
+ }
- [TestMethod()]
- public async Task ValidateFriendlyUrlName_UrlNameDontExist_ReturnUrl()
- {
- //Don't exist
- _affiliateServiceMock.Setup(c => c.GetAffiliateByFriendlyUrlName(It.IsAny<string>()))
- .Returns(() => Task.FromResult<Affiliate>(null));
- var friendlyUrl = "macbool-pro";
- Affiliate affiliate = new Affiliate {
- FriendlyUrlName = friendlyUrl
- };
- var result = await affiliate.ValidateFriendlyUrlName(_affiliateServiceMock.Object, new Domain.Seo.SeoSettings(), friendlyUrl, "");
- Assert.AreEqual(result, friendlyUrl);
- }
+ [TestMethod]
+ public void GenerateUrl_ValideParameters()
+ {
+ var friendlyUrl = "friendlyurl";
+ var affiliate = new Affiliate {
+ FriendlyUrlName = friendlyUrl
+ };
+ _workContextMock.Setup(c => c.CurrentStore).Returns(new Store { Url = _fakeStoreUrl });
+ Assert.AreEqual(string.Format(_expectedFormat, "affiliate", friendlyUrl),
+ affiliate.GenerateUrl("http://localhost/"));
+ }
- [TestMethod()]
- public async Task ValidateFriendlyUrlName_UrlNameExist_IncreaseUrl()
- {
- var invokeNumber = 1;
- _affiliateServiceMock.Setup(c => c.GetAffiliateByFriendlyUrlName(It.IsAny<string>()))
- .Returns(() =>
- {
- if (invokeNumber <= 2) return Task.FromResult(new Affiliate());
- return Task.FromResult<Affiliate>(null);
+ [TestMethod]
+ public async Task ValidateFriendlyUrlName_UrlNameDontExist_ReturnUrl()
+ {
+ //Don't exist
+ _affiliateServiceMock.Setup(c => c.GetAffiliateByFriendlyUrlName(It.IsAny<string>()))
+ .Returns(() => Task.FromResult<Affiliate>(null));
+ var friendlyUrl = "macbool-pro";
+ var affiliate = new Affiliate {
+ FriendlyUrlName = friendlyUrl
+ };
+ var result =
+ await affiliate.ValidateFriendlyUrlName(_affiliateServiceMock.Object, new SeoSettings(), friendlyUrl, "");
+ Assert.AreEqual(result, friendlyUrl);
+ }
- }).Callback(() => invokeNumber++);
- var friendlyUrl = "macbool-pro";
- var expectedUrl = "macbool-pro-3";
- Affiliate affiliate = new Affiliate {
- FriendlyUrlName = friendlyUrl
- };
- var result = await affiliate.ValidateFriendlyUrlName(_affiliateServiceMock.Object, new Domain.Seo.SeoSettings(), friendlyUrl, "");
- Assert.AreEqual(result, expectedUrl);
- }
+ [TestMethod]
+ public async Task ValidateFriendlyUrlName_UrlNameExist_IncreaseUrl()
+ {
+ var invokeNumber = 1;
+ _affiliateServiceMock.Setup(c => c.GetAffiliateByFriendlyUrlName(It.IsAny<string>()))
+ .Returns(() =>
+ {
+ if (invokeNumber <= 2) return Task.FromResult(new Affiliate());
+ return Task.FromResult<Affiliate>(null);
+ }).Callback(() => invokeNumber++);
+ var friendlyUrl = "macbool-pro";
+ var expectedUrl = "macbool-pro-3";
+ var affiliate = new Affiliate {
+ FriendlyUrlName = friendlyUrl
+ };
+ var result =
+ await affiliate.ValidateFriendlyUrlName(_affiliateServiceMock.Object, new SeoSettings(), friendlyUrl, "");
+ Assert.AreEqual(result, expectedUrl);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Handler/ActiveVendorCommandHandlerTests.cs b/src/Tests/Grand.Business.Customers.Tests/Handler/ActiveVendorCommandHandlerTests.cs
index 4cb485f7b..a6b34ff65 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Handler/ActiveVendorCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Handler/ActiveVendorCommandHandlerTests.cs
@@ -1,66 +1,73 @@
-using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Customers.Commands.Handlers;
-using Grand.Business.Core.Commands.Customers;
+using Grand.Business.Core.Commands.Customers;
using Grand.Business.Core.Events.Customers;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Customers.Commands.Handlers;
using Grand.Domain.Customers;
+using Grand.Domain.Vendors;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Handler
+namespace Grand.Business.Customers.Tests.Handler;
+
+[TestClass]
+public class ActiveVendorCommandHandlerTests
{
- [TestClass()]
- public class ActiveVendorCommandHandlerTests
- {
- private Mock<IVendorService> _vendorMock;
- private Mock<ICustomerService> _cumstomerServiceMock;
- private Mock<IGroupService> _groupServiceMock;
- private Mock<IMediator> _mediatorMock;
- private ActiveVendorCommandHandler _handler;
+ private Mock<ICustomerService> _cumstomerServiceMock;
+ private Mock<IGroupService> _groupServiceMock;
+ private ActiveVendorCommandHandler _handler;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IVendorService> _vendorMock;
- [TestInitialize()]
- public void Init()
- {
- _vendorMock = new Mock<IVendorService>();
- _cumstomerServiceMock = new Mock<ICustomerService>();
- _groupServiceMock = new Mock<IGroupService>();
- _mediatorMock = new Mock<IMediator>();
- _handler = new ActiveVendorCommandHandler(_vendorMock.Object, _cumstomerServiceMock.Object, _groupServiceMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _vendorMock = new Mock<IVendorService>();
+ _cumstomerServiceMock = new Mock<ICustomerService>();
+ _groupServiceMock = new Mock<IGroupService>();
+ _mediatorMock = new Mock<IMediator>();
+ _handler = new ActiveVendorCommandHandler(_vendorMock.Object, _cumstomerServiceMock.Object,
+ _groupServiceMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task Handle_ValidArguments_InsertCustomerGroupInCustomer()
- {
- var command = new ActiveVendorCommand {
- CustomerIds = new List<string> { "id" },
- Active = true,
- Vendor = new Domain.Vendors.Vendor()
- };
- _cumstomerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>())).Returns(() => Task.FromResult(new Customer { Active = true }));
- _groupServiceMock.Setup(c => c.IsAdmin(It.IsAny<Customer>())).Returns(() => Task.FromResult(false));
- _groupServiceMock.Setup(c => c.GetCustomerGroupBySystemName(It.IsAny<string>())).Returns(() => Task.FromResult(new CustomerGroup()));
- await _handler.Handle(command, default);
- _cumstomerServiceMock.Verify(c => c.InsertCustomerGroupInCustomer(It.IsAny<CustomerGroup>(), It.IsAny<string>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish<VendorActivationEvent>(It.IsAny<VendorActivationEvent>(), default));
- }
+ [TestMethod]
+ public async Task Handle_ValidArguments_InsertCustomerGroupInCustomer()
+ {
+ var command = new ActiveVendorCommand {
+ CustomerIds = new List<string> { "id" },
+ Active = true,
+ Vendor = new Vendor()
+ };
+ _cumstomerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Customer { Active = true }));
+ _groupServiceMock.Setup(c => c.IsAdmin(It.IsAny<Customer>())).Returns(() => Task.FromResult(false));
+ _groupServiceMock.Setup(c => c.GetCustomerGroupBySystemName(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new CustomerGroup()));
+ await _handler.Handle(command, default);
+ _cumstomerServiceMock.Verify(
+ c => c.InsertCustomerGroupInCustomer(It.IsAny<CustomerGroup>(), It.IsAny<string>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<VendorActivationEvent>(), default));
+ }
- [TestMethod()]
- public async Task Handle_ValidArguments_DeleteCustomerGroupInCustomer()
- {
- var command = new ActiveVendorCommand {
- CustomerIds = new List<string> { "id" },
- Active = false,
- Vendor = new Domain.Vendors.Vendor()
- };
- _cumstomerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>())).Returns(() => Task.FromResult(new Customer { Active = true }));
- _groupServiceMock.Setup(c => c.IsAdmin(It.IsAny<Customer>())).Returns(() => Task.FromResult(false));
- _groupServiceMock.Setup(c => c.IsVendor(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
- _groupServiceMock.Setup(c => c.GetCustomerGroupBySystemName(It.IsAny<string>())).Returns(() => Task.FromResult(new CustomerGroup()));
- await _handler.Handle(command, default);
- _cumstomerServiceMock.Verify(c => c.DeleteCustomerGroupInCustomer(It.IsAny<CustomerGroup>(), It.IsAny<string>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish<VendorActivationEvent>(It.IsAny<VendorActivationEvent>(), default));
- }
+ [TestMethod]
+ public async Task Handle_ValidArguments_DeleteCustomerGroupInCustomer()
+ {
+ var command = new ActiveVendorCommand {
+ CustomerIds = new List<string> { "id" },
+ Active = false,
+ Vendor = new Vendor()
+ };
+ _cumstomerServiceMock.Setup(c => c.GetCustomerById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new Customer { Active = true }));
+ _groupServiceMock.Setup(c => c.IsAdmin(It.IsAny<Customer>())).Returns(() => Task.FromResult(false));
+ _groupServiceMock.Setup(c => c.IsVendor(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
+ _groupServiceMock.Setup(c => c.GetCustomerGroupBySystemName(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new CustomerGroup()));
+ await _handler.Handle(command, default);
+ _cumstomerServiceMock.Verify(
+ c => c.DeleteCustomerGroupInCustomer(It.IsAny<CustomerGroup>(), It.IsAny<string>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<VendorActivationEvent>(), default));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoggedInNotificationHandlerTests.cs b/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoggedInNotificationHandlerTests.cs
index c4dfa2a8b..4159f5642 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoggedInNotificationHandlerTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoggedInNotificationHandlerTests.cs
@@ -5,37 +5,35 @@ using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Handler
+namespace Grand.Business.Customers.Tests.Handler;
+
+[TestClass]
+public class CustomerLoggedInNotificationHandlerTests
{
- [TestClass()]
- public class CustomerLoggedInNotificationHandlerTests
- {
- private Mock<ICustomerService> _cumstomerServiceMock;
- private CustomerLoggedInEventHandler _handler;
+ private Mock<ICustomerService> _cumstomerServiceMock;
+ private CustomerLoggedInEventHandler _handler;
- [TestInitialize()]
- public void Init()
- {
- _cumstomerServiceMock = new Mock<ICustomerService>();
- _handler = new CustomerLoggedInEventHandler(_cumstomerServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cumstomerServiceMock = new Mock<ICustomerService>();
+ _handler = new CustomerLoggedInEventHandler(_cumstomerServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- var customer = new Customer {
- FailedLoginAttempts = 1,
- CannotLoginUntilDateUtc = DateTime.Now
- };
- //Act
- await _handler.Handle(new CustomerLoggedInEvent(customer), CancellationToken.None);
-
- //Assert
- Assert.IsTrue(customer.FailedLoginAttempts == 0);
- Assert.IsTrue(customer.CannotLoginUntilDateUtc == null);
- _cumstomerServiceMock.Verify(c => c.UpdateCustomerLastLoginDate(customer), Times.Once);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ var customer = new Customer {
+ FailedLoginAttempts = 1,
+ CannotLoginUntilDateUtc = DateTime.Now
+ };
+ //Act
+ await _handler.Handle(new CustomerLoggedInEvent(customer), CancellationToken.None);
+ //Assert
+ Assert.IsTrue(customer.FailedLoginAttempts == 0);
+ Assert.IsTrue(customer.CannotLoginUntilDateUtc == null);
+ _cumstomerServiceMock.Verify(c => c.UpdateCustomerLastLoginDate(customer), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoginFailedNotificationHandlerTests.cs b/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoginFailedNotificationHandlerTests.cs
index e37c37b92..a8f2ebe05 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoginFailedNotificationHandlerTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Handler/CustomerLoginFailedNotificationHandlerTests.cs
@@ -5,52 +5,52 @@ using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Handler
+namespace Grand.Business.Customers.Tests.Handler;
+
+[TestClass]
+public class CustomerLoginFailedNotificationHandlerTests
{
- [TestClass()]
- public class CustomerLoginFailedNotificationHandlerTests
+ private Mock<ICustomerService> _customerServiceMock;
+ private CustomerSettings _customerSettings;
+ private CustomerLoginFailedEventHandler _handler;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _customerServiceMock = new Mock<ICustomerService>();
+ _customerSettings = new CustomerSettings { FailedPasswordAllowedAttempts = 10 };
+ _handler = new CustomerLoginFailedEventHandler(_customerServiceMock.Object, _customerSettings);
+ }
+
+ [TestMethod]
+ public async Task HandleTest_FailedLoginAttempts_Inc()
{
- private Mock<ICustomerService> _customerServiceMock;
- private CustomerSettings _customerSettings;
- private CustomerLoginFailedEventHandler _handler;
+ //Arrange
+ var customer = new Customer {
+ FailedLoginAttempts = 1,
+ CannotLoginUntilDateUtc = null
+ };
+ //Act
+ await _handler.Handle(new CustomerLoginFailedEvent(customer), CancellationToken.None);
+
+ //Assert
+ Assert.IsTrue(customer.FailedLoginAttempts == 2);
+ _customerServiceMock.Verify(c => c.UpdateCustomerLastLoginDate(customer), Times.Once);
+ }
- [TestInitialize()]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
- _customerSettings = new CustomerSettings { FailedPasswordAllowedAttempts = 10 };
- _handler = new CustomerLoginFailedEventHandler(_customerServiceMock.Object, _customerSettings);
- }
+ [TestMethod]
+ public async Task HandleTest_CannotLoginUntilDate_Set()
+ {
+ //Arrange
+ var customer = new Customer {
+ FailedLoginAttempts = 10,
+ CannotLoginUntilDateUtc = null
+ };
+ //Act
+ await _handler.Handle(new CustomerLoginFailedEvent(customer), CancellationToken.None);
- [TestMethod()]
- public async Task HandleTest_FailedLoginAttempts_Inc()
- {
- //Arrange
- var customer = new Customer {
- FailedLoginAttempts = 1,
- CannotLoginUntilDateUtc = null
- };
- //Act
- await _handler.Handle(new CustomerLoginFailedEvent(customer), CancellationToken.None);
-
- //Assert
- Assert.IsTrue(customer.FailedLoginAttempts == 2);
- _customerServiceMock.Verify(c => c.UpdateCustomerLastLoginDate(customer), Times.Once);
- }
- [TestMethod()]
- public async Task HandleTest_CannotLoginUntilDate_Set()
- {
- //Arrange
- var customer = new Customer {
- FailedLoginAttempts = 10,
- CannotLoginUntilDateUtc = null
- };
- //Act
- await _handler.Handle(new CustomerLoginFailedEvent(customer), CancellationToken.None);
-
- //Assert
- Assert.IsTrue(customer.CannotLoginUntilDateUtc != null);
- _customerServiceMock.Verify(c => c.UpdateCustomerLastLoginDate(customer), Times.Once);
- }
+ //Assert
+ Assert.IsTrue(customer.CannotLoginUntilDateUtc != null);
+ _customerServiceMock.Verify(c => c.UpdateCustomerLastLoginDate(customer), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetCustomerQueryHandlerTests.cs b/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetCustomerQueryHandlerTests.cs
index 54f11eab2..ca3efd846 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetCustomerQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetCustomerQueryHandlerTests.cs
@@ -1,36 +1,36 @@
-using Grand.Business.Customers.Queries.Handlers;
+using Grand.Business.Core.Queries.Customers;
+using Grand.Business.Customers.Queries.Handlers;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Customers.Tests.Queries.Handlers
+namespace Grand.Business.Customers.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetCustomerQueryHandlerTests
{
- [TestClass()]
- public class GetCustomerQueryHandlerTests
- {
- private GetCustomerQueryHandler handler;
+ private GetCustomerQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- var _repository = new MongoDBRepositoryTest<Customer>();
- _repository.Insert(new Customer());
- _repository.Insert(new Customer());
- _repository.Insert(new Customer());
- _repository.Insert(new Customer());
- handler = new GetCustomerQueryHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ var _repository = new MongoDBRepositoryTest<Customer>();
+ _repository.Insert(new Customer());
+ _repository.Insert(new Customer());
+ _repository.Insert(new Customer());
+ _repository.Insert(new Customer());
+ handler = new GetCustomerQueryHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Assert
- var customerQuery = new Core.Queries.Customers.GetCustomerQuery();
- //Act
- var result = await handler.Handle(customerQuery, CancellationToken.None);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Assert
+ var customerQuery = new GetCustomerQuery();
+ //Act
+ var result = await handler.Handle(customerQuery, CancellationToken.None);
- //Assert
- Assert.AreEqual(4, result.Count());
- }
+ //Assert
+ Assert.AreEqual(4, result.Count());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetGroupBySystemNameQueryHandlerTests.cs b/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetGroupBySystemNameQueryHandlerTests.cs
index 85ceb36c9..1ac040817 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetGroupBySystemNameQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetGroupBySystemNameQueryHandlerTests.cs
@@ -1,35 +1,35 @@
using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Queries.Customers;
using Grand.Business.Customers.Queries.Handlers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Queries.Handlers
+namespace Grand.Business.Customers.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetGroupBySystemNameQueryHandlerTests
{
- [TestClass()]
- public class GetGroupBySystemNameQueryHandlerTests
- {
- private Mock<IGroupService> _groupServiceMock;
- private GetGroupBySystemNameQueryHandler handler;
+ private Mock<IGroupService> _groupServiceMock;
+ private GetGroupBySystemNameQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _groupServiceMock = new Mock<IGroupService>();
- handler = new GetGroupBySystemNameQueryHandler(_groupServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _groupServiceMock = new Mock<IGroupService>();
+ handler = new GetGroupBySystemNameQueryHandler(_groupServiceMock.Object);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Assert
- var groupBySystemNameQuery = new Core.Queries.Customers.GetGroupBySystemNameQuery {
- SystemName = "sample"
- };
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Assert
+ var groupBySystemNameQuery = new GetGroupBySystemNameQuery {
+ SystemName = "sample"
+ };
- //Act
- _ = await handler.Handle(groupBySystemNameQuery, CancellationToken.None);
- //Assert
- _groupServiceMock.Verify(c => c.GetCustomerGroupBySystemName(It.IsAny<string>()), Times.Once);
- }
+ //Act
+ _ = await handler.Handle(groupBySystemNameQuery, CancellationToken.None);
+ //Assert
+ _groupServiceMock.Verify(c => c.GetCustomerGroupBySystemName(It.IsAny<string>()), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetPasswordIsExpiredQueryHandlerTests.cs b/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetPasswordIsExpiredQueryHandlerTests.cs
index bcf833ae0..487145583 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetPasswordIsExpiredQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Queries/Handlers/GetPasswordIsExpiredQueryHandlerTests.cs
@@ -1,41 +1,42 @@
using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Business.Core.Queries.Customers;
using Grand.Business.Customers.Queries.Handlers;
using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Queries.Handlers
+namespace Grand.Business.Customers.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetPasswordIsExpiredQueryHandlerTests
{
- [TestClass()]
- public class GetPasswordIsExpiredQueryHandlerTests
- {
- private Mock<IGroupService> _groupServiceMock;
- private GetPasswordIsExpiredQueryHandler handler;
+ private Mock<IGroupService> _groupServiceMock;
+ private GetPasswordIsExpiredQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _groupServiceMock = new Mock<IGroupService>();
- handler = new GetPasswordIsExpiredQueryHandler(_groupServiceMock.Object, new Domain.Customers.CustomerSettings { PasswordLifetime = 10 });
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _groupServiceMock = new Mock<IGroupService>();
+ handler = new GetPasswordIsExpiredQueryHandler(_groupServiceMock.Object,
+ new CustomerSettings { PasswordLifetime = 10 });
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Assert
- var cr = new CustomerGroup { Active = true, EnablePasswordLifetime = true };
- var cgs = new List<CustomerGroup> { cr };
- _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
- .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Assert
+ var cr = new CustomerGroup { Active = true, EnablePasswordLifetime = true };
+ var cgs = new List<CustomerGroup> { cr };
+ _groupServiceMock.Setup(c => c.GetAllByIds(It.IsAny<string[]>()))
+ .Returns(Task.FromResult<IList<CustomerGroup>>(cgs));
- var passwordIsExpiredQuery = new Core.Queries.Customers.GetPasswordIsExpiredQuery();
- var customer = new Customer { Email = "[email protected]" };
- customer.Groups.Add(cr.Id);
- passwordIsExpiredQuery.Customer = customer;
- //Act
- var result = await handler.Handle(passwordIsExpiredQuery, CancellationToken.None);
- //Assert
- Assert.IsTrue(result);
- }
+ var passwordIsExpiredQuery = new GetPasswordIsExpiredQuery();
+ var customer = new Customer { Email = "[email protected]" };
+ customer.Groups.Add(cr.Id);
+ passwordIsExpiredQuery.Customer = customer;
+ //Act
+ var result = await handler.Handle(passwordIsExpiredQuery, CancellationToken.None);
+ //Assert
+ Assert.IsTrue(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/AffiliateServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/AffiliateServiceTests.cs
index dcab6ef9c..f5a42e167 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/AffiliateServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/AffiliateServiceTests.cs
@@ -1,76 +1,77 @@
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Customers.Services;
-using Grand.Domain.Affiliates;
using Grand.Data;
+using Grand.Domain.Affiliates;
using Grand.Domain.Orders;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
-{
- [TestClass()]
- public class AffiliateServiceTests
- {
- private Mock<IRepository<Affiliate>> _affiliateRepository;
- private Mock<IRepository<Order>> _orderRepository;
- private Mock<IMediator> _mediatorMock;
- private IAffiliateService _affiliateService;
+namespace Grand.Business.Customers.Tests.Services;
- [TestInitialize()]
- public void TestInitialize()
- {
- _affiliateRepository = new Mock<IRepository<Affiliate>>();
- _orderRepository = new Mock<IRepository<Order>>();
- _mediatorMock = new Mock<IMediator>();
- _affiliateService = new AffiliateService(_affiliateRepository.Object, _orderRepository.Object, _mediatorMock.Object);
- }
- [TestMethod()]
- public async Task GetAffiliateByIdTest()
- {
- await _affiliateService.GetAffiliateById("");
- _affiliateRepository.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
-
- }
+[TestClass]
+public class AffiliateServiceTests
+{
+ private Mock<IRepository<Affiliate>> _affiliateRepository;
+ private IAffiliateService _affiliateService;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Order>> _orderRepository;
- [TestMethod()]
- public async Task UpdateAffiliate_NullParameter_ThrwoException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _affiliateService.UpdateAffiliate(null), "affiliate");
- }
+ [TestInitialize]
+ public void TestInitialize()
+ {
+ _affiliateRepository = new Mock<IRepository<Affiliate>>();
+ _orderRepository = new Mock<IRepository<Order>>();
+ _mediatorMock = new Mock<IMediator>();
+ _affiliateService =
+ new AffiliateService(_affiliateRepository.Object, _orderRepository.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task InsertAffiliate_NullParameter_ThrwoException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _affiliateService.InsertAffiliate(null), "affiliate");
- }
+ [TestMethod]
+ public async Task GetAffiliateByIdTest()
+ {
+ await _affiliateService.GetAffiliateById("");
+ _affiliateRepository.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteAffiliate_NullParameter_ThrwoException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _affiliateService.DeleteAffiliate(null), "affiliate");
- }
+ [TestMethod]
+ public async Task UpdateAffiliate_NullParameter_ThrwoException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _affiliateService.UpdateAffiliate(null), "affiliate");
+ }
+ [TestMethod]
+ public async Task InsertAffiliate_NullParameter_ThrwoException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _affiliateService.InsertAffiliate(null), "affiliate");
+ }
- [TestMethod()]
- public async Task UpdateAffiliate_ValidParamters()
- {
- var affiliate = new Affiliate();
- await _affiliateService.UpdateAffiliate(affiliate);
- _affiliateRepository.Verify(c => c.UpdateAsync(It.IsAny<Affiliate>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Affiliate>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteAffiliate_NullParameter_ThrwoException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _affiliateService.DeleteAffiliate(null), "affiliate");
+ }
- [TestMethod()]
- public async Task InsertAffiliate_ValidParamters()
- {
- var affiliate = new Affiliate();
- await _affiliateService.InsertAffiliate(affiliate);
- _affiliateRepository.Verify(c => c.InsertAsync(It.IsAny<Affiliate>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Affiliate>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateAffiliate_ValidParamters()
+ {
+ var affiliate = new Affiliate();
+ await _affiliateService.UpdateAffiliate(affiliate);
+ _affiliateRepository.Verify(c => c.UpdateAsync(It.IsAny<Affiliate>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Affiliate>>(), default), Times.Once);
+ }
+ [TestMethod]
+ public async Task InsertAffiliate_ValidParamters()
+ {
+ var affiliate = new Affiliate();
+ await _affiliateService.InsertAffiliate(affiliate);
+ _affiliateRepository.Verify(c => c.InsertAsync(It.IsAny<Affiliate>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Affiliate>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeParserTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeParserTests.cs
index d7963094b..3f249cfeb 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeParserTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeParserTests.cs
@@ -1,122 +1,135 @@
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Customers.Services;
+using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
+using Grand.Domain.Localization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class CustomerAttributeParserTests
{
- [TestClass()]
- public class CustomerAttributeParserTests
- {
- private Mock<ICustomerAttributeService> _customerAtrServiceMock;
- private CustomerAttributeParser _parser;
- private List<CustomAttribute> customAtr;
- private List<CustomerAttribute> _customerAtr;
+ private List<CustomerAttribute> _customerAtr;
+ private Mock<ICustomerAttributeService> _customerAtrServiceMock;
+ private CustomerAttributeParser _parser;
+ private List<CustomAttribute> customAtr;
- [TestInitialize()]
- public void Init()
+ [TestInitialize]
+ public void Init()
+ {
+ _customerAtrServiceMock = new Mock<ICustomerAttributeService>();
+ var _translationServiceMock = new Mock<ITranslationService>();
{
- _customerAtrServiceMock = new Mock<ICustomerAttributeService>();
- var _translationServiceMock = new Mock<ITranslationService>();
- {
- _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Warning{0}");
- }
+ _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Warning{0}");
+ }
- _parser = new CustomerAttributeParser(_customerAtrServiceMock.Object);
- customAtr = [
- new CustomAttribute { Key = "key1", Value = "value1" },
- new CustomAttribute { Key = "key2", Value = "value2" },
- new CustomAttribute { Key = "key3", Value = "value3" },
- new CustomAttribute { Key = "key4", Value = "value4" }
- ];
+ _parser = new CustomerAttributeParser(_customerAtrServiceMock.Object);
+ customAtr = [
+ new CustomAttribute { Key = "key1", Value = "value1" },
+ new CustomAttribute { Key = "key2", Value = "value2" },
+ new CustomAttribute { Key = "key3", Value = "value3" },
+ new CustomAttribute { Key = "key4", Value = "value4" }
+ ];
- _customerAtr = [
- new CustomerAttribute {
- Id = "key1", Name = "name1", AttributeControlTypeId = Domain.Catalog.AttributeControlType.TextBox
- },
- new CustomerAttribute { Id = "key2", Name = "name2" },
- new CustomerAttribute { Id = "key3", Name = "name3" },
- new CustomerAttribute { Id = "key4", Name = "name4" },
- new CustomerAttribute { Id = "key5", Name = "name5" }
- ];
- _customerAtr.ForEach(c => c.CustomerAttributeValues.Add(new CustomerAttributeValue { Id = "value" + c.Id.Last() }));
- }
+ _customerAtr = [
+ new CustomerAttribute {
+ Id = "key1", Name = "name1", AttributeControlTypeId = AttributeControlType.TextBox
+ },
+ new CustomerAttribute { Id = "key2", Name = "name2" },
+ new CustomerAttribute { Id = "key3", Name = "name3" },
+ new CustomerAttribute { Id = "key4", Name = "name4" },
+ new CustomerAttribute { Id = "key5", Name = "name5" }
+ ];
+ _customerAtr.ForEach(c =>
+ c.CustomerAttributeValues.Add(new CustomerAttributeValue { Id = "value" + c.Id.Last() }));
+ }
- [TestMethod()]
- public async Task ParseCustomerAttributes_ReturnExpectedValues()
- {
- _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.ParseCustomerAttributes(customAtr);
- Assert.IsTrue(result.Count == 4);
- Assert.IsTrue(result.Any(c => c.Id.Equals("key1")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("key2")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("key3")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("key4")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("key5")));
- }
+ [TestMethod]
+ public async Task ParseCustomerAttributes_ReturnExpectedValues()
+ {
+ _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.ParseCustomerAttributes(customAtr);
+ Assert.IsTrue(result.Count == 4);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key1")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key2")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key3")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key4")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("key5")));
+ }
- [TestMethod()]
- public async Task ParseCustomerAttributes_ReturnEmptyList()
- {
- //not exist
- _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns(() => Task.FromResult<CustomerAttribute>(null));
- var result = await _parser.ParseCustomerAttributes(customAtr);
- Assert.IsTrue(result.Count == 0);
- }
+ [TestMethod]
+ public async Task ParseCustomerAttributes_ReturnEmptyList()
+ {
+ //not exist
+ _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>()))
+ .Returns(() => Task.FromResult<CustomerAttribute>(null));
+ var result = await _parser.ParseCustomerAttributes(customAtr);
+ Assert.IsTrue(result.Count == 0);
+ }
- [TestMethod()]
- public async Task ParseCustomer0AttributeValues_ReturnExpectedValues()
- {
- _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.ParseCustomerAttributeValues(customAtr);
- Assert.IsTrue(result.Count == 3);
- Assert.IsTrue(result.Any(c => c.Id.Equals("value2")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("value3")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("value4")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("value5")));
- }
+ [TestMethod]
+ public async Task ParseCustomer0AttributeValues_ReturnExpectedValues()
+ {
+ _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.ParseCustomerAttributeValues(customAtr);
+ Assert.IsTrue(result.Count == 3);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value2")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value3")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value4")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("value5")));
+ }
- [TestMethod()]
- public void AddCustomerAttribute_ReturnExpectedValues()
- {
- //not exist
+ [TestMethod]
+ public void AddCustomerAttribute_ReturnExpectedValues()
+ {
+ //not exist
- var result = _parser.AddCustomerAttribute(customAtr, new CustomerAttribute { Id = "key7" }, "value7");
- Assert.IsTrue(result.Count == 5);
- Assert.IsTrue(result.Any(c => c.Key.Equals("key7")));
- }
+ var result = _parser.AddCustomerAttribute(customAtr, new CustomerAttribute { Id = "key7" }, "value7");
+ Assert.IsTrue(result.Count == 5);
+ Assert.IsTrue(result.Any(c => c.Key.Equals("key7")));
+ }
- [TestMethod()]
- public async Task GetAttributeWarnings_Return_NoWarning()
- {
- _customerAtrServiceMock.Setup(c => c.GetAllCustomerAttributes()).Returns(() => Task.FromResult((IList<CustomerAttribute>)_customerAtr));
- _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.GetAttributeWarnings(customAtr);
- Assert.IsTrue(result.Count == 0);
- }
- [TestMethod()]
- public async Task GetAttributeWarnings_Return_WithWarning()
- {
- _customerAtr.FirstOrDefault(x=>x.Id == "key5").IsRequired = true;
- _customerAtrServiceMock.Setup(c => c.GetAllCustomerAttributes()).Returns(() => Task.FromResult((IList<CustomerAttribute>)_customerAtr));
- _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.GetAttributeWarnings(customAtr);
- Assert.IsTrue(result.Count == 1);
- }
- [TestMethod()]
- public async Task FormatAttributes_Return_string()
- {
- _customerAtrServiceMock.Setup(c => c.GetAllCustomerAttributes()).Returns(() => Task.FromResult((IList<CustomerAttribute>)_customerAtr));
- _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.FormatAttributes(new Domain.Localization.Language(),
- new List<CustomAttribute> {
- new CustomAttribute {Key="key1",Value="value1" }
- });
- Assert.IsTrue(result == "name1: value1");
- }
+ [TestMethod]
+ public async Task GetAttributeWarnings_Return_NoWarning()
+ {
+ _customerAtrServiceMock.Setup(c => c.GetAllCustomerAttributes())
+ .Returns(() => Task.FromResult((IList<CustomerAttribute>)_customerAtr));
+ _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.GetAttributeWarnings(customAtr);
+ Assert.IsTrue(result.Count == 0);
+ }
+
+ [TestMethod]
+ public async Task GetAttributeWarnings_Return_WithWarning()
+ {
+ _customerAtr.FirstOrDefault(x => x.Id == "key5").IsRequired = true;
+ _customerAtrServiceMock.Setup(c => c.GetAllCustomerAttributes())
+ .Returns(() => Task.FromResult((IList<CustomerAttribute>)_customerAtr));
+ _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.GetAttributeWarnings(customAtr);
+ Assert.IsTrue(result.Count == 1);
+ }
+
+ [TestMethod]
+ public async Task FormatAttributes_Return_string()
+ {
+ _customerAtrServiceMock.Setup(c => c.GetAllCustomerAttributes())
+ .Returns(() => Task.FromResult((IList<CustomerAttribute>)_customerAtr));
+ _customerAtrServiceMock.Setup(c => c.GetCustomerAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_customerAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.FormatAttributes(new Language(),
+ new List<CustomAttribute> {
+ new() { Key = "key1", Value = "value1" }
+ });
+ Assert.IsTrue(result == "name1: value1");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeServiceTests.cs
index c2b5c3481..0072e583d 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerAttributeServiceTests.cs
@@ -1,92 +1,96 @@
using Grand.Business.Customers.Services;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class CustomerAttributeServiceTests
{
- [TestClass()]
- public class CustomerAttributeServiceTests
+ private CustomerAttributeService _atrService;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<CustomerAttribute>> _repositoryMock;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<ICacheBase> _cacheMock;
- private Mock<IRepository<CustomerAttribute>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private CustomerAttributeService _atrService;
+ _cacheMock = new Mock<ICacheBase>();
+ _repositoryMock = new Mock<IRepository<CustomerAttribute>>();
+ _mediatorMock = new Mock<IMediator>();
+ _atrService = new CustomerAttributeService(_cacheMock.Object, _repositoryMock.Object, _mediatorMock.Object);
+ }
- [TestInitialize]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _repositoryMock = new Mock<IRepository<CustomerAttribute>>();
- _mediatorMock = new Mock<IMediator>();
- _atrService = new CustomerAttributeService(_cacheMock.Object, _repositoryMock.Object, _mediatorMock.Object);
- }
+ [TestMethod]
+ public async Task InsertCustomerAttribute_ValidArguemnts_InvokeRepositoryAndCache()
+ {
+ await _atrService.InsertCustomerAttribute(new CustomerAttribute());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CustomerAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerAttribute>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ }
- [TestMethod()]
- public async Task InsertCustomerAttribute_ValidArguemnts_InvokeRepositoryAndCache()
- {
- await _atrService.InsertCustomerAttribute(new CustomerAttribute());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CustomerAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerAttribute>>(), default(CancellationToken)), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- }
+ [TestMethod]
+ public async Task UpdateCustomerAttribute_ValidArguemnts_InvokeRepositoryAndCache()
+ {
+ await _atrService.UpdateCustomerAttribute(new CustomerAttribute());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CustomerAttribute>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ }
- [TestMethod()]
- public async Task UpdateCustomerAttribute_ValidArguemnts_InvokeRepositoryAndCache()
- {
- await _atrService.UpdateCustomerAttribute(new CustomerAttribute());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CustomerAttribute>>(), default(CancellationToken)), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- }
+ [TestMethod]
+ public async Task DeleteCustomerAttribute_ValidArguemnts_InvokeRepositoryAndCache()
+ {
+ await _atrService.DeleteCustomerAttribute(new CustomerAttribute());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CustomerAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerAttribute>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ }
- [TestMethod()]
- public async Task DeleteCustomerAttribute_ValidArguemnts_InvokeRepositoryAndCache()
- {
- await _atrService.DeleteCustomerAttribute(new CustomerAttribute());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CustomerAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerAttribute>>(), default(CancellationToken)), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- }
+ [TestMethod]
+ public async Task InsertCustomerAttributeValue_ValidArguemnts_InvokeRepositoryAndCache()
+ {
+ _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new CustomerAttribute()));
+ await _atrService.InsertCustomerAttributeValue(new CustomerAttributeValue());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerAttributeValue>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ }
- [TestMethod()]
- public async Task InsertCustomerAttributeValue_ValidArguemnts_InvokeRepositoryAndCache()
- {
- _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(() => Task.FromResult(new CustomerAttribute()));
- await _atrService.InsertCustomerAttributeValue(new CustomerAttributeValue());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerAttributeValue>>(), default(CancellationToken)), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- }
+ [TestMethod]
+ public async Task UpdateCustomerAttributeValue_ValidArguemnts_InvokeRepositoryAndCache()
+ {
+ _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new CustomerAttribute()));
+ await _atrService.UpdateCustomerAttributeValue(new CustomerAttributeValue());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CustomerAttributeValue>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ }
- [TestMethod()]
- public async Task UpdateCustomerAttributeValue_ValidArguemnts_InvokeRepositoryAndCache()
- {
- _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(() => Task.FromResult(new CustomerAttribute()));
- await _atrService.UpdateCustomerAttributeValue(new CustomerAttributeValue());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CustomerAttributeValue>>(), default(CancellationToken)), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- }
- [TestMethod()]
- public async Task DeleteCustomerAttributeValue_ValidArguemnts_InvokeRepositoryAndCache()
- {
- _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(() => Task.FromResult(new CustomerAttribute()));
- await _atrService.DeleteCustomerAttributeValue(new CustomerAttributeValue());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerAttributeValue>>(), default(CancellationToken)), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
- }
+ [TestMethod]
+ public async Task DeleteCustomerAttributeValue_ValidArguemnts_InvokeRepositoryAndCache()
+ {
+ _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(new CustomerAttribute()));
+ await _atrService.DeleteCustomerAttributeValue(new CustomerAttributeValue());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<CustomerAttribute>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerAttributeValue>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), true));
+ }
- [TestMethod()]
- public async Task GetAllCustomerAttributes_InvokeRepositoryAndCache()
- {
- await _atrService.GetAllCustomerAttributes();
- _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<CustomerAttribute>>>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GetAllCustomerAttributes_InvokeRepositoryAndCache()
+ {
+ await _atrService.GetAllCustomerAttributes();
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<CustomerAttribute>>>>()),
+ Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerHistoryPasswordServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerHistoryPasswordServiceTests.cs
index 8cc4a5ce8..5e0a1c682 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerHistoryPasswordServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerHistoryPasswordServiceTests.cs
@@ -1,49 +1,49 @@
using Grand.Business.Customers.Services;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class CustomerHistoryPasswordServiceTests
{
- [TestClass()]
- public class CustomerHistoryPasswordServiceTests
+ private CustomerHistoryPasswordService _customerHistoryPasswordService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CustomerHistoryPassword> _repository;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<CustomerHistoryPassword> _repository;
- private Mock<IMediator> _mediatorMock;
- private CustomerHistoryPasswordService _customerHistoryPasswordService;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<CustomerHistoryPassword>();
- _mediatorMock = new Mock<IMediator>();
- _customerHistoryPasswordService = new CustomerHistoryPasswordService(_repository, _mediatorMock.Object);
- }
+ _repository = new MongoDBRepositoryTest<CustomerHistoryPassword>();
+ _mediatorMock = new Mock<IMediator>();
+ _customerHistoryPasswordService = new CustomerHistoryPasswordService(_repository, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task InsertCustomerPasswordTest()
- {
- //Act
- await _customerHistoryPasswordService.InsertCustomerPassword(new Customer());
- //Asser
- Assert.IsTrue(_repository.Table.Any());
- }
+ [TestMethod]
+ public async Task InsertCustomerPasswordTest()
+ {
+ //Act
+ await _customerHistoryPasswordService.InsertCustomerPassword(new Customer());
+ //Asser
+ Assert.IsTrue(_repository.Table.Any());
+ }
- [TestMethod()]
- public async Task GetPasswordsTest()
- {
- //Arrange
- //Act
- await _customerHistoryPasswordService.InsertCustomerPassword(new Customer {Id = "1" });
- await _customerHistoryPasswordService.InsertCustomerPassword(new Customer { Id = "1" });
+ [TestMethod]
+ public async Task GetPasswordsTest()
+ {
+ //Arrange
+ //Act
+ await _customerHistoryPasswordService.InsertCustomerPassword(new Customer { Id = "1" });
+ await _customerHistoryPasswordService.InsertCustomerPassword(new Customer { Id = "1" });
- //Act
- var result = await _customerHistoryPasswordService.GetPasswords("1", 1);
- //Asser
- Assert.IsTrue(result.Count == 1);
- }
+ //Act
+ var result = await _customerHistoryPasswordService.GetPasswords("1", 1);
+ //Asser
+ Assert.IsTrue(result.Count == 1);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
index 904b224d9..58ddc91e2 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerManagerServiceTests.cs
@@ -2,87 +2,91 @@
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.Customers;
+using Grand.Business.Core.Utilities.Customers;
using Grand.Business.Customers.Services;
using Grand.Domain.Customers;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class CustomerManagerServiceTests
{
- [TestClass()]
- public class CustomerManagerServiceTests
+ private Mock<ICustomerHistoryPasswordService> _customerHistoryPasswordServiceMock;
+ private CustomerManagerService _customerManagerService;
+
+ private Mock<ICustomerService> _customerServiceMock;
+ private CustomerSettings _customerSettings;
+ private Mock<IEncryptionService> _encryptionServiceMock;
+ private Mock<IGroupService> _groupServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<ITranslationService> _translationServiceMock;
+ private Mock<IUserFieldService> _userFieldServiceMock;
+
+ [TestInitialize]
+ public void Init()
{
+ _customerServiceMock = new Mock<ICustomerService>();
+ _groupServiceMock = new Mock<IGroupService>();
+ _encryptionServiceMock = new Mock<IEncryptionService>();
+ _translationServiceMock = new Mock<ITranslationService>();
+ _mediatorMock = new Mock<IMediator>();
+ _userFieldServiceMock = new Mock<IUserFieldService>();
+ _customerHistoryPasswordServiceMock = new Mock<ICustomerHistoryPasswordService>();
+ _customerSettings = new CustomerSettings {
+ AllowUsersToChangeUsernames = true
+ };
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<IGroupService> _groupServiceMock;
- private Mock<IEncryptionService> _encryptionServiceMock;
- private Mock<ITranslationService> _translationServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IUserFieldService> _userFieldServiceMock;
- private Mock<ICustomerHistoryPasswordService> _customerHistoryPasswordServiceMock;
- private CustomerSettings _customerSettings;
- private CustomerManagerService _customerManagerService;
- [TestInitialize()]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
- _groupServiceMock = new Mock<IGroupService>();
- _encryptionServiceMock = new Mock<IEncryptionService>();
- _translationServiceMock = new Mock<ITranslationService>();
- _mediatorMock = new Mock<IMediator>();
- _userFieldServiceMock = new Mock<IUserFieldService>();
- _customerHistoryPasswordServiceMock = new Mock<ICustomerHistoryPasswordService>();
- _customerSettings = new CustomerSettings {
- AllowUsersToChangeUsernames = true
- };
+ _customerManagerService = new CustomerManagerService(_customerServiceMock.Object, _groupServiceMock.Object,
+ _encryptionServiceMock.Object, _mediatorMock.Object, _userFieldServiceMock.Object,
+ _customerHistoryPasswordServiceMock.Object, _customerSettings);
+ }
- _customerManagerService = new CustomerManagerService(_customerServiceMock.Object, _groupServiceMock.Object,
- _encryptionServiceMock.Object, _mediatorMock.Object, _userFieldServiceMock.Object,
- _customerHistoryPasswordServiceMock.Object, _customerSettings);
- }
-
- [TestMethod()]
- public async Task LoginCustomerTest_WrongPassword()
- {
- //Arrange
- var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "12345" };
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));
- _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
- //Act
- var result = await _customerManagerService.LoginCustomer("[email protected]", "123456");
- //Assert
- Assert.AreEqual(CustomerLoginResults.WrongPassword, result);
- }
- [TestMethod()]
- public async Task LoginCustomerTest_Successful()
- {
- //Arrange
- var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));
- _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
- //Act
- var result = await _customerManagerService.LoginCustomer("[email protected]", "123456");
- //Assert
- Assert.AreEqual(CustomerLoginResults.Successful, result);
- }
-
- [TestMethod()]
- public async Task ChangePasswordTest_Success()
- {
- //Arrange
- var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };
- _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>())).Returns(() => Task.FromResult<Customer>(customer));
+ [TestMethod]
+ public async Task LoginCustomerTest_WrongPassword()
+ {
+ //Arrange
+ var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "12345" };
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(customer));
+ _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
+ //Act
+ var result = await _customerManagerService.LoginCustomer("[email protected]", "123456");
+ //Assert
+ Assert.AreEqual(CustomerLoginResults.WrongPassword, result);
+ }
+
+ [TestMethod]
+ public async Task LoginCustomerTest_Successful()
+ {
+ //Arrange
+ var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(customer));
+ _groupServiceMock.Setup(c => c.IsRegistered(It.IsAny<Customer>())).Returns(() => Task.FromResult(true));
+ //Act
+ var result = await _customerManagerService.LoginCustomer("[email protected]", "123456");
+ //Assert
+ Assert.AreEqual(CustomerLoginResults.Successful, result);
+ }
+
+ [TestMethod]
+ public async Task ChangePasswordTest_Success()
+ {
+ //Arrange
+ var customer = new Customer { Active = true, PasswordFormatId = PasswordFormat.Clear, Password = "123456" };
+ _customerServiceMock.Setup(c => c.GetCustomerByEmail(It.IsAny<string>()))
+ .Returns(() => Task.FromResult(customer));
- var changepassword = new Core.Utilities.Customers.ChangePasswordRequest("[email protected]",
- PasswordFormat.Clear,
- "zxcvbn", "123456");
- //Act
- await _customerManagerService.ChangePassword(changepassword);
- //Assert
- var passwordMatch = _customerManagerService.PasswordMatch(PasswordFormat.Clear, "zxcvb", "zxcvb", string.Empty);
- Assert.IsTrue(passwordMatch);
- }
-
+ var changepassword = new ChangePasswordRequest("[email protected]",
+ PasswordFormat.Clear,
+ "zxcvbn", "123456");
+ //Act
+ await _customerManagerService.ChangePassword(changepassword);
+ //Assert
+ var passwordMatch = _customerManagerService.PasswordMatch(PasswordFormat.Clear, "zxcvb", "zxcvb", string.Empty);
+ Assert.IsTrue(passwordMatch);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerNoteServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerNoteServiceTests.cs
index 010381053..d295b3aef 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerNoteServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerNoteServiceTests.cs
@@ -1,55 +1,55 @@
using Grand.Business.Customers.Services;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class CustomerNoteServiceTests
{
- [TestClass()]
- public class CustomerNoteServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private CustomerNoteService _noteService;
+ private Mock<IRepository<CustomerNote>> _repositoryMock;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<IRepository<CustomerNote>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private CustomerNoteService _noteService;
+ _repositoryMock = new Mock<IRepository<CustomerNote>>();
+ _mediatorMock = new Mock<IMediator>();
+ _noteService = new CustomerNoteService(_repositoryMock.Object, _mediatorMock.Object);
+ }
- [TestInitialize()]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<CustomerNote>>();
- _mediatorMock = new Mock<IMediator>();
- _noteService = new CustomerNoteService(_repositoryMock.Object, _mediatorMock.Object);
- }
- [TestMethod()]
- public async Task GetCustomerNoteTest()
- {
- await _noteService.GetCustomerNote("1");
- _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ [TestMethod]
+ public async Task GetCustomerNoteTest()
+ {
+ await _noteService.GetCustomerNote("1");
+ _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
- }
- [TestMethod()]
- public async Task GetCustomerNoteTest_Null()
- {
- await _noteService.GetCustomerNote("");
- _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Never);
+ [TestMethod]
+ public async Task GetCustomerNoteTest_Null()
+ {
+ await _noteService.GetCustomerNote("");
+ _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Never);
+ }
- }
- [TestMethod()]
- public async Task InsertCustomerNote_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _noteService.InsertCustomerNote(new CustomerNote());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CustomerNote>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerNote>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertCustomerNote_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _noteService.InsertCustomerNote(new CustomerNote());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<CustomerNote>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CustomerNote>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteCustomerNote_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _noteService.DeleteCustomerNote(new CustomerNote());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CustomerNote>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerNote>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteCustomerNote_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _noteService.DeleteCustomerNote(new CustomerNote());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<CustomerNote>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<CustomerNote>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
index 75ee336dd..c3ebeebe6 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/CustomerServiceTests.cs
@@ -2,463 +2,470 @@
using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Queries.Customers;
using Grand.Business.Customers.Services;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Common;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Orders;
-using MediatR;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
-using Moq;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
+using MediatR;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Moq;
+
+namespace Grand.Business.Customers.Tests.Services;
-namespace Grand.Business.Customers.Tests.Services
+[TestClass]
+public class CustomerServiceTests
{
- [TestClass()]
- public class CustomerServiceTests
- {
- private IRepository<Customer> _repository;
- private Mock<IMediator> _mediatorMock;
- private IUserFieldService _userFieldService;
- private MemoryCacheBase _cacheBase;
- private CustomerService _customerService;
- [TestInitialize()]
- public void TestInitialize()
- {
- _repository = new MongoDBRepositoryTest<Customer>();
- _mediatorMock = new Mock<IMediator>();
- _userFieldService = new UserFieldService(new MongoDBRepositoryTest<UserFieldBaseEntity>());
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
-
- _customerService = new CustomerService(_repository, _userFieldService, _mediatorMock.Object, _cacheBase);
- }
-
-
- [TestMethod()]
- public async Task GetOnlineCustomersTest()
- {
- //Assert
- await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow.AddDays(-1) });
- await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow });
- await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow });
- //Act
- var result = await _customerService.GetOnlineCustomers(DateTime.UtcNow.AddMinutes(-1), null);
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task GetCountOnlineShoppingCartTest()
- {
- //Assert
- await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow.AddDays(-1) });
- await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow });
- var customer = new Customer { LastUpdateCartDateUtc = DateTime.UtcNow, Active = true };
- customer.ShoppingCartItems.Add(new Domain.Orders.ShoppingCartItem { CreatedOnUtc = DateTime.UtcNow, ShoppingCartTypeId = Domain.Orders.ShoppingCartType.ShoppingCart });
- await _repository.InsertAsync(customer);
- //Act
- var result = await _customerService.GetCountOnlineShoppingCart(DateTime.UtcNow.AddMinutes(-1), null);
- //Assert
- Assert.AreEqual(1, result);
- }
-
- [TestMethod()]
- public async Task GetCustomerByIdTest()
- {
- //Assert
- await _repository.InsertAsync(new Customer { Id = "1" });
- //Act
- var result = await _customerService.GetCustomerById("1");
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCustomersByIdsTest()
- {
- //Assert
- await _repository.InsertAsync(new Customer { Id = "1" });
- await _repository.InsertAsync(new Customer { Id = "2" });
- await _repository.InsertAsync(new Customer { Id = "3" });
- //Act
- var result = await _customerService.GetCustomersByIds(["1", "2"]);
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task GetCustomerByGuidTest()
- {
- //Assert
- var guid = Guid.NewGuid();
- await _repository.InsertAsync(new Customer { CustomerGuid = guid });
- //Act
- var result = await _customerService.GetCustomerByGuid(guid);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCustomerByEmailTest()
- {
- //Assert
- var email = "[email protected]";
- await _repository.InsertAsync(new Customer { Email = email });
- //Act
- var result = await _customerService.GetCustomerByEmail(email);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCustomerBySystemNameTest()
- {
- //Assert
- var systemName = "sample";
- await _repository.InsertAsync(new Customer { SystemName = systemName });
- //Act
- var result = await _customerService.GetCustomerBySystemName(systemName);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCustomerByUsernameTest()
- {
- //Assert
- var userName = "user";
- await _repository.InsertAsync(new Customer { Username = userName });
- //Act
- var result = await _customerService.GetCustomerByUsername(userName);
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task InsertGuestCustomerTest()
- {
- //Arrange
- var cg = new CustomerGroup();
- _mediatorMock.Setup(x => x.Send(It.IsAny<GetGroupBySystemNameQuery>(), default))
- .Returns(Task.FromResult(cg));
-
- var customer = new Customer {
- CustomerGuid = Guid.NewGuid(),
- Active = true,
- StoreId = "1",
- LastActivityDateUtc = DateTime.UtcNow,
- };
-
- //Act
- await _customerService.InsertGuestCustomer(customer);
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- Assert.IsTrue(_repository.Table.Any(x => x.StoreId == "1"));
- }
-
- [TestMethod()]
- public async Task InsertCustomerTest()
- {
- //Act
- await _customerService.InsertCustomer(new Customer());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCustomerFieldTest()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.UpdateCustomerField(customer, x => x.Email, "[email protected]");
- //Assert
- Assert.AreEqual("[email protected]", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Email);
- }
-
- [TestMethod()]
- public async Task UpdateCustomerFieldTest_Type()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.UpdateCustomerField<string>(customer, x => x.Username, "username");
- //Assert
- Assert.AreEqual("username", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Username);
- }
-
- [TestMethod()]
- public async Task UpdateCustomerTest()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- customer.Email = "[email protected]";
- await _customerService.UpdateCustomer(customer);
- //Assert
- Assert.AreEqual("[email protected]", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Email);
- }
-
- [TestMethod()]
- public async Task DeleteCustomerTest()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.DeleteCustomer(customer);
- //Assert
- Assert.IsTrue(_repository.Table.FirstOrDefault(x=>x.Id == customer.Id).Deleted);
- }
-
- [TestMethod()]
- public async Task DeleteCustomerTest_Hard()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.DeleteCustomer(customer, true);
- //Assert
- Assert.IsFalse(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCustomerLastLoginDateTest()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- var date = DateTime.UtcNow;
- customer.LastLoginDateUtc = date;
- await _customerService.UpdateCustomerLastLoginDate(customer);
- //Assert
- Assert.AreEqual(date.ToString(), _repository.Table.FirstOrDefault(x => x.Id == customer.Id).LastLoginDateUtc.ToString());
- }
-
- [TestMethod()]
- public async Task UpdateCustomerinAdminPanelTest()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- customer.AdminComment = "test";
- await _customerService.UpdateCustomerInAdminPanel(customer);
- //Assert
- Assert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).AdminComment);
-
- }
-
- [TestMethod()]
- public async Task UpdateActiveTest()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]", Active = true };
- await _repository.InsertAsync(customer);
- //Act
- customer.Active = false;
- await _customerService.UpdateActive(customer);
- //Assert
- Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Active);
- }
-
- [TestMethod()]
- public async Task UpdateContributionsTest()
- {
- //Assert
- var customer = new Customer { Email = "[email protected]" };
- await _repository.InsertAsync(customer);
- //Act
- customer.Active = false;
- await _customerService.UpdateContributions(customer);
- //Assert
- Assert.AreEqual(true, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).HasContributions);
- }
-
- [TestMethod()]
- public async Task DeleteGuestCustomersTest()
- {
- //Arrange
- var cg = new CustomerGroup();
- _mediatorMock.Setup(x => x.Send(It.IsAny<GetGroupBySystemNameQuery>(), default))
- .Returns(Task.FromResult(cg));
-
- var customer = new Customer { };
- customer.Groups.Add(cg.Id);
- await _repository.InsertAsync(customer);
- var customer2 = new Customer { };
- customer2.Groups.Add("1");
- await _repository.InsertAsync(customer2);
- //Act
- await _customerService.DeleteGuestCustomers(null, null, onlyWithoutShoppingCart: false);
- //Assert
- Assert.AreEqual(1, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task DeleteCustomerGroupInCustomerTest()
- {
- //Arrange
- var cg = new CustomerGroup();
- var customer = new Customer();
- customer.Groups.Add(cg.Id);
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.DeleteCustomerGroupInCustomer(cg, customer.Id);
- //Assert
- Assert.AreEqual(0, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Groups.Count);
- }
-
- [TestMethod()]
- public async Task InsertCustomerGroupInCustomerTest()
- {
- //Arrange
- var cg = new CustomerGroup();
- var customer = new Customer();
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.InsertCustomerGroupInCustomer(cg, customer.Id);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Groups.Count);
- }
-
- [TestMethod()]
- public async Task DeleteAddressTest()
- {
- //Arrange
- var address = new Address();
- var customer = new Customer();
- customer.Addresses.Add(address);
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.DeleteAddress(address, customer.Id);
- //Assert
- Assert.AreEqual(0, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.Count);
- }
-
- [TestMethod()]
- public async Task InsertAddressTest()
- {
- //Arrange
- var customer = new Customer();
- await _repository.InsertAsync(customer);
- //Act
- var address = new Address();
- await _customerService.InsertAddress(address, customer.Id);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.Count);
- }
-
- [TestMethod()]
- public async Task UpdateAddressTest()
- {
- //Arrange
- var address = new Address();
- var customer = new Customer();
- customer.Addresses.Add(address);
- await _repository.InsertAsync(customer);
- //Act
- address.Name = "sample";
- await _customerService.UpdateAddress(address, customer.Id);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.Count);
- Assert.AreEqual("sample", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.FirstOrDefault(x => x.Id == address.Id).Name);
- }
-
- [TestMethod()]
- public async Task UpdateBillingAddressTest()
- {
- //Arrange
- var customer = new Customer();
- await _repository.InsertAsync(customer);
- //Act
- var address = new Address {
- Name = "BillingAddress"
- };
- await _customerService.UpdateBillingAddress(address, customer.Id);
- //Assert
- Assert.AreEqual("BillingAddress", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).BillingAddress.Name);
- }
-
- [TestMethod()]
- public async Task UpdateShippingAddressTest()
- {
- //Arrange
- var customer = new Customer();
- await _repository.InsertAsync(customer);
- //Act
- var address = new Address {
- Name = "ShippingAddress"
- };
- await _customerService.UpdateShippingAddress(address, customer.Id);
- //Assert
- Assert.AreEqual("ShippingAddress", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShippingAddress.Name);
- }
-
- [TestMethod()]
- public async Task DeleteShoppingCartItemTest()
- {
- //Arrange
- var customer = new Customer();
- var cart = new ShoppingCartItem();
- customer.ShoppingCartItems.Add(cart);
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.DeleteShoppingCartItem(customer.Id, cart);
- //Assert
- Assert.AreEqual(0, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems.Count);
- }
-
- [TestMethod()]
- public async Task ClearShoppingCartItemTest()
- {
- //Arrange
- var customer = new Customer();
- var cart = new ShoppingCartItem();
- var cart2 = new ShoppingCartItem();
- customer.ShoppingCartItems.Add(cart);
- customer.ShoppingCartItems.Add(cart2);
- await _repository.InsertAsync(customer);
- //Act
- await _customerService.ClearShoppingCartItem(customer.Id, new List<ShoppingCartItem> { cart });
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems.Count);
- }
-
- [TestMethod()]
- public async Task InsertShoppingCartItemTest()
- {
- //Arrange
- var customer = new Customer();
- await _repository.InsertAsync(customer);
- //Act
- var cart = new ShoppingCartItem();
- await _customerService.InsertShoppingCartItem(customer.Id, cart);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems.Count);
-
- }
-
- [TestMethod()]
- public async Task UpdateShoppingCartItemTest()
- {
- //Arrange
- var customer = new Customer();
- var cart = new ShoppingCartItem();
- customer.ShoppingCartItems.Add(cart);
- await _repository.InsertAsync(customer);
- //Act
- cart.Parameter = "test";
- await _customerService.UpdateShoppingCartItem(customer.Id, cart);
- //Assert
- Assert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems.FirstOrDefault(x => x.Id == cart.Id).Parameter);
- }
+ private MemoryCacheBase _cacheBase;
+ private CustomerService _customerService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Customer> _repository;
+ private IUserFieldService _userFieldService;
+
+ [TestInitialize]
+ public void TestInitialize()
+ {
+ _repository = new MongoDBRepositoryTest<Customer>();
+ _mediatorMock = new Mock<IMediator>();
+ _userFieldService = new UserFieldService(new MongoDBRepositoryTest<UserFieldBaseEntity>());
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+
+ _customerService = new CustomerService(_repository, _userFieldService, _mediatorMock.Object, _cacheBase);
+ }
+
+
+ [TestMethod]
+ public async Task GetOnlineCustomersTest()
+ {
+ //Assert
+ await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow.AddDays(-1) });
+ await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow });
+ await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow });
+ //Act
+ var result = await _customerService.GetOnlineCustomers(DateTime.UtcNow.AddMinutes(-1), null);
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCountOnlineShoppingCartTest()
+ {
+ //Assert
+ await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow.AddDays(-1) });
+ await _repository.InsertAsync(new Customer { LastActivityDateUtc = DateTime.UtcNow });
+ var customer = new Customer { LastUpdateCartDateUtc = DateTime.UtcNow, Active = true };
+ customer.ShoppingCartItems.Add(new ShoppingCartItem
+ { CreatedOnUtc = DateTime.UtcNow, ShoppingCartTypeId = ShoppingCartType.ShoppingCart });
+ await _repository.InsertAsync(customer);
+ //Act
+ var result = await _customerService.GetCountOnlineShoppingCart(DateTime.UtcNow.AddMinutes(-1), null);
+ //Assert
+ Assert.AreEqual(1, result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerByIdTest()
+ {
+ //Assert
+ await _repository.InsertAsync(new Customer { Id = "1" });
+ //Act
+ var result = await _customerService.GetCustomerById("1");
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomersByIdsTest()
+ {
+ //Assert
+ await _repository.InsertAsync(new Customer { Id = "1" });
+ await _repository.InsertAsync(new Customer { Id = "2" });
+ await _repository.InsertAsync(new Customer { Id = "3" });
+ //Act
+ var result = await _customerService.GetCustomersByIds(["1", "2"]);
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerByGuidTest()
+ {
+ //Assert
+ var guid = Guid.NewGuid();
+ await _repository.InsertAsync(new Customer { CustomerGuid = guid });
+ //Act
+ var result = await _customerService.GetCustomerByGuid(guid);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerByEmailTest()
+ {
+ //Assert
+ var email = "[email protected]";
+ await _repository.InsertAsync(new Customer { Email = email });
+ //Act
+ var result = await _customerService.GetCustomerByEmail(email);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerBySystemNameTest()
+ {
+ //Assert
+ var systemName = "sample";
+ await _repository.InsertAsync(new Customer { SystemName = systemName });
+ //Act
+ var result = await _customerService.GetCustomerBySystemName(systemName);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerByUsernameTest()
+ {
+ //Assert
+ var userName = "user";
+ await _repository.InsertAsync(new Customer { Username = userName });
+ //Act
+ var result = await _customerService.GetCustomerByUsername(userName);
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task InsertGuestCustomerTest()
+ {
+ //Arrange
+ var cg = new CustomerGroup();
+ _mediatorMock.Setup(x => x.Send(It.IsAny<GetGroupBySystemNameQuery>(), default))
+ .Returns(Task.FromResult(cg));
+
+ var customer = new Customer {
+ CustomerGuid = Guid.NewGuid(),
+ Active = true,
+ StoreId = "1",
+ LastActivityDateUtc = DateTime.UtcNow
+ };
+
+ //Act
+ await _customerService.InsertGuestCustomer(customer);
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ Assert.IsTrue(_repository.Table.Any(x => x.StoreId == "1"));
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerTest()
+ {
+ //Act
+ await _customerService.InsertCustomer(new Customer());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerFieldTest()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.UpdateCustomerField(customer, x => x.Email, "[email protected]");
+ //Assert
+ Assert.AreEqual("[email protected]", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Email);
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerFieldTest_Type()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.UpdateCustomerField(customer, x => x.Username, "username");
+ //Assert
+ Assert.AreEqual("username", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Username);
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerTest()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ customer.Email = "[email protected]";
+ await _customerService.UpdateCustomer(customer);
+ //Assert
+ Assert.AreEqual("[email protected]", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Email);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerTest()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.DeleteCustomer(customer);
+ //Assert
+ Assert.IsTrue(_repository.Table.FirstOrDefault(x => x.Id == customer.Id).Deleted);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerTest_Hard()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.DeleteCustomer(customer, true);
+ //Assert
+ Assert.IsFalse(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerLastLoginDateTest()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ var date = DateTime.UtcNow;
+ customer.LastLoginDateUtc = date;
+ await _customerService.UpdateCustomerLastLoginDate(customer);
+ //Assert
+ Assert.AreEqual(date.ToString(),
+ _repository.Table.FirstOrDefault(x => x.Id == customer.Id).LastLoginDateUtc.ToString());
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerinAdminPanelTest()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ customer.AdminComment = "test";
+ await _customerService.UpdateCustomerInAdminPanel(customer);
+ //Assert
+ Assert.AreEqual("test", _repository.Table.FirstOrDefault(x => x.Id == customer.Id).AdminComment);
+ }
+
+ [TestMethod]
+ public async Task UpdateActiveTest()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]", Active = true };
+ await _repository.InsertAsync(customer);
+ //Act
+ customer.Active = false;
+ await _customerService.UpdateActive(customer);
+ //Assert
+ Assert.AreEqual(false, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Active);
+ }
+
+ [TestMethod]
+ public async Task UpdateContributionsTest()
+ {
+ //Assert
+ var customer = new Customer { Email = "[email protected]" };
+ await _repository.InsertAsync(customer);
+ //Act
+ customer.Active = false;
+ await _customerService.UpdateContributions(customer);
+ //Assert
+ Assert.AreEqual(true, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).HasContributions);
+ }
+
+ [TestMethod]
+ public async Task DeleteGuestCustomersTest()
+ {
+ //Arrange
+ var cg = new CustomerGroup();
+ _mediatorMock.Setup(x => x.Send(It.IsAny<GetGroupBySystemNameQuery>(), default))
+ .Returns(Task.FromResult(cg));
+
+ var customer = new Customer();
+ customer.Groups.Add(cg.Id);
+ await _repository.InsertAsync(customer);
+ var customer2 = new Customer();
+ customer2.Groups.Add("1");
+ await _repository.InsertAsync(customer2);
+ //Act
+ await _customerService.DeleteGuestCustomers(null, null, false);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerGroupInCustomerTest()
+ {
+ //Arrange
+ var cg = new CustomerGroup();
+ var customer = new Customer();
+ customer.Groups.Add(cg.Id);
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.DeleteCustomerGroupInCustomer(cg, customer.Id);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Groups.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerGroupInCustomerTest()
+ {
+ //Arrange
+ var cg = new CustomerGroup();
+ var customer = new Customer();
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.InsertCustomerGroupInCustomer(cg, customer.Id);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Groups.Count);
+ }
+
+ [TestMethod]
+ public async Task DeleteAddressTest()
+ {
+ //Arrange
+ var address = new Address();
+ var customer = new Customer();
+ customer.Addresses.Add(address);
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.DeleteAddress(address, customer.Id);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertAddressTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ await _repository.InsertAsync(customer);
+ //Act
+ var address = new Address();
+ await _customerService.InsertAddress(address, customer.Id);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateAddressTest()
+ {
+ //Arrange
+ var address = new Address();
+ var customer = new Customer();
+ customer.Addresses.Add(address);
+ await _repository.InsertAsync(customer);
+ //Act
+ address.Name = "sample";
+ await _customerService.UpdateAddress(address, customer.Id);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.Count);
+ Assert.AreEqual("sample",
+ _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Addresses.FirstOrDefault(x => x.Id == address.Id)
+ .Name);
+ }
+
+ [TestMethod]
+ public async Task UpdateBillingAddressTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ await _repository.InsertAsync(customer);
+ //Act
+ var address = new Address {
+ Name = "BillingAddress"
+ };
+ await _customerService.UpdateBillingAddress(address, customer.Id);
+ //Assert
+ Assert.AreEqual("BillingAddress",
+ _repository.Table.FirstOrDefault(x => x.Id == customer.Id).BillingAddress.Name);
+ }
+
+ [TestMethod]
+ public async Task UpdateShippingAddressTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ await _repository.InsertAsync(customer);
+ //Act
+ var address = new Address {
+ Name = "ShippingAddress"
+ };
+ await _customerService.UpdateShippingAddress(address, customer.Id);
+ //Assert
+ Assert.AreEqual("ShippingAddress",
+ _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShippingAddress.Name);
+ }
+
+ [TestMethod]
+ public async Task DeleteShoppingCartItemTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ var cart = new ShoppingCartItem();
+ customer.ShoppingCartItems.Add(cart);
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.DeleteShoppingCartItem(customer.Id, cart);
+ //Assert
+ Assert.AreEqual(0, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems.Count);
+ }
+
+ [TestMethod]
+ public async Task ClearShoppingCartItemTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ var cart = new ShoppingCartItem();
+ var cart2 = new ShoppingCartItem();
+ customer.ShoppingCartItems.Add(cart);
+ customer.ShoppingCartItems.Add(cart2);
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerService.ClearShoppingCartItem(customer.Id, new List<ShoppingCartItem> { cart });
+ //Assert
+ Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertShoppingCartItemTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ await _repository.InsertAsync(customer);
+ //Act
+ var cart = new ShoppingCartItem();
+ await _customerService.InsertShoppingCartItem(customer.Id, cart);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateShoppingCartItemTest()
+ {
+ //Arrange
+ var customer = new Customer();
+ var cart = new ShoppingCartItem();
+ customer.ShoppingCartItems.Add(cart);
+ await _repository.InsertAsync(customer);
+ //Act
+ cart.Parameter = "test";
+ await _customerService.UpdateShoppingCartItem(customer.Id, cart);
+ //Assert
+ Assert.AreEqual("test",
+ _repository.Table.FirstOrDefault(x => x.Id == customer.Id).ShoppingCartItems
+ .FirstOrDefault(x => x.Id == cart.Id).Parameter);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/SalesEmployeeServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/SalesEmployeeServiceTests.cs
index 213870127..ef3874e13 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/SalesEmployeeServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/SalesEmployeeServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Customers.Services;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,84 +9,84 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class SalesEmployeeServiceTests
{
- [TestClass()]
- public class SalesEmployeeServiceTests
- {
- private IRepository<SalesEmployee> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private SalesEmployeeService _salesEmployeeService;
+ private MemoryCacheBase _cacheBase;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<SalesEmployee> _repository;
+ private SalesEmployeeService _salesEmployeeService;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<SalesEmployee>();
- _mediatorMock = new Mock<IMediator>();
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<SalesEmployee>();
+ _mediatorMock = new Mock<IMediator>();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _salesEmployeeService = new SalesEmployeeService(_repository, _mediatorMock.Object, _cacheBase);
- }
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _salesEmployeeService = new SalesEmployeeService(_repository, _mediatorMock.Object, _cacheBase);
+ }
- [TestMethod()]
- public async Task GetSalesEmployeeByIdTest()
- {
- //Arrange
- var salesEmployee = new SalesEmployee();
- await _repository.InsertAsync(salesEmployee);
- //Act
- var result = await _salesEmployeeService.GetSalesEmployeeById(salesEmployee.Id);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task GetSalesEmployeeByIdTest()
+ {
+ //Arrange
+ var salesEmployee = new SalesEmployee();
+ await _repository.InsertAsync(salesEmployee);
+ //Act
+ var result = await _salesEmployeeService.GetSalesEmployeeById(salesEmployee.Id);
+ //Assert
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public async Task GetAllTest()
- {
- //Arrange
- await _repository.InsertAsync(new SalesEmployee());
- await _repository.InsertAsync(new SalesEmployee());
- await _repository.InsertAsync(new SalesEmployee());
- //Act
- var result = await _salesEmployeeService.GetAll();
- //Assert
- Assert.AreEqual(3, result.Count);
- }
+ [TestMethod]
+ public async Task GetAllTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new SalesEmployee());
+ await _repository.InsertAsync(new SalesEmployee());
+ await _repository.InsertAsync(new SalesEmployee());
+ //Act
+ var result = await _salesEmployeeService.GetAll();
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
- [TestMethod()]
- public async Task InsertSalesEmployeeTest()
- {
- //Act
- await _salesEmployeeService.InsertSalesEmployee(new SalesEmployee());
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
+ [TestMethod]
+ public async Task InsertSalesEmployeeTest()
+ {
+ //Act
+ await _salesEmployeeService.InsertSalesEmployee(new SalesEmployee());
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
- [TestMethod()]
- public async Task UpdateSalesEmployeeTest()
- {
- //Arrange
- var salesEmployee = new SalesEmployee();
- await _repository.InsertAsync(salesEmployee);
- //Act
- salesEmployee.Email = "[email protected]";
- await _salesEmployeeService.UpdateSalesEmployee(salesEmployee);
- //Assert
- Assert.AreEqual("[email protected]", _repository.Table.FirstOrDefault(x => x.Id == salesEmployee.Id).Email);
- }
+ [TestMethod]
+ public async Task UpdateSalesEmployeeTest()
+ {
+ //Arrange
+ var salesEmployee = new SalesEmployee();
+ await _repository.InsertAsync(salesEmployee);
+ //Act
+ salesEmployee.Email = "[email protected]";
+ await _salesEmployeeService.UpdateSalesEmployee(salesEmployee);
+ //Assert
+ Assert.AreEqual("[email protected]", _repository.Table.FirstOrDefault(x => x.Id == salesEmployee.Id).Email);
+ }
- [TestMethod()]
- public async Task DeleteSalesEmployeeTest()
- {
- //Arrange
- var salesEmployee = new SalesEmployee();
- await _repository.InsertAsync(salesEmployee);
- //Act
- await _salesEmployeeService.DeleteSalesEmployee(salesEmployee);
- //Assert
- Assert.IsFalse(_repository.Table.Any());
- }
+ [TestMethod]
+ public async Task DeleteSalesEmployeeTest()
+ {
+ //Arrange
+ var salesEmployee = new SalesEmployee();
+ await _repository.InsertAsync(salesEmployee);
+ //Act
+ await _salesEmployeeService.DeleteSalesEmployee(salesEmployee);
+ //Assert
+ Assert.IsFalse(_repository.Table.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/UserApiServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/UserApiServiceTests.cs
index 4418618ad..511f3b368 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/UserApiServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/UserApiServiceTests.cs
@@ -1,58 +1,57 @@
using Grand.Business.Customers.Services;
-using Grand.Domain.Customers;
using Grand.Data;
+using Grand.Domain.Customers;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class UserApiServiceTests
{
- [TestClass()]
- public class UserApiServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<UserApi>> _repositoryMock;
+ private UserApiService _userApiService;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<UserApi>>();
+ _mediatorMock = new Mock<IMediator>();
+ _userApiService = new UserApiService(_repositoryMock.Object, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetUserByIdTest()
+ {
+ await _userApiService.GetUserById("");
+ _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task InsertUserApi_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _userApiService.InsertUserApi(new UserApi());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<UserApi>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<UserApi>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteUserApi_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _userApiService.DeleteUserApi(new UserApi());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<UserApi>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<UserApi>>(), default), Times.Once);
+ }
+
+
+ [TestMethod]
+ public async Task UpdateUserApi_ValidArguments_InvokeRepositoryAndPublishEvent()
{
- private Mock<IRepository<UserApi>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private UserApiService _userApiService;
-
- [TestInitialize()]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<UserApi>>();
- _mediatorMock = new Mock<IMediator>();
- _userApiService = new UserApiService(_repositoryMock.Object, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetUserByIdTest()
- {
- await _userApiService.GetUserById("");
- _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
-
- }
- [TestMethod()]
- public async Task InsertUserApi_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _userApiService.InsertUserApi(new UserApi());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<UserApi>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<UserApi>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public async Task DeleteUserApi_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _userApiService.DeleteUserApi(new UserApi());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<UserApi>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<UserApi>>(), default(CancellationToken)), Times.Once);
- }
-
-
- [TestMethod()]
- public async Task UpdateUserApi_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _userApiService.UpdateUserApi(new UserApi());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<UserApi>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<UserApi>>(), default(CancellationToken)), Times.Once);
- }
+ await _userApiService.UpdateUserApi(new UserApi());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<UserApi>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<UserApi>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Services/VendorServiceTests.cs b/src/Tests/Grand.Business.Customers.Tests/Services/VendorServiceTests.cs
index b881cfab3..a5e86be5f 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Services/VendorServiceTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Services/VendorServiceTests.cs
@@ -6,113 +6,113 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Customers.Tests.Services
+namespace Grand.Business.Customers.Tests.Services;
+
+[TestClass]
+public class VendorServiceTests
{
- [TestClass()]
- public class VendorServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Vendor>> _repoMock;
+ private Mock<IRepository<VendorReview>> _vendorReviewRepositoryMock;
+ private VendorService _vendorService;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repoMock = new Mock<IRepository<Vendor>>();
+ _vendorReviewRepositoryMock = new Mock<IRepository<VendorReview>>();
+ _mediatorMock = new Mock<IMediator>();
+ _vendorService = new VendorService(_repoMock.Object, _vendorReviewRepositoryMock.Object, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetVendorByIdTest()
+ {
+ await _vendorService.GetVendorById("");
+ _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task GetVendorNoteById_Test()
+ {
+ await _vendorService.GetVendorNoteById("1", "1");
+ _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task InsertVendor_ValidArguments_InvokeRepositoryAndPublishEvent()
{
- private Mock<IRepository<Vendor>> _repoMock;
- private Mock<IRepository<VendorReview>> _vendorReviewRepositoryMock;
- private Mock<IMediator> _mediatorMock;
- private VendorService _vendorService;
-
- [TestInitialize()]
- public void Init()
- {
- _repoMock = new Mock<IRepository<Vendor>>();
- _vendorReviewRepositoryMock = new Mock<IRepository<VendorReview>>();
- _mediatorMock = new Mock<IMediator>();
- _vendorService = new VendorService(_repoMock.Object, _vendorReviewRepositoryMock.Object, _mediatorMock.Object);
- }
- [TestMethod()]
- public async Task GetVendorByIdTest()
- {
- await _vendorService.GetVendorById("");
- _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
-
- }
-
- [TestMethod()]
- public async Task GetVendorNoteById_Test()
- {
- await _vendorService.GetVendorNoteById("1", "1");
- _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
-
- }
-
- [TestMethod()]
- public async Task InsertVendor_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _vendorService.InsertVendor(new Vendor());
- _repoMock.Verify(c => c.InsertAsync(It.IsAny<Vendor>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Vendor>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public async Task DeleteVendor_ValidArguments_SoftDeleteAndPublishEvent()
- {
- var vendor = new Vendor();
- await _vendorService.DeleteVendor(vendor);
- //soft delete
- Assert.IsTrue(vendor.Deleted);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Vendor>>(), default(CancellationToken)), Times.Once);
- }
-
-
- [TestMethod()]
- public async Task UpdateVendor_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _vendorService.UpdateVendor(new Vendor());
- _repoMock.Verify(c => c.UpdateAsync(It.IsAny<Vendor>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Vendor>>(), default(CancellationToken)), Times.Once);
- }
-
-
- [TestMethod()]
- public async Task InsertVendorReview_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _vendorService.InsertVendorReview(new VendorReview());
- _vendorReviewRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<VendorReview>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<VendorReview>>(), default(CancellationToken)), Times.Once);
- }
- [TestMethod()]
- public async Task UpdateVendorReview_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _vendorService.UpdateVendorReview(new VendorReview());
- //_vendorReviewRepositoryMock.Verify(c => c.UpdateOneAsync(x=>x.Id == It.IsAny<string>(), It.IsAny<UpdateBuilder<VendorReview>>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<VendorReview>>(), default(CancellationToken)), Times.Once);
- }
- [TestMethod()]
- public async Task UpdateVendorReviewTotal_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _vendorService.UpdateVendorReviewTotals(new Vendor());
- //_vendorReviewRepositoryMock.Verify(c => c.UpdateOneAsync(x=>x.Id == It.IsAny<string>(), It.IsAny<UpdateBuilder<VendorReview>>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Vendor>>(), default(CancellationToken)), Times.Once);
- }
- [TestMethod()]
- public async Task DeleteVendorReview_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _vendorService.DeleteVendorReview(new VendorReview());
- _vendorReviewRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<VendorReview>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<VendorReview>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public async Task InsertVendorNote_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _vendorService.InsertVendorNote(new VendorNote(), "1");
- _repoMock.Verify(c => c.AddToSet(It.IsAny<string>(), x=>x.VendorNotes, It.IsAny<VendorNote>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<VendorNote>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public async Task DeleteVendorNote_ValidArguments_SoftDeleteAndPublishEvent()
- {
- await _vendorService.DeleteVendorNote(new VendorNote(), "1");
- _repoMock.Verify(c => c.PullFilter(It.IsAny<string>(), x => x.VendorNotes, x => x.Id, It.IsAny<string>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<VendorNote>>(), default(CancellationToken)), Times.Once);
- }
+ await _vendorService.InsertVendor(new Vendor());
+ _repoMock.Verify(c => c.InsertAsync(It.IsAny<Vendor>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Vendor>>(), default), Times.Once);
+ }
+ [TestMethod]
+ public async Task DeleteVendor_ValidArguments_SoftDeleteAndPublishEvent()
+ {
+ var vendor = new Vendor();
+ await _vendorService.DeleteVendor(vendor);
+ //soft delete
+ Assert.IsTrue(vendor.Deleted);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Vendor>>(), default), Times.Once);
+ }
+
+
+ [TestMethod]
+ public async Task UpdateVendor_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _vendorService.UpdateVendor(new Vendor());
+ _repoMock.Verify(c => c.UpdateAsync(It.IsAny<Vendor>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Vendor>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task InsertVendorReview_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _vendorService.InsertVendorReview(new VendorReview());
+ _vendorReviewRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<VendorReview>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<VendorReview>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task UpdateVendorReview_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _vendorService.UpdateVendorReview(new VendorReview());
+ //_vendorReviewRepositoryMock.Verify(c => c.UpdateOneAsync(x=>x.Id == It.IsAny<string>(), It.IsAny<UpdateBuilder<VendorReview>>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<VendorReview>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task UpdateVendorReviewTotal_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _vendorService.UpdateVendorReviewTotals(new Vendor());
+ //_vendorReviewRepositoryMock.Verify(c => c.UpdateOneAsync(x=>x.Id == It.IsAny<string>(), It.IsAny<UpdateBuilder<VendorReview>>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Vendor>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteVendorReview_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _vendorService.DeleteVendorReview(new VendorReview());
+ _vendorReviewRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<VendorReview>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<VendorReview>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task InsertVendorNote_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _vendorService.InsertVendorNote(new VendorNote(), "1");
+ _repoMock.Verify(c => c.AddToSet(It.IsAny<string>(), x => x.VendorNotes, It.IsAny<VendorNote>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<VendorNote>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteVendorNote_ValidArguments_SoftDeleteAndPublishEvent()
+ {
+ await _vendorService.DeleteVendorNote(new VendorNote(), "1");
+ _repoMock.Verify(c => c.PullFilter(It.IsAny<string>(), x => x.VendorNotes, x => x.Id, It.IsAny<string>()),
+ Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<VendorNote>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Customers.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Customers.Tests/Startup/StartupApplicationTests.cs
index 24610c783..5040226a7 100644
--- a/src/Tests/Grand.Business.Customers.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Customers.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Customers.Tests.Startup
+namespace Grand.Business.Customers.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Extensions/ContactAttributeExtensionsTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Extensions/ContactAttributeExtensionsTests.cs
index cfd0bfd0c..ad92ea4fa 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Extensions/ContactAttributeExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Extensions/ContactAttributeExtensionsTests.cs
@@ -2,44 +2,42 @@
using Grand.Domain.Messages;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Marketing.Tests.Extensions
+namespace Grand.Business.Marketing.Tests.Extensions;
+
+[TestClass]
+public class ContactAttributeExtensionsTests
{
- [TestClass()]
- public class ContactAttributeExtensionsTests
+ [TestMethod]
+ public void ShouldHaveValues_ReturnExpentedResult()
{
+ var ca = new ContactAttribute { AttributeControlType = AttributeControlType.TextBox };
+ var ca2 = new ContactAttribute { AttributeControlType = AttributeControlType.MultilineTextbox };
+ var ca3 = new ContactAttribute { AttributeControlType = AttributeControlType.Datepicker };
+ var ca4 = new ContactAttribute { AttributeControlType = AttributeControlType.FileUpload };
+ var ca5 = new ContactAttribute { AttributeControlType = AttributeControlType.DropdownList };
+ ContactAttribute ca6 = null;
+ Assert.AreEqual(false, ca.ShouldHaveValues());
+ Assert.AreEqual(false, ca6.ShouldHaveValues());
+ Assert.AreEqual(false, ca2.ShouldHaveValues());
+ Assert.AreEqual(false, ca4.ShouldHaveValues());
+ Assert.AreEqual(false, ca3.ShouldHaveValues());
+ Assert.AreEqual(true, ca5.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues_ReturnExpentedResult()
- {
- var ca = new ContactAttribute { AttributeControlType = AttributeControlType.TextBox };
- var ca2 = new ContactAttribute { AttributeControlType = AttributeControlType.MultilineTextbox };
- var ca3 = new ContactAttribute { AttributeControlType = AttributeControlType.Datepicker };
- var ca4 = new ContactAttribute { AttributeControlType = AttributeControlType.FileUpload };
- var ca5 = new ContactAttribute { AttributeControlType = AttributeControlType.DropdownList };
- ContactAttribute ca6 = null;
- Assert.AreEqual(false, ca.ShouldHaveValues());
- Assert.AreEqual(false, ca6.ShouldHaveValues());
- Assert.AreEqual(false, ca2.ShouldHaveValues());
- Assert.AreEqual(false, ca4.ShouldHaveValues());
- Assert.AreEqual(false, ca3.ShouldHaveValues());
- Assert.AreEqual(true, ca5.ShouldHaveValues());
- }
-
- [TestMethod()]
- public void CanBeUsedAsCondition_ReturnExpentedResult()
- {
- var ca = new ContactAttribute { AttributeControlType = AttributeControlType.TextBox };
- var ca2 = new ContactAttribute { AttributeControlType = AttributeControlType.MultilineTextbox };
- var ca3 = new ContactAttribute { AttributeControlType = AttributeControlType.Datepicker };
- var ca4 = new ContactAttribute { AttributeControlType = AttributeControlType.FileUpload };
- var ca5 = new ContactAttribute { AttributeControlType = AttributeControlType.DropdownList };
- ContactAttribute ca6 = null;
- Assert.AreEqual(false, ca.CanBeUsedAsCondition());
- Assert.AreEqual(false, ca6.CanBeUsedAsCondition());
- Assert.AreEqual(false, ca2.CanBeUsedAsCondition());
- Assert.AreEqual(false, ca4.CanBeUsedAsCondition());
- Assert.AreEqual(false, ca3.CanBeUsedAsCondition());
- Assert.AreEqual(true, ca5.CanBeUsedAsCondition());
- }
+ [TestMethod]
+ public void CanBeUsedAsCondition_ReturnExpentedResult()
+ {
+ var ca = new ContactAttribute { AttributeControlType = AttributeControlType.TextBox };
+ var ca2 = new ContactAttribute { AttributeControlType = AttributeControlType.MultilineTextbox };
+ var ca3 = new ContactAttribute { AttributeControlType = AttributeControlType.Datepicker };
+ var ca4 = new ContactAttribute { AttributeControlType = AttributeControlType.FileUpload };
+ var ca5 = new ContactAttribute { AttributeControlType = AttributeControlType.DropdownList };
+ ContactAttribute ca6 = null;
+ Assert.AreEqual(false, ca.CanBeUsedAsCondition());
+ Assert.AreEqual(false, ca6.CanBeUsedAsCondition());
+ Assert.AreEqual(false, ca2.CanBeUsedAsCondition());
+ Assert.AreEqual(false, ca4.CanBeUsedAsCondition());
+ Assert.AreEqual(false, ca3.CanBeUsedAsCondition());
+ Assert.AreEqual(true, ca5.CanBeUsedAsCondition());
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs
index e2f1db331..2e0b70226 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Campaigns/CampaignServiceTests.cs
@@ -2,189 +2,194 @@
using Grand.Business.Core.Interfaces.Common.Stores;
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Marketing.Services.Campaigns;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Localization;
using Grand.Domain.Messages;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Campaigns
+namespace Grand.Business.Marketing.Tests.Services.Campaigns;
+
+[TestClass]
+public class CampaignServiceTests
{
- [TestClass()]
- public class CampaignServiceTests
+ private IRepository<CampaignHistory> _campaignHistoryRepository;
+ private IRepository<Campaign> _campaignRepository;
+ private CampaignService _campaignService;
+ private IRepository<Customer> _customerRepository;
+ private Mock<IEmailSender> _emailSenderMock;
+ private Mock<ILanguageService> _languageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<NewsLetterSubscription> _newsLetterSubscriptionRepository;
+ private Mock<IQueuedEmailService> _queuedEmailServiceMock;
+ private Mock<IStoreService> _storeServiceMock;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _campaignRepository = new MongoDBRepositoryTest<Campaign>();
+ _campaignHistoryRepository = new MongoDBRepositoryTest<CampaignHistory>();
+ _newsLetterSubscriptionRepository = new MongoDBRepositoryTest<NewsLetterSubscription>();
+ _customerRepository = new MongoDBRepositoryTest<Customer>();
+ _mediatorMock = new Mock<IMediator>();
+ _emailSenderMock = new Mock<IEmailSender>();
+ _queuedEmailServiceMock = new Mock<IQueuedEmailService>();
+ _storeServiceMock = new Mock<IStoreService>();
+ _languageServiceMock = new Mock<ILanguageService>();
+ _workContextMock = new Mock<IWorkContext>();
+ _campaignService = new CampaignService(_campaignRepository, _campaignHistoryRepository,
+ _newsLetterSubscriptionRepository, _customerRepository,
+ _emailSenderMock.Object, _queuedEmailServiceMock.Object, _storeServiceMock.Object, _mediatorMock.Object,
+ _languageServiceMock.Object, _workContextMock.Object);
+ }
+
+ [TestMethod]
+ public async Task InsertCampaignTest()
+ {
+ //Act
+ await _campaignService.InsertCampaign(new Campaign());
+ //Assert
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Campaign>>(), default), Times.Once);
+ Assert.IsTrue(_campaignRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertCampaignHistoryTest()
+ {
+ //Act
+ await _campaignService.InsertCampaignHistory(new CampaignHistory());
+ //Assert
+ Assert.IsTrue(_campaignHistoryRepository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCampaignTest()
{
- private IRepository<Campaign> _campaignRepository;
- private IRepository<CampaignHistory> _campaignHistoryRepository;
- private IRepository<NewsLetterSubscription> _newsLetterSubscriptionRepository;
- private IRepository<Customer> _customerRepository;
- private Mock<IEmailSender> _emailSenderMock;
- private Mock<IQueuedEmailService> _queuedEmailServiceMock;
- private Mock<IStoreService> _storeServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<ILanguageService> _languageServiceMock;
- private Mock<IWorkContext> _workContextMock;
- private CampaignService _campaignService;
-
- [TestInitialize()]
- public void Init()
- {
- _campaignRepository = new MongoDBRepositoryTest<Campaign>();
- _campaignHistoryRepository = new MongoDBRepositoryTest<CampaignHistory>();
- _newsLetterSubscriptionRepository = new MongoDBRepositoryTest<NewsLetterSubscription>();
- _customerRepository = new MongoDBRepositoryTest<Customer>();
- _mediatorMock = new Mock<IMediator>();
- _emailSenderMock = new Mock<IEmailSender>();
- _queuedEmailServiceMock = new Mock<IQueuedEmailService>();
- _storeServiceMock = new Mock<IStoreService>();
- _languageServiceMock = new Mock<ILanguageService>();
- _workContextMock = new Mock<IWorkContext>();
- _campaignService = new CampaignService(_campaignRepository, _campaignHistoryRepository, _newsLetterSubscriptionRepository, _customerRepository,
- _emailSenderMock.Object, _queuedEmailServiceMock.Object, _storeServiceMock.Object, _mediatorMock.Object, _languageServiceMock.Object, _workContextMock.Object);
-
- }
-
- [TestMethod()]
- public async Task InsertCampaignTest()
- {
- //Act
- await _campaignService.InsertCampaign(new Campaign());
- //Assert
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Campaign>>(), default(CancellationToken)), Times.Once);
- Assert.IsTrue(_campaignRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task InsertCampaignHistoryTest()
- {
- //Act
- await _campaignService.InsertCampaignHistory(new CampaignHistory());
- //Assert
- Assert.IsTrue(_campaignHistoryRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCampaignTest()
- {
- //Arrange
- var campaign = new Campaign();
- await _campaignService.InsertCampaign(campaign);
-
- //Act
- campaign.Subject = "test";
- await _campaignService.UpdateCampaign(campaign);
- //Assert
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Campaign>>(), default(CancellationToken)), Times.Once);
- Assert.IsTrue(_campaignRepository.Table.FirstOrDefault(x => x.Id == campaign.Id).Subject == "test");
- }
-
- [TestMethod()]
- public async Task DeleteCampaignTest()
- {
- //Arrange
- var campaign = new Campaign();
- await _campaignService.InsertCampaign(campaign);
-
- //Act
- await _campaignService.DeleteCampaign(campaign);
- //Assert
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Campaign>>(), default(CancellationToken)), Times.Once);
- Assert.IsFalse(_campaignRepository.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetCampaignByIdTest()
- {
- //Arrange
- var campaign = new Campaign {
- Name = "test"
- };
- await _campaignRepository.InsertAsync(campaign);
-
- //Act
- var result = await _campaignService.GetCampaignById(campaign.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task GetAllCampaignsTest()
- {
- //Arrange
- await _campaignRepository.InsertAsync(new Campaign());
- await _campaignRepository.InsertAsync(new Campaign());
- await _campaignRepository.InsertAsync(new Campaign());
-
- //Act
- var result = await _campaignService.GetAllCampaigns();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetCampaignHistoryTest()
- {
- //Arrange
- var campaign = new Campaign {
- Name = "test"
- };
- await _campaignRepository.InsertAsync(campaign);
- await _campaignHistoryRepository.InsertAsync(new CampaignHistory { CampaignId = campaign.Id });
- await _campaignHistoryRepository.InsertAsync(new CampaignHistory { CampaignId = campaign.Id });
-
- //Act
- var result = await _campaignService.GetCampaignHistory(campaign);
-
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task CustomerSubscriptionsTest()
- {
- //Arrange
- var campaign = new Campaign {
- Name = "test",
- StoreId = "1"
- };
- await _campaignRepository.InsertAsync(campaign);
- await _newsLetterSubscriptionRepository.InsertAsync(new NewsLetterSubscription { StoreId = "1", Active = true });
- //Act
- var result = await _campaignService.CustomerSubscriptions(campaign);
-
- //Assert
- Assert.AreEqual(1, result.Count);
- }
-
- [TestMethod()]
- public async Task SendCampaignTest()
- {
- //Arrange
- var campaign = new Campaign {
- Name = "test",
- StoreId = "1"
- };
- await _campaignRepository.InsertAsync(campaign);
- await _newsLetterSubscriptionRepository.InsertAsync(new NewsLetterSubscription { StoreId = "1", Active = true, Email = "[email protected]" });
-
- _languageServiceMock.Setup(x => x.GetLanguageById(It.IsAny<string>()))
- .Returns(Task.FromResult(new Language()));
- _storeServiceMock.Setup(x => x.GetStoreById(It.IsAny<string>()))
- .Returns(Task.FromResult(new Domain.Stores.Store()));
-
- //Act
- await _campaignService.SendCampaign(campaign, new EmailAccount { Host = "host.com" }, "[email protected]");
-
- //Assert
- _emailSenderMock.Verify(c => c.SendEmail(It.IsAny<EmailAccount>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), null,null, null, null, null, null, null), Times.Once);
- }
+ //Arrange
+ var campaign = new Campaign();
+ await _campaignService.InsertCampaign(campaign);
+
+ //Act
+ campaign.Subject = "test";
+ await _campaignService.UpdateCampaign(campaign);
+ //Assert
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Campaign>>(), default), Times.Once);
+ Assert.IsTrue(_campaignRepository.Table.FirstOrDefault(x => x.Id == campaign.Id).Subject == "test");
+ }
+
+ [TestMethod]
+ public async Task DeleteCampaignTest()
+ {
+ //Arrange
+ var campaign = new Campaign();
+ await _campaignService.InsertCampaign(campaign);
+
+ //Act
+ await _campaignService.DeleteCampaign(campaign);
+ //Assert
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Campaign>>(), default), Times.Once);
+ Assert.IsFalse(_campaignRepository.Table.Any());
+ }
+ [TestMethod]
+ public async Task GetCampaignByIdTest()
+ {
+ //Arrange
+ var campaign = new Campaign {
+ Name = "test"
+ };
+ await _campaignRepository.InsertAsync(campaign);
+
+ //Act
+ var result = await _campaignService.GetCampaignById(campaign.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task GetAllCampaignsTest()
+ {
+ //Arrange
+ await _campaignRepository.InsertAsync(new Campaign());
+ await _campaignRepository.InsertAsync(new Campaign());
+ await _campaignRepository.InsertAsync(new Campaign());
+
+ //Act
+ var result = await _campaignService.GetAllCampaigns();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCampaignHistoryTest()
+ {
+ //Arrange
+ var campaign = new Campaign {
+ Name = "test"
+ };
+ await _campaignRepository.InsertAsync(campaign);
+ await _campaignHistoryRepository.InsertAsync(new CampaignHistory { CampaignId = campaign.Id });
+ await _campaignHistoryRepository.InsertAsync(new CampaignHistory { CampaignId = campaign.Id });
+
+ //Act
+ var result = await _campaignService.GetCampaignHistory(campaign);
+
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task CustomerSubscriptionsTest()
+ {
+ //Arrange
+ var campaign = new Campaign {
+ Name = "test",
+ StoreId = "1"
+ };
+ await _campaignRepository.InsertAsync(campaign);
+ await _newsLetterSubscriptionRepository.InsertAsync(new NewsLetterSubscription
+ { StoreId = "1", Active = true });
+ //Act
+ var result = await _campaignService.CustomerSubscriptions(campaign);
+
+ //Assert
+ Assert.AreEqual(1, result.Count);
+ }
+
+ [TestMethod]
+ public async Task SendCampaignTest()
+ {
+ //Arrange
+ var campaign = new Campaign {
+ Name = "test",
+ StoreId = "1"
+ };
+ await _campaignRepository.InsertAsync(campaign);
+ await _newsLetterSubscriptionRepository.InsertAsync(new NewsLetterSubscription
+ { StoreId = "1", Active = true, Email = "[email protected]" });
+
+ _languageServiceMock.Setup(x => x.GetLanguageById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new Language()));
+ _storeServiceMock.Setup(x => x.GetStoreById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new Store()));
+
+ //Act
+ await _campaignService.SendCampaign(campaign, new EmailAccount { Host = "host.com" }, "[email protected]");
+
+ //Assert
+ _emailSenderMock.Verify(
+ c => c.SendEmail(It.IsAny<EmailAccount>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), null, null, null, null, null, null, null),
+ Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs
index 511c4689d..2dbbe3604 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeParserTests.cs
@@ -1,123 +1,133 @@
using Grand.Business.Core.Interfaces.Common.Localization;
using Grand.Business.Core.Interfaces.Marketing.Contacts;
using Grand.Business.Marketing.Services.Contacts;
+using Grand.Domain.Catalog;
using Grand.Domain.Common;
using Grand.Domain.Customers;
+using Grand.Domain.Localization;
using Grand.Domain.Messages;
using Grand.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Contacts
+namespace Grand.Business.Marketing.Tests.Services.Contacts;
+
+[TestClass]
+public class ContactAttributeParserTests
{
- [TestClass()]
- public class ContactAttributeParserTests
- {
- private Mock<IContactAttributeService> _contactAttributeServiceMock;
- private Mock<IWorkContext> _workContextMock;
- private ContactAttributeParser _parser;
- private List<CustomAttribute> customAtr;
- private List<ContactAttribute> _contactAtr;
+ private List<ContactAttribute> _contactAtr;
+ private Mock<IContactAttributeService> _contactAttributeServiceMock;
+ private ContactAttributeParser _parser;
+ private Mock<IWorkContext> _workContextMock;
+ private List<CustomAttribute> customAtr;
- [TestInitialize()]
- public void Init()
+ [TestInitialize]
+ public void Init()
+ {
+ _contactAttributeServiceMock = new Mock<IContactAttributeService>();
+ _workContextMock = new Mock<IWorkContext>();
+ var _translationServiceMock = new Mock<ITranslationService>();
{
- _contactAttributeServiceMock = new Mock<IContactAttributeService>();
- _workContextMock = new Mock<IWorkContext>();
- var _translationServiceMock = new Mock<ITranslationService>();
- {
- _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Warning{0}");
- }
+ _translationServiceMock.Setup(x => x.GetResource(It.IsAny<string>())).Returns("Warning{0}");
+ }
- _parser = new ContactAttributeParser(_contactAttributeServiceMock.Object, _workContextMock.Object);
- customAtr = [
- new CustomAttribute { Key = "key1", Value = "value1" },
- new CustomAttribute { Key = "key2", Value = "value2" },
- new CustomAttribute { Key = "key3", Value = "value3" },
- new CustomAttribute { Key = "key4", Value = "value4" }
- ];
+ _parser = new ContactAttributeParser(_contactAttributeServiceMock.Object, _workContextMock.Object);
+ customAtr = [
+ new CustomAttribute { Key = "key1", Value = "value1" },
+ new CustomAttribute { Key = "key2", Value = "value2" },
+ new CustomAttribute { Key = "key3", Value = "value3" },
+ new CustomAttribute { Key = "key4", Value = "value4" }
+ ];
- _contactAtr = [
- new ContactAttribute { Id = "key1", Name = "name1", AttributeControlType = Domain.Catalog.AttributeControlType.TextBox },
- new ContactAttribute { Id = "key2", Name = "name2" },
- new ContactAttribute { Id = "key3", Name = "name3" },
- new ContactAttribute { Id = "key4", Name = "name4" },
- new ContactAttribute { Id = "key5", Name = "name5" }
- ];
- _contactAtr.ForEach(c => c.ContactAttributeValues.Add(new ContactAttributeValue { Id = "value" + c.Id.Last() }));
- }
+ _contactAtr = [
+ new ContactAttribute { Id = "key1", Name = "name1", AttributeControlType = AttributeControlType.TextBox },
+ new ContactAttribute { Id = "key2", Name = "name2" },
+ new ContactAttribute { Id = "key3", Name = "name3" },
+ new ContactAttribute { Id = "key4", Name = "name4" },
+ new ContactAttribute { Id = "key5", Name = "name5" }
+ ];
+ _contactAtr.ForEach(c =>
+ c.ContactAttributeValues.Add(new ContactAttributeValue { Id = "value" + c.Id.Last() }));
+ }
- [TestMethod()]
- public async Task ParseContactAttributes_ReturnExpectedValues()
- {
- _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.ParseContactAttributes(customAtr);
- Assert.IsTrue(result.Count == 4);
- Assert.IsTrue(result.Any(c => c.Id.Equals("key1")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("key2")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("key3")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("key4")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("key5")));
- }
+ [TestMethod]
+ public async Task ParseContactAttributes_ReturnExpectedValues()
+ {
+ _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.ParseContactAttributes(customAtr);
+ Assert.IsTrue(result.Count == 4);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key1")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key2")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key3")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("key4")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("key5")));
+ }
- [TestMethod()]
- public async Task ParseCustomer0AttributeValues_ReturnExpectedValues()
- {
- _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.ParseContactAttributeValues(customAtr);
- Assert.IsTrue(result.Count == 3);
- Assert.IsTrue(result.Any(c => c.Id.Equals("value2")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("value3")));
- Assert.IsTrue(result.Any(c => c.Id.Equals("value4")));
- Assert.IsFalse(result.Any(c => c.Id.Equals("value5")));
- }
+ [TestMethod]
+ public async Task ParseCustomer0AttributeValues_ReturnExpectedValues()
+ {
+ _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.ParseContactAttributeValues(customAtr);
+ Assert.IsTrue(result.Count == 3);
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value2")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value3")));
+ Assert.IsTrue(result.Any(c => c.Id.Equals("value4")));
+ Assert.IsFalse(result.Any(c => c.Id.Equals("value5")));
+ }
- [TestMethod()]
- public void AddContactAttributeTest()
- {
- var result = _parser.AddContactAttribute(customAtr, new ContactAttribute { Id = "key7" }, "value7");
- Assert.IsTrue(result.Count == 5);
- Assert.IsTrue(result.Any(c => c.Key.Equals("key7")));
- }
+ [TestMethod]
+ public void AddContactAttributeTest()
+ {
+ var result = _parser.AddContactAttribute(customAtr, new ContactAttribute { Id = "key7" }, "value7");
+ Assert.IsTrue(result.Count == 5);
+ Assert.IsTrue(result.Any(c => c.Key.Equals("key7")));
+ }
- [TestMethod()]
- public async Task IsConditionMetTest_IsConditionMet_True()
- {
- _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var contactAttribute = new ContactAttribute { };
- contactAttribute.ConditionAttribute.Add(new CustomAttribute { Key = "key2", Value = "2" });
- var result = await _parser.IsConditionMet(contactAttribute, new List<CustomAttribute> { new CustomAttribute { Key = "key2", Value = "2" } });
- Assert.IsTrue(result);
- }
+ [TestMethod]
+ public async Task IsConditionMetTest_IsConditionMet_True()
+ {
+ _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var contactAttribute = new ContactAttribute();
+ contactAttribute.ConditionAttribute.Add(new CustomAttribute { Key = "key2", Value = "2" });
+ var result = await _parser.IsConditionMet(contactAttribute,
+ new List<CustomAttribute> { new() { Key = "key2", Value = "2" } });
+ Assert.IsTrue(result);
+ }
- [TestMethod()]
- public async Task IsConditionMetTest_IsConditionMet_False()
- {
- _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var contactAttribute = new ContactAttribute { };
- contactAttribute.ConditionAttribute.Add(new CustomAttribute { Key = "key2", Value = "2" });
- var result = await _parser.IsConditionMet(contactAttribute, new List<CustomAttribute> { new CustomAttribute { Key = "key3", Value = "2" } });
- Assert.IsFalse(result);
- }
+ [TestMethod]
+ public async Task IsConditionMetTest_IsConditionMet_False()
+ {
+ _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var contactAttribute = new ContactAttribute();
+ contactAttribute.ConditionAttribute.Add(new CustomAttribute { Key = "key2", Value = "2" });
+ var result = await _parser.IsConditionMet(contactAttribute,
+ new List<CustomAttribute> { new() { Key = "key3", Value = "2" } });
+ Assert.IsFalse(result);
+ }
- [TestMethod()]
- public void RemoveContactAttributeTest()
- {
- var result = _parser.RemoveContactAttribute(customAtr, new ContactAttribute { Id = "key1" });
- Assert.IsTrue(result.Count == 3);
- Assert.IsFalse(result.Any(c => c.Key.Equals("key1")));
- }
+ [TestMethod]
+ public void RemoveContactAttributeTest()
+ {
+ var result = _parser.RemoveContactAttribute(customAtr, new ContactAttribute { Id = "key1" });
+ Assert.IsTrue(result.Count == 3);
+ Assert.IsFalse(result.Any(c => c.Key.Equals("key1")));
+ }
- [TestMethod()]
- public async Task FormatAttributesTest()
- {
- _contactAttributeServiceMock.Setup(c => c.GetAllContactAttributes("", false)).Returns(() => Task.FromResult((IList<ContactAttribute>)_contactAtr));
- _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) => Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
- var result = await _parser.FormatAttributes(new Domain.Localization.Language(),
- new List<CustomAttribute> {
- new CustomAttribute {Key="key1",Value="value1" }
- }, new Customer());
- Assert.IsTrue(result == "name1: value1");
- }
+ [TestMethod]
+ public async Task FormatAttributesTest()
+ {
+ _contactAttributeServiceMock.Setup(c => c.GetAllContactAttributes("", false))
+ .Returns(() => Task.FromResult((IList<ContactAttribute>)_contactAtr));
+ _contactAttributeServiceMock.Setup(c => c.GetContactAttributeById(It.IsAny<string>())).Returns((string w) =>
+ Task.FromResult(_contactAtr.FirstOrDefault(a => a.Id.Equals(w))));
+ var result = await _parser.FormatAttributes(new Language(),
+ new List<CustomAttribute> {
+ new() { Key = "key1", Value = "value1" }
+ }, new Customer());
+ Assert.IsTrue(result == "name1: value1");
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs
index 408a11da6..e97d55313 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactAttributeServiceTests.cs
@@ -1,8 +1,9 @@
using Grand.Business.Marketing.Services.Contacts;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Domain.Messages;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -11,107 +12,108 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Contacts
+namespace Grand.Business.Marketing.Tests.Services.Contacts;
+
+[TestClass]
+public class ContactAttributeServiceTests
{
- [TestClass()]
- public class ContactAttributeServiceTests
+ private MemoryCacheBase _cacheBase;
+ private ContactAttributeService _contactAttributeService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<ContactAttribute> _repository;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<ContactAttribute>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
+ var accessControlConfig = new AccessControlConfig();
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _contactAttributeService = new ContactAttributeService(_cacheBase, _repository, _mediatorMock.Object,
+ _workContextMock.Object, accessControlConfig);
+ }
+
+ [TestMethod]
+ public async Task DeleteContactAttributeTest()
+ {
+ //Arrange
+ var contactAttribute = new ContactAttribute {
+ Name = "test"
+ };
+ await _contactAttributeService.InsertContactAttribute(contactAttribute);
+
+ //Act
+ await _contactAttributeService.DeleteContactAttribute(contactAttribute);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetAllContactAttributesTest()
+ {
+ //Arrange
+ await _contactAttributeService.InsertContactAttribute(new ContactAttribute());
+ await _contactAttributeService.InsertContactAttribute(new ContactAttribute());
+ await _contactAttributeService.InsertContactAttribute(new ContactAttribute());
+
+ //Act
+ var result = await _contactAttributeService.GetAllContactAttributes();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetContactAttributeByIdTest()
+ {
+ //Arrange
+ var contactAttribute = new ContactAttribute {
+ Name = "test"
+ };
+ await _contactAttributeService.InsertContactAttribute(contactAttribute);
+
+ //Act
+ var result = await _contactAttributeService.GetContactAttributeById(contactAttribute.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertContactAttributeTest()
+ {
+ //Act
+ var contactAttribute = new ContactAttribute {
+ Name = "test"
+ };
+ await _contactAttributeService.InsertContactAttribute(contactAttribute);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateContactAttributeTest()
{
- private ContactAttributeService _contactAttributeService;
- private IRepository<ContactAttribute> _repository;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
- private Mock<IWorkContext> _workContextMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<ContactAttribute>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => new Customer());
- var accessControlConfig = new AccessControlConfig();
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _contactAttributeService = new ContactAttributeService(_cacheBase, _repository, _mediatorMock.Object, _workContextMock.Object, accessControlConfig);
- }
-
- [TestMethod()]
- public async Task DeleteContactAttributeTest()
- {
- //Arrange
- var contactAttribute = new ContactAttribute {
- Name = "test"
- };
- await _contactAttributeService.InsertContactAttribute(contactAttribute);
-
- //Act
- await _contactAttributeService.DeleteContactAttribute(contactAttribute);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetAllContactAttributesTest()
- {
- //Arrange
- await _contactAttributeService.InsertContactAttribute(new ContactAttribute());
- await _contactAttributeService.InsertContactAttribute(new ContactAttribute());
- await _contactAttributeService.InsertContactAttribute(new ContactAttribute());
-
- //Act
- var result = await _contactAttributeService.GetAllContactAttributes();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetContactAttributeByIdTest()
- {
- //Arrange
- var contactAttribute = new ContactAttribute {
- Name = "test"
- };
- await _contactAttributeService.InsertContactAttribute(contactAttribute);
-
- //Act
- var result = await _contactAttributeService.GetContactAttributeById(contactAttribute.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task InsertContactAttributeTest()
- {
- //Act
- var contactAttribute = new ContactAttribute {
- Name = "test"
- };
- await _contactAttributeService.InsertContactAttribute(contactAttribute);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateContactAttributeTest()
- {
- //Arrange
- var contactAttribute = new ContactAttribute {
- Name = "test"
- };
- await _contactAttributeService.InsertContactAttribute(contactAttribute);
- contactAttribute.Name = "test2";
-
- //Act
- await _contactAttributeService.UpdateContactAttribute(contactAttribute);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
+ //Arrange
+ var contactAttribute = new ContactAttribute {
+ Name = "test"
+ };
+ await _contactAttributeService.InsertContactAttribute(contactAttribute);
+ contactAttribute.Name = "test2";
+
+ //Act
+ await _contactAttributeService.UpdateContactAttribute(contactAttribute);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactUsServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactUsServiceTests.cs
index f949fcd28..bbb58bb8a 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactUsServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Contacts/ContactUsServiceTests.cs
@@ -1,103 +1,102 @@
using Grand.Business.Marketing.Services.Contacts;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Messages;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Contacts
+namespace Grand.Business.Marketing.Tests.Services.Contacts;
+
+[TestClass]
+public class ContactUsServiceTests
{
- [TestClass()]
- public class ContactUsServiceTests
+ private ContactUsService _contactUsService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<ContactUs> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<ContactUs>();
+ _mediatorMock = new Mock<IMediator>();
+ _contactUsService = new ContactUsService(_repository, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task DeleteContactUsTest()
+ {
+ //Arrange
+ var contactUs = new ContactUs {
+ FullName = "test"
+ };
+ await _contactUsService.InsertContactUs(contactUs);
+
+ //Act
+ await _contactUsService.DeleteContactUs(contactUs);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.FullName == "test"));
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task ClearTableTest()
+ {
+ //Arrange
+ await _contactUsService.InsertContactUs(new ContactUs());
+ await _contactUsService.InsertContactUs(new ContactUs());
+ await _contactUsService.InsertContactUs(new ContactUs());
+
+ //Act
+ await _contactUsService.ClearTable();
+
+ //Assert
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetAllContactUsTest()
+ {
+ //Arrange
+ await _contactUsService.InsertContactUs(new ContactUs());
+ await _contactUsService.InsertContactUs(new ContactUs());
+ await _contactUsService.InsertContactUs(new ContactUs());
+
+ //Act
+ var result = await _contactUsService.GetAllContactUs();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetContactUsByIdTest()
+ {
+ //Arrange
+ var contactUs = new ContactUs {
+ FullName = "test"
+ };
+ await _contactUsService.InsertContactUs(contactUs);
+
+ //Act
+ var result = await _contactUsService.GetContactUsById(contactUs.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.FullName);
+ }
+
+ [TestMethod]
+ public async Task InsertContactUsTest()
{
- private ContactUsService _contactUsService;
- private IRepository<ContactUs> _repository;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<ContactUs>();
- _mediatorMock = new Mock<IMediator>();
- _contactUsService = new ContactUsService(_repository, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task DeleteContactUsTest()
- {
- //Arrange
- var contactUs = new ContactUs {
- FullName = "test"
- };
- await _contactUsService.InsertContactUs(contactUs);
-
- //Act
- await _contactUsService.DeleteContactUs(contactUs);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.FullName == "test"));
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task ClearTableTest()
- {
- //Arrange
- await _contactUsService.InsertContactUs(new ContactUs());
- await _contactUsService.InsertContactUs(new ContactUs());
- await _contactUsService.InsertContactUs(new ContactUs());
-
- //Act
- await _contactUsService.ClearTable();
-
- //Assert
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetAllContactUsTest()
- {
- //Arrange
- await _contactUsService.InsertContactUs(new ContactUs());
- await _contactUsService.InsertContactUs(new ContactUs());
- await _contactUsService.InsertContactUs(new ContactUs());
-
- //Act
- var result = await _contactUsService.GetAllContactUs();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetContactUsByIdTest()
- {
- //Arrange
- var contactUs = new ContactUs {
- FullName = "test"
- };
- await _contactUsService.InsertContactUs(contactUs);
-
- //Act
- var result = await _contactUsService.GetContactUsById(contactUs.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.FullName);
- }
-
- [TestMethod()]
- public async Task InsertContactUsTest()
- {
- //Act
- var contactUs = new ContactUs {
- FullName = "test"
- };
- await _contactUsService.InsertContactUs(contactUs);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
+ //Act
+ var contactUs = new ContactUs {
+ FullName = "test"
+ };
+ await _contactUsService.InsertContactUs(contactUs);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseActionServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseActionServiceTests.cs
index 4083ee0ee..2c93820de 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseActionServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseActionServiceTests.cs
@@ -1,55 +1,56 @@
using Grand.Business.Marketing.Services.Courses;
-using Grand.Domain.Courses;
using Grand.Data;
+using Grand.Domain.Courses;
using Grand.Infrastructure.Events;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Courses
+namespace Grand.Business.Marketing.Tests.Services.Courses;
+
+[TestClass]
+public class CourseActionServiceTests
{
- [TestClass()]
- public class CourseActionServiceTests
+ private Mock<IRepository<CourseAction>> _courseActionRepository;
+ private CourseActionService _courseActionService;
+ private Mock<IMediator> _mediatorMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _courseActionRepository = new Mock<IRepository<CourseAction>>();
+ _mediatorMock = new Mock<IMediator>();
+ _courseActionService = new CourseActionService(_courseActionRepository.Object, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public void InsertAsync_NullArgument_ThrowExcepiton()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseActionService.InsertAsync(null),
+ "courseAction");
+ }
+
+ [TestMethod]
+ public async Task InsertAsync_NullArgument_InvokeRepository()
+ {
+ await _courseActionService.InsertAsync(new CourseAction());
+ _courseActionRepository.Verify(c => c.InsertAsync(It.IsAny<CourseAction>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CourseAction>>(), default), Times.Once);
+ }
+
+ [TestMethod]
+ public void Update_NullArgument_ThrowExcepiton()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseActionService.Update(null),
+ "courseAction");
+ }
+
+
+ [TestMethod]
+ public async Task Update_ValidArgument_InvokeRepository()
{
- private Mock<IRepository<CourseAction>> _courseActionRepository;
- private Mock<IMediator> _mediatorMock;
- private CourseActionService _courseActionService;
-
- [TestInitialize()]
- public void Init()
- {
- _courseActionRepository = new Mock<IRepository<CourseAction>>();
- _mediatorMock = new Mock<IMediator>();
- _courseActionService = new CourseActionService(_courseActionRepository.Object, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public void InsertAsync_NullArgument_ThrowExcepiton()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseActionService.InsertAsync(null), "courseAction");
- }
-
- [TestMethod()]
- public async Task InsertAsync_NullArgument_InvokeRepository()
- {
- await _courseActionService.InsertAsync(new CourseAction());
- _courseActionRepository.Verify(c => c.InsertAsync(It.IsAny<CourseAction>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<CourseAction>>(), default(CancellationToken)), Times.Once);
- }
-
- [TestMethod()]
- public void Update_NullArgument_ThrowExcepiton()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseActionService.Update(null), "courseAction");
- }
-
-
- [TestMethod()]
- public async Task Update_ValidArgument_InvokeRepository()
- {
- await _courseActionService.Update(new CourseAction());
- _courseActionRepository.Verify(c => c.UpdateAsync(It.IsAny<CourseAction>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CourseAction>>(), default(CancellationToken)), Times.Once);
- }
+ await _courseActionService.Update(new CourseAction());
+ _courseActionRepository.Verify(c => c.UpdateAsync(It.IsAny<CourseAction>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<CourseAction>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLessonServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLessonServiceTests.cs
index 6e9daf955..c42b30282 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLessonServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLessonServiceTests.cs
@@ -1,108 +1,107 @@
using Grand.Business.Marketing.Services.Courses;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Courses;
-using Grand.Data;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Courses
+namespace Grand.Business.Marketing.Tests.Services.Courses;
+
+[TestClass]
+public class CourseLessonServiceTests
{
- [TestClass()]
- public class CourseLessonServiceTests
+ private CourseLessonService _courseLessonService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CourseLesson> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<CourseLesson>();
+ _mediatorMock = new Mock<IMediator>();
+ _courseLessonService = new CourseLessonService(_repository, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task DeleteTest()
+ {
+ //Arrange
+ var courseLesson = new CourseLesson {
+ Name = "test"
+ };
+ await _courseLessonService.Insert(courseLesson);
+
+ //Act
+ await _courseLessonService.Delete(courseLesson);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetByCourseIdTest()
+ {
+ //Arrange
+ var courseLesson = new CourseLesson {
+ Name = "test",
+ CourseId = "1"
+ };
+ await _courseLessonService.Insert(courseLesson);
+
+ //Act
+ var result = await _courseLessonService.GetByCourseId(courseLesson.CourseId);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetByIdTest()
+ {
+ //Arrange
+ var courseLesson = new CourseLesson {
+ Name = "test"
+ };
+ await _courseLessonService.Insert(courseLesson);
+
+ //Act
+ var result = await _courseLessonService.GetById(courseLesson.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertTest()
+ {
+ //Act
+ var courseLesson = new CourseLesson {
+ Name = "test"
+ };
+ await _courseLessonService.Insert(courseLesson);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateTest()
{
- private CourseLessonService _courseLessonService;
- private IRepository<CourseLesson> _repository;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<CourseLesson>();
- _mediatorMock = new Mock<IMediator>();
- _courseLessonService = new CourseLessonService(_repository, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task DeleteTest()
- {
- //Arrange
- var courseLesson = new CourseLesson {
- Name = "test"
- };
- await _courseLessonService.Insert(courseLesson);
-
- //Act
- await _courseLessonService.Delete(courseLesson);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetByCourseIdTest()
- {
- //Arrange
- var courseLesson = new CourseLesson {
- Name = "test",
- CourseId = "1"
- };
- await _courseLessonService.Insert(courseLesson);
-
- //Act
- var result = await _courseLessonService.GetByCourseId(courseLesson.CourseId);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.Count);
- }
-
- [TestMethod()]
- public async Task GetByIdTest()
- {
- //Arrange
- var courseLesson = new CourseLesson {
- Name = "test"
- };
- await _courseLessonService.Insert(courseLesson);
-
- //Act
- var result = await _courseLessonService.GetById(courseLesson.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task InsertTest()
- {
- //Act
- var courseLesson = new CourseLesson {
- Name = "test"
- };
- await _courseLessonService.Insert(courseLesson);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateTest()
- {
- //Arrange
- var courseLesson = new CourseLesson {
- Name = "test"
- };
- await _courseLessonService.Insert(courseLesson);
- courseLesson.Name = "test2";
-
- //Act
- await _courseLessonService.Update(courseLesson);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
+ //Arrange
+ var courseLesson = new CourseLesson {
+ Name = "test"
+ };
+ await _courseLessonService.Insert(courseLesson);
+ courseLesson.Name = "test2";
+
+ //Act
+ await _courseLessonService.Update(courseLesson);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLevelServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLevelServiceTests.cs
index b56aef238..5ed491eef 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLevelServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseLevelServiceTests.cs
@@ -1,105 +1,104 @@
using Grand.Business.Marketing.Services.Courses;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Courses;
-using Grand.Data;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Courses
+namespace Grand.Business.Marketing.Tests.Services.Courses;
+
+[TestClass]
+public class CourseLevelServiceTests
{
- [TestClass()]
- public class CourseLevelServiceTests
+ private CourseLevelService _courseLevelService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CourseLevel> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<CourseLevel>();
+ _mediatorMock = new Mock<IMediator>();
+ _courseLevelService = new CourseLevelService(_repository, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task DeleteTest()
+ {
+ //Arrange
+ var courseLevel = new CourseLevel {
+ Name = "test"
+ };
+ await _courseLevelService.Insert(courseLevel);
+
+ //Act
+ await _courseLevelService.Delete(courseLevel);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetAllTest()
+ {
+ //Arrange
+ await _courseLevelService.Insert(new CourseLevel());
+ await _courseLevelService.Insert(new CourseLevel());
+ await _courseLevelService.Insert(new CourseLevel());
+
+ //Act
+ var result = await _courseLevelService.GetAll();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetByIdTest()
+ {
+ //Arrange
+ var courseLevel = new CourseLevel {
+ Name = "test"
+ };
+ await _courseLevelService.Insert(courseLevel);
+
+ //Act
+ var result = await _courseLevelService.GetById(courseLevel.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task InsertTest()
+ {
+ //Act
+ var courseLevel = new CourseLevel {
+ Name = "test"
+ };
+ await _courseLevelService.Insert(courseLevel);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateTest()
{
- private CourseLevelService _courseLevelService;
- private IRepository<CourseLevel> _repository;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<CourseLevel>();
- _mediatorMock = new Mock<IMediator>();
- _courseLevelService = new CourseLevelService(_repository, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task DeleteTest()
- {
- //Arrange
- var courseLevel = new CourseLevel {
- Name = "test"
- };
- await _courseLevelService.Insert(courseLevel);
-
- //Act
- await _courseLevelService.Delete(courseLevel);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetAllTest()
- {
- //Arrange
- await _courseLevelService.Insert(new CourseLevel());
- await _courseLevelService.Insert(new CourseLevel());
- await _courseLevelService.Insert(new CourseLevel());
-
- //Act
- var result = await _courseLevelService.GetAll();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetByIdTest()
- {
- //Arrange
- var courseLevel = new CourseLevel {
- Name = "test"
- };
- await _courseLevelService.Insert(courseLevel);
-
- //Act
- var result = await _courseLevelService.GetById(courseLevel.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task InsertTest()
- {
- //Act
- var courseLevel = new CourseLevel {
- Name = "test"
- };
- await _courseLevelService.Insert(courseLevel);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateTest()
- {
- //Arrange
- var courseLevel = new CourseLevel {
- Name = "test"
- };
- await _courseLevelService.Insert(courseLevel);
- courseLevel.Name = "test2";
-
- //Act
- await _courseLevelService.Update(courseLevel);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
+ //Arrange
+ var courseLevel = new CourseLevel {
+ Name = "test"
+ };
+ await _courseLevelService.Insert(courseLevel);
+ courseLevel.Name = "test2";
+
+ //Act
+ await _courseLevelService.Update(courseLevel);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseSubjectServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseSubjectServiceTests.cs
index a55f13390..3e8a137f5 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseSubjectServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CourseSubjectServiceTests.cs
@@ -1,108 +1,107 @@
using Grand.Business.Marketing.Services.Courses;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Courses;
-using Grand.Data;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Courses
+namespace Grand.Business.Marketing.Tests.Services.Courses;
+
+[TestClass]
+public class CourseSubjectServiceTests
{
- [TestClass()]
- public class CourseSubjectServiceTests
+ private CourseSubjectService _courseSubjectService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CourseSubject> _repository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repository = new MongoDBRepositoryTest<CourseSubject>();
+ _mediatorMock = new Mock<IMediator>();
+ _courseSubjectService = new CourseSubjectService(_repository, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task DeleteTest()
+ {
+ //Arrange
+ var courseSubject = new CourseSubject {
+ Name = "test"
+ };
+ await _courseSubjectService.Insert(courseSubject);
+
+ //Act
+ await _courseSubjectService.Delete(courseSubject);
+
+ //Assert
+ Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
+ Assert.AreEqual(0, _repository.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetByCourseIdTest()
{
+ //Arrange
+ var courseSubject = new CourseSubject {
+ Name = "test",
+ CourseId = "1"
+ };
+ await _courseSubjectService.Insert(courseSubject);
+
+ //Act
+ var result = await _courseSubjectService.GetByCourseId(courseSubject.CourseId);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(1, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetByIdTest()
+ {
+ //Arrange
+ var courseSubject = new CourseSubject {
+ Name = "test"
+ };
+ await _courseSubjectService.Insert(courseSubject);
+
+ //Act
+ var result = await _courseSubjectService.GetById(courseSubject.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
- private CourseSubjectService _courseSubjectService;
- private IRepository<CourseSubject> _repository;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<CourseSubject>();
- _mediatorMock = new Mock<IMediator>();
- _courseSubjectService = new CourseSubjectService(_repository, _mediatorMock.Object);
- }
- [TestMethod()]
- public async Task DeleteTest()
- {
- //Arrange
- var courseSubject = new CourseSubject {
- Name = "test"
- };
- await _courseSubjectService.Insert(courseSubject);
-
- //Act
- await _courseSubjectService.Delete(courseSubject);
-
- //Assert
- Assert.IsNull(_repository.Table.FirstOrDefault(x => x.Name == "test"));
- Assert.AreEqual(0, _repository.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetByCourseIdTest()
- {
- //Arrange
- var courseSubject = new CourseSubject {
- Name = "test",
- CourseId = "1"
- };
- await _courseSubjectService.Insert(courseSubject);
-
- //Act
- var result = await _courseSubjectService.GetByCourseId(courseSubject.CourseId);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(1, result.Count);
- }
-
- [TestMethod()]
- public async Task GetByIdTest()
- {
- //Arrange
- var courseSubject = new CourseSubject {
- Name = "test"
- };
- await _courseSubjectService.Insert(courseSubject);
-
- //Act
- var result = await _courseSubjectService.GetById(courseSubject.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task InsertTest()
- {
- //Act
- var courseSubject = new CourseSubject {
- Name = "test"
- };
- await _courseSubjectService.Insert(courseSubject);
-
- //Assert
- Assert.IsTrue(_repository.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateTest()
- {
- //Arrange
- var courseSubject = new CourseSubject {
- Name = "test"
- };
- await _courseSubjectService.Insert(courseSubject);
- courseSubject.Name = "test2";
-
- //Act
- await _courseSubjectService.Update(courseSubject);
-
- //Assert
- Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
- }
+ [TestMethod]
+ public async Task InsertTest()
+ {
+ //Act
+ var courseSubject = new CourseSubject {
+ Name = "test"
+ };
+ await _courseSubjectService.Insert(courseSubject);
+
+ //Assert
+ Assert.IsTrue(_repository.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateTest()
+ {
+ //Arrange
+ var courseSubject = new CourseSubject {
+ Name = "test"
+ };
+ await _courseSubjectService.Insert(courseSubject);
+ courseSubject.Name = "test2";
+
+ //Act
+ await _courseSubjectService.Update(courseSubject);
+
+ //Assert
+ Assert.IsNotNull(_repository.Table.FirstOrDefault(x => x.Name == "test2"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CoursesServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CoursesServiceTests.cs
index e2312b113..6cdfff14f 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CoursesServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Courses/CoursesServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Marketing.Services.Courses;
+using Grand.Data;
using Grand.Domain.Catalog;
using Grand.Domain.Courses;
-using Grand.Data;
using Grand.Domain.Orders;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Events;
@@ -9,76 +9,75 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Courses
-{
- [TestClass()]
- public class CoursesServiceTests
- {
- private Mock<IRepository<Course>> _courseRepositoryMock;
- private Mock<IRepository<Order>> _orderRepositoryMock;
- private Mock<IMediator> _mediatorMock;
- private CatalogSettings _settings;
- private CourseService _courseService;
+namespace Grand.Business.Marketing.Tests.Services.Courses;
- [TestInitialize()]
- public void Init()
- {
- _courseRepositoryMock = new Mock<IRepository<Course>>();
- _orderRepositoryMock = new Mock<IRepository<Order>>();
- _mediatorMock = new Mock<IMediator>();
- _settings = new CatalogSettings();
- var accessControlConfig = new AccessControlConfig();
- _courseService = new CourseService(_courseRepositoryMock.Object, _orderRepositoryMock.Object, _mediatorMock.Object, accessControlConfig);
+[TestClass]
+public class CoursesServiceTests
+{
+ private Mock<IRepository<Course>> _courseRepositoryMock;
+ private CourseService _courseService;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Order>> _orderRepositoryMock;
+ private CatalogSettings _settings;
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _courseRepositoryMock = new Mock<IRepository<Course>>();
+ _orderRepositoryMock = new Mock<IRepository<Order>>();
+ _mediatorMock = new Mock<IMediator>();
+ _settings = new CatalogSettings();
+ var accessControlConfig = new AccessControlConfig();
+ _courseService = new CourseService(_courseRepositoryMock.Object, _orderRepositoryMock.Object,
+ _mediatorMock.Object, accessControlConfig);
+ }
- [TestMethod()]
- public void Delete_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseService.Delete(null), "course");
- }
+ [TestMethod]
+ public void Delete_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseService.Delete(null), "course");
+ }
- [TestMethod()]
- public async Task Delete_ValidArgument_InvokeRepository()
- {
- await _courseService.Delete(new Course());
- _courseRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Course>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Course>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task Delete_ValidArgument_InvokeRepository()
+ {
+ await _courseService.Delete(new Course());
+ _courseRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Course>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Course>>(), default), Times.Once);
+ }
- [TestMethod()]
- public void Insert_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseService.Insert(null), "course");
- }
+ [TestMethod]
+ public void Insert_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseService.Insert(null), "course");
+ }
- [TestMethod()]
- public async Task Insert_ValidArgument_InvokeRepository()
- {
- await _courseService.Insert(new Course());
- _courseRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Course>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Course>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task Insert_ValidArgument_InvokeRepository()
+ {
+ await _courseService.Insert(new Course());
+ _courseRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Course>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Course>>(), default), Times.Once);
+ }
- [TestMethod()]
- public void Update_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseService.Update(null), "course");
- }
+ [TestMethod]
+ public void Update_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _courseService.Update(null), "course");
+ }
- [TestMethod()]
- public async Task Update_ValidArgument_InvokeRepository()
- {
- await _courseService.Update(new Course());
- _courseRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Course>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Course>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task Update_ValidArgument_InvokeRepository()
+ {
+ await _courseService.Update(new Course());
+ _courseRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Course>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Course>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task GetById_ValidArgument_InvokeRepository()
- {
- await _courseService.GetById("id");
- _courseRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GetById_ValidArgument_InvokeRepository()
+ {
+ await _courseService.GetById("id");
+ _courseRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs
index 54eaae886..fff2b518e 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerCoordinatesServiceTests.cs
@@ -1,85 +1,87 @@
using Grand.Business.Core.Events.Marketing;
using Grand.Business.Marketing.Services.Customers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
+using Grand.Domain.Stores;
using Grand.Infrastructure;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Customers
+namespace Grand.Business.Marketing.Tests.Services.Customers;
+
+[TestClass]
+public class CustomerCoordinatesServiceTests
{
- [TestClass()]
- public class CustomerCoordinatesServiceTests
+ private Customer _customer;
+ private CustomerCoordinatesService _customerCoordinatesService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Customer> _repository;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
{
- CustomerCoordinatesService _customerCoordinatesService;
- private Mock<IWorkContext> _workContextMock;
- private IRepository<Customer> _repository;
- private Mock<IMediator> _mediatorMock;
- private Customer _customer;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Customer>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Domain.Stores.Store { Id = "" });
- _customer = new Customer();
- _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => _customer);
+ _repository = new MongoDBRepositoryTest<Customer>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
+ _workContextMock.Setup(c => c.CurrentStore).Returns(() => new Store { Id = "" });
+ _customer = new Customer();
+ _workContextMock.Setup(c => c.CurrentCustomer).Returns(() => _customer);
- _customerCoordinatesService = new CustomerCoordinatesService(_repository, _workContextMock.Object, _mediatorMock.Object);
- }
+ _customerCoordinatesService =
+ new CustomerCoordinatesService(_repository, _workContextMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task GetGeoCoordinateTest_WorkContext()
- {
- //Arrange
- await _customerCoordinatesService.SaveGeoCoordinate(1, 2);
- //Act
- var result = await _customerCoordinatesService.GetGeoCoordinate();
- //Assert
- Assert.AreEqual(1, result.longitude);
- Assert.AreEqual(2, result.latitude);
- }
+ [TestMethod]
+ public async Task GetGeoCoordinateTest_WorkContext()
+ {
+ //Arrange
+ await _customerCoordinatesService.SaveGeoCoordinate(1, 2);
+ //Act
+ var result = await _customerCoordinatesService.GetGeoCoordinate();
+ //Assert
+ Assert.AreEqual(1, result.longitude);
+ Assert.AreEqual(2, result.latitude);
+ }
- [TestMethod()]
- public async Task GetGeoCoordinateTest_Customer()
- {
- //Arrange
- var customer = new Customer();
- await _repository.InsertAsync(customer);
- await _customerCoordinatesService.SaveGeoCoordinate(customer, 1, 2);
- //Act
- var result = await _customerCoordinatesService.GetGeoCoordinate(customer);
- //Assert
- Assert.AreEqual(1, result.longitude);
- Assert.AreEqual(2, result.latitude);
- }
+ [TestMethod]
+ public async Task GetGeoCoordinateTest_Customer()
+ {
+ //Arrange
+ var customer = new Customer();
+ await _repository.InsertAsync(customer);
+ await _customerCoordinatesService.SaveGeoCoordinate(customer, 1, 2);
+ //Act
+ var result = await _customerCoordinatesService.GetGeoCoordinate(customer);
+ //Assert
+ Assert.AreEqual(1, result.longitude);
+ Assert.AreEqual(2, result.latitude);
+ }
- [TestMethod()]
- public async Task SaveGeoCoordinateTest_Customer()
- {
- //Arrange
- var customer = new Customer();
- await _repository.InsertAsync(customer);
- //Act
- await _customerCoordinatesService.SaveGeoCoordinate(customer, 1, 2);
- //Assert
- Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Coordinates.X);
- Assert.AreEqual(2, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Coordinates.Y);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<CustomerCoordinatesEvent>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task SaveGeoCoordinateTest_Customer()
+ {
+ //Arrange
+ var customer = new Customer();
+ await _repository.InsertAsync(customer);
+ //Act
+ await _customerCoordinatesService.SaveGeoCoordinate(customer, 1, 2);
+ //Assert
+ Assert.AreEqual(1, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Coordinates.X);
+ Assert.AreEqual(2, _repository.Table.FirstOrDefault(x => x.Id == customer.Id).Coordinates.Y);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<CustomerCoordinatesEvent>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task SaveGeoCoordinateTest_WorkContext()
- {
- //Act
- await _customerCoordinatesService.SaveGeoCoordinate(1, 2);
- //Assert
- Assert.AreEqual(1, _workContextMock.Object.CurrentCustomer.Coordinates.X);
- Assert.AreEqual(2, _workContextMock.Object.CurrentCustomer.Coordinates.Y);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<CustomerCoordinatesEvent>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task SaveGeoCoordinateTest_WorkContext()
+ {
+ //Act
+ await _customerCoordinatesService.SaveGeoCoordinate(1, 2);
+ //Assert
+ Assert.AreEqual(1, _workContextMock.Object.CurrentCustomer.Coordinates.X);
+ Assert.AreEqual(2, _workContextMock.Object.CurrentCustomer.Coordinates.Y);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<CustomerCoordinatesEvent>(), default), Times.Once);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerProductServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerProductServiceTests.cs
index 4c1c6e437..eea27298e 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerProductServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerProductServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Marketing.Services.Customers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,210 +9,211 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Customers
+namespace Grand.Business.Marketing.Tests.Services.Customers;
+
+[TestClass]
+public class CustomerProductServiceTests
{
- [TestClass()]
- public class CustomerProductServiceTests
+ private MemoryCacheBase _cacheBase;
+ private CustomerProductService _customerProductService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<CustomerProduct> _repositoryCustomerProduct;
+ private IRepository<CustomerProductPrice> _repositoryCustomerProductPrice;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryCustomerProductPrice = new MongoDBRepositoryTest<CustomerProductPrice>();
+ _repositoryCustomerProduct = new MongoDBRepositoryTest<CustomerProduct>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _customerProductService = new CustomerProductService(_repositoryCustomerProductPrice,
+ _repositoryCustomerProduct, _cacheBase, _mediatorMock.Object);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerProductPriceByIdTest()
+ {
+ //Arrange
+ var customerProductPrice = new CustomerProductPrice { Price = 10 };
+
+ await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
+
+ //Act
+ var result = await _customerProductService.GetCustomerProductPriceById(customerProductPrice.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(10, result.Price);
+ }
+
+ [TestMethod]
+ public async Task GetPriceByCustomerProductTest()
+ {
+ //Arrange
+ var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
+
+ await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
+
+ //Act
+ var result = await _customerProductService.GetPriceByCustomerProduct("1", "1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(10, result);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerProductPriceTest()
{
- private CustomerProductService _customerProductService;
- private IRepository<CustomerProductPrice> _repositoryCustomerProductPrice;
- private IRepository<CustomerProduct> _repositoryCustomerProduct;
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repositoryCustomerProductPrice = new MongoDBRepositoryTest<CustomerProductPrice>();
- _repositoryCustomerProduct = new MongoDBRepositoryTest<CustomerProduct>();
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _customerProductService = new CustomerProductService(_repositoryCustomerProductPrice, _repositoryCustomerProduct, _cacheBase, _mediatorMock.Object);
- }
-
- [TestMethod()]
- public async Task GetCustomerProductPriceByIdTest()
- {
- //Arrange
- var customerProductPrice = new CustomerProductPrice { Price = 10 };
-
- await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
-
- //Act
- var result = await _customerProductService.GetCustomerProductPriceById(customerProductPrice.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(10, result.Price);
- }
-
- [TestMethod()]
- public async Task GetPriceByCustomerProductTest()
- {
- //Arrange
- var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
-
- await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
-
- //Act
- var result = await _customerProductService.GetPriceByCustomerProduct("1", "1");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(10, result);
- }
-
- [TestMethod()]
- public async Task InsertCustomerProductPriceTest()
- {
- //Act
- var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
- await _customerProductService.InsertCustomerProductPrice(customerProductPrice);
-
- //Assert
- Assert.IsTrue(_repositoryCustomerProductPrice.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCustomerProductPriceTest()
- {
- //Arrange
- var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
-
- await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
-
- //Act
- customerProductPrice.Price = 20;
- await _customerProductService.UpdateCustomerProductPrice(customerProductPrice);
- var result = await _customerProductService.GetCustomerProductPriceById(customerProductPrice.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(20, result.Price);
- }
-
- [TestMethod()]
- public async Task DeleteCustomerProductPriceTest()
- {
- //Arrange
- var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
-
- await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
-
- //Act
- await _customerProductService.DeleteCustomerProductPrice(customerProductPrice);
- var result = await _customerProductService.GetCustomerProductPriceById(customerProductPrice.Id);
-
- //Assert
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task GetProductsPriceByCustomerTest()
- {
- //Arrange
- await _repositoryCustomerProductPrice.InsertAsync(new CustomerProductPrice { CustomerId = "1" });
- await _repositoryCustomerProductPrice.InsertAsync(new CustomerProductPrice { CustomerId = "1" });
- await _repositoryCustomerProductPrice.InsertAsync(new CustomerProductPrice { CustomerId = "1" });
-
- //Act
- var result = await _customerProductService.GetProductsPriceByCustomer("1");
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetCustomerProductTest()
- {
- //Arrange
- var customerProduct = new CustomerProduct { CustomerId = "1" };
-
- await _repositoryCustomerProduct.InsertAsync(customerProduct);
-
- //Act
- var result = await _customerProductService.GetCustomerProduct(customerProduct.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.CustomerId);
- }
-
- [TestMethod()]
- public async Task GetCustomerProductTest_Customer_Product()
- {
- //Arrange
- var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1" };
-
- await _repositoryCustomerProduct.InsertAsync(customerProduct);
-
- //Act
- var result = await _customerProductService.GetCustomerProduct("1", "1");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.CustomerId);
- }
-
- [TestMethod()]
- public async Task InsertCustomerProductTest()
- {
- //Act
- var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1" };
- await _customerProductService.InsertCustomerProduct(customerProduct);
-
- //Assert
- Assert.IsTrue(_repositoryCustomerProduct.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCustomerProductTest()
- {
- //Arrange
- var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1", DisplayOrder = 1 };
-
- await _repositoryCustomerProduct.InsertAsync(customerProduct);
-
- //Act
- customerProduct.DisplayOrder = 20;
- await _customerProductService.UpdateCustomerProduct(customerProduct);
- var result = await _customerProductService.GetCustomerProduct(customerProduct.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(20, result.DisplayOrder);
- }
-
- [TestMethod()]
- public async Task DeleteCustomerProductTest()
- {
- //Arrange
- var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1" };
-
- await _repositoryCustomerProduct.InsertAsync(customerProduct);
-
- //Act
- await _customerProductService.DeleteCustomerProduct(customerProduct);
- var result = await _customerProductService.GetCustomerProduct(customerProduct.Id);
-
- //Assert
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task GetProductsByCustomerTest()
- {
- //Arrange
- await _repositoryCustomerProduct.InsertAsync(new CustomerProduct { CustomerId = "1" });
- await _repositoryCustomerProduct.InsertAsync(new CustomerProduct { CustomerId = "1" });
- await _repositoryCustomerProduct.InsertAsync(new CustomerProduct { CustomerId = "1" });
-
- //Act
- var result = await _customerProductService.GetProductsByCustomer("1");
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
+ //Act
+ var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
+ await _customerProductService.InsertCustomerProductPrice(customerProductPrice);
+
+ //Assert
+ Assert.IsTrue(_repositoryCustomerProductPrice.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerProductPriceTest()
+ {
+ //Arrange
+ var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
+
+ await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
+
+ //Act
+ customerProductPrice.Price = 20;
+ await _customerProductService.UpdateCustomerProductPrice(customerProductPrice);
+ var result = await _customerProductService.GetCustomerProductPriceById(customerProductPrice.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(20, result.Price);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerProductPriceTest()
+ {
+ //Arrange
+ var customerProductPrice = new CustomerProductPrice { Price = 10, CustomerId = "1", ProductId = "1" };
+
+ await _repositoryCustomerProductPrice.InsertAsync(customerProductPrice);
+
+ //Act
+ await _customerProductService.DeleteCustomerProductPrice(customerProductPrice);
+ var result = await _customerProductService.GetCustomerProductPriceById(customerProductPrice.Id);
+
+ //Assert
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetProductsPriceByCustomerTest()
+ {
+ //Arrange
+ await _repositoryCustomerProductPrice.InsertAsync(new CustomerProductPrice { CustomerId = "1" });
+ await _repositoryCustomerProductPrice.InsertAsync(new CustomerProductPrice { CustomerId = "1" });
+ await _repositoryCustomerProductPrice.InsertAsync(new CustomerProductPrice { CustomerId = "1" });
+
+ //Act
+ var result = await _customerProductService.GetProductsPriceByCustomer("1");
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerProductTest()
+ {
+ //Arrange
+ var customerProduct = new CustomerProduct { CustomerId = "1" };
+
+ await _repositoryCustomerProduct.InsertAsync(customerProduct);
+
+ //Act
+ var result = await _customerProductService.GetCustomerProduct(customerProduct.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.CustomerId);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerProductTest_Customer_Product()
+ {
+ //Arrange
+ var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1" };
+
+ await _repositoryCustomerProduct.InsertAsync(customerProduct);
+
+ //Act
+ var result = await _customerProductService.GetCustomerProduct("1", "1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.CustomerId);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerProductTest()
+ {
+ //Act
+ var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1" };
+ await _customerProductService.InsertCustomerProduct(customerProduct);
+
+ //Assert
+ Assert.IsTrue(_repositoryCustomerProduct.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerProductTest()
+ {
+ //Arrange
+ var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1", DisplayOrder = 1 };
+
+ await _repositoryCustomerProduct.InsertAsync(customerProduct);
+
+ //Act
+ customerProduct.DisplayOrder = 20;
+ await _customerProductService.UpdateCustomerProduct(customerProduct);
+ var result = await _customerProductService.GetCustomerProduct(customerProduct.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(20, result.DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerProductTest()
+ {
+ //Arrange
+ var customerProduct = new CustomerProduct { CustomerId = "1", ProductId = "1" };
+
+ await _repositoryCustomerProduct.InsertAsync(customerProduct);
+
+ //Act
+ await _customerProductService.DeleteCustomerProduct(customerProduct);
+ var result = await _customerProductService.GetCustomerProduct(customerProduct.Id);
+
+ //Assert
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetProductsByCustomerTest()
+ {
+ //Arrange
+ await _repositoryCustomerProduct.InsertAsync(new CustomerProduct { CustomerId = "1" });
+ await _repositoryCustomerProduct.InsertAsync(new CustomerProduct { CustomerId = "1" });
+ await _repositoryCustomerProduct.InsertAsync(new CustomerProduct { CustomerId = "1" });
+
+ //Act
+ var result = await _customerProductService.GetProductsByCustomer("1");
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerTagServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerTagServiceTests.cs
index d46624c55..fbba03e88 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerTagServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Customers/CustomerTagServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Marketing.Services.Customers;
+using Grand.Data;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Tests.Caching;
@@ -9,316 +9,321 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Customers
+namespace Grand.Business.Marketing.Tests.Services.Customers;
+
+[TestClass]
+public class CustomerTagServiceTests
{
- [TestClass()]
- public class CustomerTagServiceTests
+ private MemoryCacheBase _cacheBase;
+ private CustomerTagService _customerTagService;
+ private Mock<IMediator> _mediatorMock;
+ private IRepository<Customer> _repositoryCustomer;
+ private IRepository<CustomerTag> _repositoryCustomerTag;
+ private IRepository<CustomerTagProduct> _repositoryCustomerTagProduct;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryCustomerTag = new MongoDBRepositoryTest<CustomerTag>();
+ _repositoryCustomerTagProduct = new MongoDBRepositoryTest<CustomerTagProduct>();
+ _repositoryCustomer = new MongoDBRepositoryTest<Customer>();
+ _mediatorMock = new Mock<IMediator>();
+
+ _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object,
+ new CacheConfig { DefaultCacheTimeMinutes = 1 });
+ _customerTagService = new CustomerTagService(_repositoryCustomerTag, _repositoryCustomerTagProduct,
+ _repositoryCustomer, _mediatorMock.Object, _cacheBase);
+ }
+
+ [TestMethod]
+ public async Task GetCustomersByTagTest()
+ {
+ //Arrange
+ var customer1 = new Customer();
+ customer1.CustomerTags.Add("1");
+ await _repositoryCustomer.InsertAsync(customer1);
+ var customer2 = new Customer();
+ customer2.CustomerTags.Add("2");
+ await _repositoryCustomer.InsertAsync(customer2);
+ var customer3 = new Customer();
+ customer3.CustomerTags.Add("1");
+ await _repositoryCustomer.InsertAsync(customer3);
+
+ //Act
+ var result = await _customerTagService.GetCustomersByTag("1");
+
+ //Assert
+ Assert.IsTrue(result.Any());
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerTagTest()
+ {
+ //Arrange
+ var customer1 = new Customer();
+ customer1.CustomerTags.Add("1");
+ await _repositoryCustomer.InsertAsync(customer1);
+ var customer2 = new Customer();
+ customer2.CustomerTags.Add("2");
+ await _repositoryCustomer.InsertAsync(customer2);
+ var customer3 = new Customer();
+ customer3.CustomerTags.Add("1");
+ await _repositoryCustomer.InsertAsync(customer3);
+
+ var customerTag = new CustomerTag { Id = "1" };
+ await _repositoryCustomerTag.InsertAsync(customerTag);
+
+ //Act
+ await _customerTagService.DeleteCustomerTag(customerTag);
+ var result = await _customerTagService.GetCustomersByTag("1");
+
+ //Assert
+ Assert.IsFalse(result.Any());
+ Assert.AreEqual(0, result.Count);
+ Assert.AreEqual(0, _repositoryCustomerTag.Table.Count());
+ }
+
+ [TestMethod]
+ public async Task GetAllCustomerTagsTest()
+ {
+ //Assert
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+
+ //Act
+ var result = await _customerTagService.GetAllCustomerTags();
+
+ //Assert
+ Assert.IsTrue(result.Any());
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerTagByIdTest()
+ {
+ //Assert
+ var customerTag = new CustomerTag { Id = "1", Name = "test" };
+ await _repositoryCustomerTag.InsertAsync(customerTag);
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+
+ //Act
+ var result = await _customerTagService.GetCustomerTagById(customerTag.Id);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerTagByNameTest()
+ {
+ //Assert
+ var customerTag = new CustomerTag { Id = "1", Name = "test" };
+ await _repositoryCustomerTag.InsertAsync(customerTag);
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+
+ //Act
+ var result = await _customerTagService.GetCustomerTagByName("test");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("test", result.Name);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerTagsByNameTest()
+ {
+ //Assert
+ var customerTag = new CustomerTag { Id = "1", Name = "test" };
+ await _repositoryCustomerTag.InsertAsync(customerTag);
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag { Name = "test" });
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+ await _repositoryCustomerTag.InsertAsync(new CustomerTag());
+
+ //Act
+ var result = await _customerTagService.GetCustomerTagsByName("test");
+
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerTagTest()
{
- private CustomerTagService _customerTagService;
- private IRepository<CustomerTag> _repositoryCustomerTag;
- private IRepository<CustomerTagProduct> _repositoryCustomerTagProduct;
- private IRepository<Customer> _repositoryCustomer;
-
- private MemoryCacheBase _cacheBase;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize()]
- public void Init()
- {
- _repositoryCustomerTag = new MongoDBRepositoryTest<CustomerTag>();
- _repositoryCustomerTagProduct = new MongoDBRepositoryTest<CustomerTagProduct>();
- _repositoryCustomer = new MongoDBRepositoryTest<Customer>();
- _mediatorMock = new Mock<IMediator>();
-
- _cacheBase = new MemoryCacheBase(MemoryCacheTest.Get(), _mediatorMock.Object, new CacheConfig { DefaultCacheTimeMinutes = 1});
- _customerTagService = new CustomerTagService(_repositoryCustomerTag, _repositoryCustomerTagProduct, _repositoryCustomer, _mediatorMock.Object, _cacheBase);
- }
-
- [TestMethod()]
- public async Task GetCustomersByTagTest()
- {
- //Arrange
- var customer1 = new Customer();
- customer1.CustomerTags.Add("1");
- await _repositoryCustomer.InsertAsync(customer1);
- var customer2 = new Customer();
- customer2.CustomerTags.Add("2");
- await _repositoryCustomer.InsertAsync(customer2);
- var customer3 = new Customer();
- customer3.CustomerTags.Add("1");
- await _repositoryCustomer.InsertAsync(customer3);
-
- //Act
- var result = await _customerTagService.GetCustomersByTag("1");
-
- //Assert
- Assert.IsTrue(result.Any());
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task DeleteCustomerTagTest()
- {
- //Arrange
- var customer1 = new Customer();
- customer1.CustomerTags.Add("1");
- await _repositoryCustomer.InsertAsync(customer1);
- var customer2 = new Customer();
- customer2.CustomerTags.Add("2");
- await _repositoryCustomer.InsertAsync(customer2);
- var customer3 = new Customer();
- customer3.CustomerTags.Add("1");
- await _repositoryCustomer.InsertAsync(customer3);
-
- var customerTag = new CustomerTag { Id = "1" };
- await _repositoryCustomerTag.InsertAsync(customerTag);
-
- //Act
- await _customerTagService.DeleteCustomerTag(customerTag);
- var result = await _customerTagService.GetCustomersByTag("1");
-
- //Assert
- Assert.IsFalse(result.Any());
- Assert.AreEqual(0, result.Count);
- Assert.AreEqual(0, _repositoryCustomerTag.Table.Count());
- }
-
- [TestMethod()]
- public async Task GetAllCustomerTagsTest()
- {
- //Assert
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
-
- //Act
- var result = await _customerTagService.GetAllCustomerTags();
-
- //Assert
- Assert.IsTrue(result.Any());
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetCustomerTagByIdTest()
- {
- //Assert
- var customerTag = new CustomerTag { Id = "1", Name = "test" };
- await _repositoryCustomerTag.InsertAsync(customerTag);
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
-
- //Act
- var result = await _customerTagService.GetCustomerTagById(customerTag.Id);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task GetCustomerTagByNameTest()
- {
- //Assert
- var customerTag = new CustomerTag { Id = "1", Name = "test" };
- await _repositoryCustomerTag.InsertAsync(customerTag);
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
-
- //Act
- var result = await _customerTagService.GetCustomerTagByName("test");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("test", result.Name);
- }
-
- [TestMethod()]
- public async Task GetCustomerTagsByNameTest()
- {
- //Assert
- var customerTag = new CustomerTag { Id = "1", Name = "test" };
- await _repositoryCustomerTag.InsertAsync(customerTag);
- await _repositoryCustomerTag.InsertAsync(new CustomerTag { Name = "test" });
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
- await _repositoryCustomerTag.InsertAsync(new CustomerTag());
-
- //Act
- var result = await _customerTagService.GetCustomerTagsByName("test");
-
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task InsertCustomerTagTest()
- {
- //Assert
- var customerTag = new CustomerTag { Id = "1", Name = "test" };
-
- //Act
- await _customerTagService.InsertCustomerTag(customerTag);
-
- //Assert
- Assert.IsTrue(_repositoryCustomerTag.Table.Any());
- }
-
- [TestMethod()]
- public async Task InsertTagToCustomerTest()
- {
- //Arrange
- var customer = new Customer {Id = "1" };
- await _repositoryCustomer.InsertAsync(customer);
-
- var customerTag = new CustomerTag { Id = "1" };
- await _repositoryCustomerTag.InsertAsync(customerTag);
-
- //Act
- await _customerTagService.InsertTagToCustomer(customerTag.Id, customer.Id);
-
- //Assert
- Assert.IsTrue(_repositoryCustomer.Table.FirstOrDefault(x=>x.Id == customer.Id).CustomerTags.Contains(customerTag.Id));
- }
-
- [TestMethod()]
- public async Task DeleteTagFromCustomerTest()
- {
- //Arrange
- var customer = new Customer { Id = "1" };
- customer.CustomerTags.Add("1");
- await _repositoryCustomer.InsertAsync(customer);
-
- var customerTag = new CustomerTag { Id = "1" };
- await _repositoryCustomerTag.InsertAsync(customerTag);
-
- //Act
- await _customerTagService.DeleteTagFromCustomer(customerTag.Id, customer.Id);
-
- //Assert
- Assert.IsFalse(_repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).CustomerTags.Contains(customerTag.Id));
- }
-
- [TestMethod()]
- public async Task UpdateCustomerTagTest()
- {
- //Assert
- var customerTag = new CustomerTag { Id = "1", Name = "test" };
- await _customerTagService.InsertCustomerTag(customerTag);
-
- //Act
- customerTag.Name = "test2";
- await _customerTagService.UpdateCustomerTag(customerTag);
-
- //Assert
- Assert.IsTrue(_repositoryCustomerTag.Table.FirstOrDefault(x=>x.Id == customerTag.Id).Name == "test2");
- }
-
- [TestMethod()]
- public async Task GetCustomerCountTest()
- {
- //Arrange
- var customer1 = new Customer();
- customer1.CustomerTags.Add("1");
- await _repositoryCustomer.InsertAsync(customer1);
- var customer2 = new Customer();
- customer2.CustomerTags.Add("2");
- await _repositoryCustomer.InsertAsync(customer2);
- var customer3 = new Customer();
- customer3.CustomerTags.Add("1");
- await _repositoryCustomer.InsertAsync(customer3);
-
- //Act
- var result = await _customerTagService.GetCustomerCount("1");
-
- //Assert
- Assert.AreEqual(2, result);
- }
-
- [TestMethod()]
- public async Task GetCustomerTagProductsTest()
- {
- //Assert
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1" });
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1" });
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "2" });
-
- //Act
- var result = await _customerTagService.GetCustomerTagProducts("1");
-
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task GetCustomerTagProductTest()
- {
- //Assert
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1", ProductId = "1" });
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1" });
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "2" });
-
- //Act
- var result = await _customerTagService.GetCustomerTagProduct("1", "1");
-
- //Assert
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task GetCustomerTagProductByIdTest()
- {
- //Assert
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1", ProductId = "1" });
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { Id = "1", CustomerTagId = "1" });
- await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "2" });
-
- //Act
- var result = await _customerTagService.GetCustomerTagProductById("1");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.CustomerTagId);
- }
-
- [TestMethod()]
- public async Task InsertCustomerTagProductTest()
- {
- //Act
- await _customerTagService.InsertCustomerTagProduct(new CustomerTagProduct());
-
- //Assert
- Assert.IsTrue(_repositoryCustomerTagProduct.Table.Any());
- }
-
- [TestMethod()]
- public async Task UpdateCustomerTagProductTest()
- {
- //Assert
- var customerTagProduct = new CustomerTagProduct();
- await _repositoryCustomerTagProduct.InsertAsync(customerTagProduct);
-
- //Act
- customerTagProduct.DisplayOrder = 10;
- await _customerTagService.UpdateCustomerTagProduct(customerTagProduct);
-
- //Assert
- Assert.IsTrue(_repositoryCustomerTagProduct.Table.FirstOrDefault(x=>x.Id == customerTagProduct.Id).DisplayOrder == 10);
- }
-
- [TestMethod()]
- public async Task DeleteCustomerTagProductTest()
- {
- //Assert
- var customerTagProduct = new CustomerTagProduct();
- await _repositoryCustomerTagProduct.InsertAsync(customerTagProduct);
-
- //Act
- await _customerTagService.DeleteCustomerTagProduct(customerTagProduct);
-
- //Assert
- Assert.IsFalse(_repositoryCustomerTag.Table.Any());
- }
+ //Assert
+ var customerTag = new CustomerTag { Id = "1", Name = "test" };
+
+ //Act
+ await _customerTagService.InsertCustomerTag(customerTag);
+
+ //Assert
+ Assert.IsTrue(_repositoryCustomerTag.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task InsertTagToCustomerTest()
+ {
+ //Arrange
+ var customer = new Customer { Id = "1" };
+ await _repositoryCustomer.InsertAsync(customer);
+
+ var customerTag = new CustomerTag { Id = "1" };
+ await _repositoryCustomerTag.InsertAsync(customerTag);
+
+ //Act
+ await _customerTagService.InsertTagToCustomer(customerTag.Id, customer.Id);
+
+ //Assert
+ Assert.IsTrue(_repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).CustomerTags
+ .Contains(customerTag.Id));
+ }
+
+ [TestMethod]
+ public async Task DeleteTagFromCustomerTest()
+ {
+ //Arrange
+ var customer = new Customer { Id = "1" };
+ customer.CustomerTags.Add("1");
+ await _repositoryCustomer.InsertAsync(customer);
+
+ var customerTag = new CustomerTag { Id = "1" };
+ await _repositoryCustomerTag.InsertAsync(customerTag);
+
+ //Act
+ await _customerTagService.DeleteTagFromCustomer(customerTag.Id, customer.Id);
+
+ //Assert
+ Assert.IsFalse(_repositoryCustomer.Table.FirstOrDefault(x => x.Id == customer.Id).CustomerTags
+ .Contains(customerTag.Id));
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerTagTest()
+ {
+ //Assert
+ var customerTag = new CustomerTag { Id = "1", Name = "test" };
+ await _customerTagService.InsertCustomerTag(customerTag);
+
+ //Act
+ customerTag.Name = "test2";
+ await _customerTagService.UpdateCustomerTag(customerTag);
+
+ //Assert
+ Assert.IsTrue(_repositoryCustomerTag.Table.FirstOrDefault(x => x.Id == customerTag.Id).Name == "test2");
+ }
+
+ [TestMethod]
+ public async Task GetCustomerCountTest()
+ {
+ //Arrange
+ var customer1 = new Customer();
+ customer1.CustomerTags.Add("1");
+ await _repositoryCustomer.InsertAsync(customer1);
+ var customer2 = new Customer();
+ customer2.CustomerTags.Add("2");
+ await _repositoryCustomer.InsertAsync(customer2);
+ var customer3 = new Customer();
+ customer3.CustomerTags.Add("1");
+ await _repositoryCustomer.InsertAsync(customer3);
+
+ //Act
+ var result = await _customerTagService.GetCustomerCount("1");
+
+ //Assert
+ Assert.AreEqual(2, result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerTagProductsTest()
+ {
+ //Assert
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1" });
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1" });
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "2" });
+
+ //Act
+ var result = await _customerTagService.GetCustomerTagProducts("1");
+
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerTagProductTest()
+ {
+ //Assert
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct
+ { CustomerTagId = "1", ProductId = "1" });
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "1" });
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "2" });
+
+ //Act
+ var result = await _customerTagService.GetCustomerTagProduct("1", "1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task GetCustomerTagProductByIdTest()
+ {
+ //Assert
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct
+ { CustomerTagId = "1", ProductId = "1" });
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { Id = "1", CustomerTagId = "1" });
+ await _repositoryCustomerTagProduct.InsertAsync(new CustomerTagProduct { CustomerTagId = "2" });
+
+ //Act
+ var result = await _customerTagService.GetCustomerTagProductById("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.CustomerTagId);
+ }
+
+ [TestMethod]
+ public async Task InsertCustomerTagProductTest()
+ {
+ //Act
+ await _customerTagService.InsertCustomerTagProduct(new CustomerTagProduct());
+
+ //Assert
+ Assert.IsTrue(_repositoryCustomerTagProduct.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task UpdateCustomerTagProductTest()
+ {
+ //Assert
+ var customerTagProduct = new CustomerTagProduct();
+ await _repositoryCustomerTagProduct.InsertAsync(customerTagProduct);
+
+ //Act
+ customerTagProduct.DisplayOrder = 10;
+ await _customerTagService.UpdateCustomerTagProduct(customerTagProduct);
+
+ //Assert
+ Assert.IsTrue(_repositoryCustomerTagProduct.Table.FirstOrDefault(x => x.Id == customerTagProduct.Id)
+ .DisplayOrder == 10);
+ }
+
+ [TestMethod]
+ public async Task DeleteCustomerTagProductTest()
+ {
+ //Assert
+ var customerTagProduct = new CustomerTagProduct();
+ await _repositoryCustomerTagProduct.InsertAsync(customerTagProduct);
+
+ //Act
+ await _customerTagService.DeleteCustomerTagProduct(customerTagProduct);
+
+ //Assert
+ Assert.IsFalse(_repositoryCustomerTag.Table.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentServiceTests.cs
index e7ed261b8..509448a20 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentServiceTests.cs
@@ -6,70 +6,71 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Documents
+namespace Grand.Business.Marketing.Tests.Services.Documents;
+
+[TestClass]
+public class DocumentServiceTests
{
- [TestClass()]
- public class DocumentServiceTests
- {
- private Mock<IRepository<Document>> _documentRepositoryMock;
- private DocumentService _documentService;
- private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Document>> _documentRepositoryMock;
+ private DocumentService _documentService;
+ private Mock<IMediator> _mediatorMock;
- [TestInitialize()]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _documentRepositoryMock = new Mock<IRepository<Document>>();
- _documentService = new DocumentService(_documentRepositoryMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _documentRepositoryMock = new Mock<IRepository<Document>>();
+ _documentService = new DocumentService(_documentRepositoryMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task DeleteDocument_NullArgument_ThrowException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentService.Delete(null), "document");
- }
+ [TestMethod]
+ public async Task DeleteDocument_NullArgument_ThrowException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentService.Delete(null),
+ "document");
+ }
- [TestMethod()]
- public async Task DeleteDocument_ValidArgument()
- {
- await _documentService.Delete(new Document());
- _documentRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Document>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Document>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteDocument_ValidArgument()
+ {
+ await _documentService.Delete(new Document());
+ _documentRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Document>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Document>>(), default), Times.Once);
+ }
- [TestMethod]
- public async Task GetDocumentById()
- {
- await _documentService.GetById("id");
- _documentRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GetDocumentById()
+ {
+ await _documentService.GetById("id");
+ _documentRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertDocument_NullArgument_ThrowException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentService.Insert(null), "document");
- }
+ [TestMethod]
+ public async Task InsertDocument_NullArgument_ThrowException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentService.Insert(null),
+ "document");
+ }
- [TestMethod()]
- public async Task InsertDocument_ValidArgument()
- {
- await _documentService.Insert(new Document());
- _documentRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Document>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Document>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertDocument_ValidArgument()
+ {
+ await _documentService.Insert(new Document());
+ _documentRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<Document>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Document>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateDocument_ValidArgument()
- {
- await _documentService.Update(new Document());
- _documentRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Document>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Document>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateDocument_ValidArgument()
+ {
+ await _documentService.Update(new Document());
+ _documentRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Document>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Document>>(), default), Times.Once);
+ }
- [TestMethod()]
- public void UpdateDocument_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentService.Update(null), "document");
- }
+ [TestMethod]
+ public void UpdateDocument_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentService.Update(null), "document");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentTypeServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentTypeServiceTests.cs
index dcf48563d..5110e86aa 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentTypeServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Documents/DocumentTypeServiceTests.cs
@@ -8,86 +8,88 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Documents
+namespace Grand.Business.Marketing.Tests.Services.Documents;
+
+[TestClass]
+public class DocumentTypeServiceTests
{
- [TestClass()]
- public class DocumentTypeServiceTests
- {
- private Mock<IRepository<DocumentType>> _documentTypeRepositoryMock;
- private DocumentTypeService _documentTypeService;
- private Mock<IMediator> _mediatorMock;
- private List<DocumentType> _expected;
- private IQueryable<DocumentType> _expectedQueryable;
+ private Mock<IRepository<DocumentType>> _documentTypeRepositoryMock;
+ private DocumentTypeService _documentTypeService;
+ private List<DocumentType> _expected;
+ private IQueryable<DocumentType> _expectedQueryable;
+ private Mock<IMediator> _mediatorMock;
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "";
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = "";
- _mediatorMock = new Mock<IMediator>();
- _documentTypeRepositoryMock = new Mock<IRepository<DocumentType>>();
- var _mongoQueryableMock = new Mock<MongoRepository<DocumentType>>(Mock.Of<IAuditInfoProvider>());
- _expected = [
- new DocumentType { Name = "name1", Description = "t1", DisplayOrder = 0 },
- new DocumentType { Name = "name2", Description = "t2", DisplayOrder = 1 }
- ];
- _expectedQueryable = _expected.AsQueryable();
- //_mongoQueryableMock.Setup(x => x.ElementType).Returns(_expectedQueryable.ElementType);
- //_mongoQueryableMock.Setup(x => x.Expression).Returns(_expectedQueryable.Expression);
- //_mongoQueryableMock.Setup(x => x.Provider).Returns(_expectedQueryable.Provider);
- //_mongoQueryableMock.Setup(x => x.GetEnumerator()).Returns(_expectedQueryable.GetEnumerator());
+ _mediatorMock = new Mock<IMediator>();
+ _documentTypeRepositoryMock = new Mock<IRepository<DocumentType>>();
+ var _mongoQueryableMock = new Mock<MongoRepository<DocumentType>>(Mock.Of<IAuditInfoProvider>());
+ _expected = [
+ new DocumentType { Name = "name1", Description = "t1", DisplayOrder = 0 },
+ new DocumentType { Name = "name2", Description = "t2", DisplayOrder = 1 }
+ ];
+ _expectedQueryable = _expected.AsQueryable();
+ //_mongoQueryableMock.Setup(x => x.ElementType).Returns(_expectedQueryable.ElementType);
+ //_mongoQueryableMock.Setup(x => x.Expression).Returns(_expectedQueryable.Expression);
+ //_mongoQueryableMock.Setup(x => x.Provider).Returns(_expectedQueryable.Provider);
+ //_mongoQueryableMock.Setup(x => x.GetEnumerator()).Returns(_expectedQueryable.GetEnumerator());
- _documentTypeRepositoryMock.Setup(x => x.Table).Returns(_mongoQueryableMock.Object.Table);
- _documentTypeService = new DocumentTypeService(_documentTypeRepositoryMock.Object, _mediatorMock.Object);
- }
+ _documentTypeRepositoryMock.Setup(x => x.Table).Returns(_mongoQueryableMock.Object.Table);
+ _documentTypeService = new DocumentTypeService(_documentTypeRepositoryMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task DeleteDocumentType_NullArgument_ThrowException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentTypeService.Delete(null), "documentType");
- }
+ [TestMethod]
+ public async Task DeleteDocumentType_NullArgument_ThrowException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentTypeService.Delete(null),
+ "documentType");
+ }
- [TestMethod()]
- public async Task DeleteDocumentType_ValidArgument()
- {
- await _documentTypeService.Delete(new DocumentType());
- _documentTypeRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<DocumentType>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<DocumentType>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteDocumentType_ValidArgument()
+ {
+ await _documentTypeService.Delete(new DocumentType());
+ _documentTypeRepositoryMock.Verify(c => c.DeleteAsync(It.IsAny<DocumentType>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<DocumentType>>(), default), Times.Once);
+ }
- [TestMethod]
- public async Task GetDocumentTypeById()
- {
- await _documentTypeService.GetById("id");
- _documentTypeRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GetDocumentTypeById()
+ {
+ await _documentTypeService.GetById("id");
+ _documentTypeRepositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertDocumentType_NullArgument_ThrowException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentTypeService.Insert(null), "documentType");
- }
+ [TestMethod]
+ public async Task InsertDocumentType_NullArgument_ThrowException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentTypeService.Insert(null),
+ "documentType");
+ }
- [TestMethod()]
- public async Task InsertDocumentType_ValidArgument()
- {
- await _documentTypeService.Insert(new DocumentType());
- _documentTypeRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<DocumentType>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<DocumentType>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertDocumentType_ValidArgument()
+ {
+ await _documentTypeService.Insert(new DocumentType());
+ _documentTypeRepositoryMock.Verify(c => c.InsertAsync(It.IsAny<DocumentType>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<DocumentType>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateDocumentType_ValidArgument()
- {
- await _documentTypeService.Update(new DocumentType());
- _documentTypeRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<DocumentType>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<DocumentType>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateDocumentType_ValidArgument()
+ {
+ await _documentTypeService.Update(new DocumentType());
+ _documentTypeRepositoryMock.Verify(c => c.UpdateAsync(It.IsAny<DocumentType>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<DocumentType>>(), default), Times.Once);
+ }
- [TestMethod()]
- public void UpdateDocumentType_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentTypeService.Update(null), "documentType");
- }
+ [TestMethod]
+ public void UpdateDocumentType_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _documentTypeService.Update(null),
+ "documentType");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsLetterSubscriptionServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsLetterSubscriptionServiceTests.cs
index b77adf6d7..bfa433e5a 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsLetterSubscriptionServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsLetterSubscriptionServiceTests.cs
@@ -1,9 +1,9 @@
-using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Business.Core.Events.Marketing;
+using Grand.Business.Core.Events.Marketing;
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Marketing.Newsletters;
using Grand.Business.Marketing.Services.Newsletters;
-using Grand.Domain;
using Grand.Data;
+using Grand.Domain;
using Grand.Domain.Messages;
using Grand.Infrastructure.Events;
using Grand.SharedKernel;
@@ -11,80 +11,81 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Newsletters
+namespace Grand.Business.Marketing.Tests.Services.Newsletters;
+
+[TestClass]
+public class NewsLetterSubscriptionServiceTests
{
- [TestClass()]
- public class NewsLetterSubscriptionServiceTests
- {
- private Mock<IMediator> _mediatorMock;
- private Mock<IRepository<NewsLetterSubscription>> _subscriptionRepository;
- private Mock<IHistoryService> _historyServiceMock;
- private INewsLetterSubscriptionService _newsLetterSubscriptionService;
+ private Mock<IHistoryService> _historyServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private INewsLetterSubscriptionService _newsLetterSubscriptionService;
+ private Mock<IRepository<NewsLetterSubscription>> _subscriptionRepository;
- [TestInitialize()]
- public void TestInitialize()
- {
- _mediatorMock = new Mock<IMediator>();
- _subscriptionRepository = new Mock<IRepository<NewsLetterSubscription>>();
- _historyServiceMock = new Mock<IHistoryService>();
- _newsLetterSubscriptionService = new NewsLetterSubscriptionService(_subscriptionRepository.Object, _mediatorMock.Object, _historyServiceMock.Object);
- }
+ [TestInitialize]
+ public void TestInitialize()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _subscriptionRepository = new Mock<IRepository<NewsLetterSubscription>>();
+ _historyServiceMock = new Mock<IHistoryService>();
+ _newsLetterSubscriptionService = new NewsLetterSubscriptionService(_subscriptionRepository.Object,
+ _mediatorMock.Object, _historyServiceMock.Object);
+ }
- [TestMethod]
- public void InsertNewsLetterSubscription_InvalidEmail_ThrowException()
- {
- var email = "NotValidEmail";
- var newsLetterSubscription = new NewsLetterSubscription {
- Email = email
- };
- Assert.ThrowsExceptionAsync<GrandException>(async () => await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription));
- }
+ [TestMethod]
+ public void InsertNewsLetterSubscription_InvalidEmail_ThrowException()
+ {
+ var email = "NotValidEmail";
+ var newsLetterSubscription = new NewsLetterSubscription {
+ Email = email
+ };
+ Assert.ThrowsExceptionAsync<GrandException>(async () =>
+ await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription));
+ }
- [TestMethod]
- public async Task InsertNewsLetterSubscription_ActiveSubcription_InvokeRepositoryAndPublishSubscriptionEvent()
- {
- var email = "[email protected]";
- var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = true };
- await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
- _subscriptionRepository.Verify(r => r.InsertAsync(newsLetterSubscription), Times.Once);
- _historyServiceMock.Verify(h => h.SaveObject(It.IsAny<BaseEntity>()), Times.Once);
- _mediatorMock.Verify(m => m.Publish<EmailSubscribedEvent>(It.IsAny<EmailSubscribedEvent>(), default(CancellationToken)), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<NewsLetterSubscription>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertNewsLetterSubscription_ActiveSubcription_InvokeRepositoryAndPublishSubscriptionEvent()
+ {
+ var email = "[email protected]";
+ var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = true };
+ await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
+ _subscriptionRepository.Verify(r => r.InsertAsync(newsLetterSubscription), Times.Once);
+ _historyServiceMock.Verify(h => h.SaveObject(It.IsAny<BaseEntity>()), Times.Once);
+ _mediatorMock.Verify(m => m.Publish(It.IsAny<EmailSubscribedEvent>(), default), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<NewsLetterSubscription>>(), default), Times.Once);
+ }
- [TestMethod]
- public async Task InsertNewsLetterSubscription_InactiveSubcription_InvokeRepository()
- {
- var email = "[email protected]";
- var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = false };
- await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
- _subscriptionRepository.Verify(r => r.InsertAsync(newsLetterSubscription), Times.Once);
- _historyServiceMock.Verify(h => h.SaveObject(It.IsAny<BaseEntity>()), Times.Once);
- _mediatorMock.Verify(m => m.Publish<EmailSubscribedEvent>(It.IsAny<EmailSubscribedEvent>(), default(CancellationToken)), Times.Never);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<NewsLetterSubscription>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertNewsLetterSubscription_InactiveSubcription_InvokeRepository()
+ {
+ var email = "[email protected]";
+ var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = false };
+ await _newsLetterSubscriptionService.InsertNewsLetterSubscription(newsLetterSubscription);
+ _subscriptionRepository.Verify(r => r.InsertAsync(newsLetterSubscription), Times.Once);
+ _historyServiceMock.Verify(h => h.SaveObject(It.IsAny<BaseEntity>()), Times.Once);
+ _mediatorMock.Verify(m => m.Publish(It.IsAny<EmailSubscribedEvent>(), default), Times.Never);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<NewsLetterSubscription>>(), default), Times.Once);
+ }
- [TestMethod]
- public async Task UpdateNewsLetterSubscription_InvokeRepository()
- {
- var email = "[email protected]";
- var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = false };
- await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsLetterSubscription);
- _subscriptionRepository.Verify(r => r.UpdateAsync(newsLetterSubscription), Times.Once);
- _historyServiceMock.Verify(h => h.SaveObject(It.IsAny<BaseEntity>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<NewsLetterSubscription>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateNewsLetterSubscription_InvokeRepository()
+ {
+ var email = "[email protected]";
+ var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = false };
+ await _newsLetterSubscriptionService.UpdateNewsLetterSubscription(newsLetterSubscription);
+ _subscriptionRepository.Verify(r => r.UpdateAsync(newsLetterSubscription), Times.Once);
+ _historyServiceMock.Verify(h => h.SaveObject(It.IsAny<BaseEntity>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<NewsLetterSubscription>>(), default), Times.Once);
+ }
- [TestMethod]
- public async Task DeleteNewsLetterSubscription_InvokeRepositoryAndEmailUnsubscribedEvent()
- {
- var email = "[email protected]";
- var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = false };
- await _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsLetterSubscription);
- _subscriptionRepository.Verify(r => r.DeleteAsync(newsLetterSubscription), Times.Once);
- _mediatorMock.Verify(m => m.Publish<EmailUnsubscribedEvent>(It.IsAny<EmailUnsubscribedEvent>(), default(CancellationToken)), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<NewsLetterSubscription>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteNewsLetterSubscription_InvokeRepositoryAndEmailUnsubscribedEvent()
+ {
+ var email = "[email protected]";
+ var newsLetterSubscription = new NewsLetterSubscription { Email = email, Active = false };
+ await _newsLetterSubscriptionService.DeleteNewsLetterSubscription(newsLetterSubscription);
+ _subscriptionRepository.Verify(r => r.DeleteAsync(newsLetterSubscription), Times.Once);
+ _mediatorMock.Verify(m => m.Publish(It.IsAny<EmailUnsubscribedEvent>(), default), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<NewsLetterSubscription>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.cs
index a7f62e046..1ecdf6514 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/Newsletters/NewsletterCategoryServiceTests.cs
@@ -6,70 +6,72 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Marketing.Tests.Services.Newsletters
+namespace Grand.Business.Marketing.Tests.Services.Newsletters;
+
+[TestClass]
+public class NewsletterCategoryServiceTests
{
- [TestClass()]
- public class NewsletterCategoryServiceTests
- {
- private Mock<IRepository<NewsletterCategory>> _repoMock;
- private Mock<IMediator> _mediatorMock;
- private NewsletterCategoryService _newsletterCategoryService;
+ private Mock<IMediator> _mediatorMock;
+ private NewsletterCategoryService _newsletterCategoryService;
+ private Mock<IRepository<NewsletterCategory>> _repoMock;
- [TestInitialize()]
- public void Init()
- {
- _repoMock = new Mock<IRepository<NewsletterCategory>>();
- _mediatorMock = new Mock<IMediator>();
- _newsletterCategoryService = new NewsletterCategoryService(_repoMock.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repoMock = new Mock<IRepository<NewsletterCategory>>();
+ _mediatorMock = new Mock<IMediator>();
+ _newsletterCategoryService = new NewsletterCategoryService(_repoMock.Object, _mediatorMock.Object);
+ }
- [TestMethod()]
- public async Task DeleteNewsletterCategory_NullArgument_ThrowException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _newsletterCategoryService.DeleteNewsletterCategory(null), "newslettercategory");
- }
+ [TestMethod]
+ public async Task DeleteNewsletterCategory_NullArgument_ThrowException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _newsletterCategoryService.DeleteNewsletterCategory(null), "newslettercategory");
+ }
- [TestMethod()]
- public async Task DeleteNewsletterCategory_ValidArgument()
- {
- await _newsletterCategoryService.DeleteNewsletterCategory(new NewsletterCategory());
- _repoMock.Verify(c => c.DeleteAsync(It.IsAny<NewsletterCategory>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<NewsletterCategory>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteNewsletterCategory_ValidArgument()
+ {
+ await _newsletterCategoryService.DeleteNewsletterCategory(new NewsletterCategory());
+ _repoMock.Verify(c => c.DeleteAsync(It.IsAny<NewsletterCategory>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<NewsletterCategory>>(), default), Times.Once);
+ }
- [TestMethod]
- public async Task GetDocumentById()
- {
- await _newsletterCategoryService.GetNewsletterCategoryById("id");
- _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GetDocumentById()
+ {
+ await _newsletterCategoryService.GetNewsletterCategoryById("id");
+ _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
- [TestMethod()]
- public async Task InsertNewsletterCategory_NullArgument_ThrowException()
- {
- await Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _newsletterCategoryService.InsertNewsletterCategory(null), "newslettercategory");
- }
+ [TestMethod]
+ public async Task InsertNewsletterCategory_NullArgument_ThrowException()
+ {
+ await Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _newsletterCategoryService.InsertNewsletterCategory(null), "newslettercategory");
+ }
- [TestMethod()]
- public async Task InsertNewsletterCategory_ValidArgument()
- {
- await _newsletterCategoryService.InsertNewsletterCategory(new NewsletterCategory());
- _repoMock.Verify(c => c.InsertAsync(It.IsAny<NewsletterCategory>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<NewsletterCategory>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertNewsletterCategory_ValidArgument()
+ {
+ await _newsletterCategoryService.InsertNewsletterCategory(new NewsletterCategory());
+ _repoMock.Verify(c => c.InsertAsync(It.IsAny<NewsletterCategory>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<NewsletterCategory>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateNewsletterCategory_ValidArgument()
- {
- await _newsletterCategoryService.UpdateNewsletterCategory(new NewsletterCategory());
- _repoMock.Verify(c => c.UpdateAsync(It.IsAny<NewsletterCategory>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<NewsletterCategory>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateNewsletterCategory_ValidArgument()
+ {
+ await _newsletterCategoryService.UpdateNewsletterCategory(new NewsletterCategory());
+ _repoMock.Verify(c => c.UpdateAsync(It.IsAny<NewsletterCategory>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<NewsletterCategory>>(), default), Times.Once);
+ }
- [TestMethod()]
- public void UpdateNewsletterCategory_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _newsletterCategoryService.UpdateNewsletterCategory(null), "newslettercategory");
- }
+ [TestMethod]
+ public void UpdateNewsletterCategory_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(
+ async () => await _newsletterCategoryService.UpdateNewsletterCategory(null), "newslettercategory");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs
index ead2dba74..7bd799e1b 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Services/PushNotifications/PushNotificationsServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Marketing.Services.PushNotifications;
using Grand.Business.Marketing.Utilities;
-using Grand.Data.Tests.MongoDb;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.PushNotifications;
using MediatR;
using Microsoft.Extensions.Logging;
@@ -12,204 +12,205 @@ using System.Net;
using System.Net.Http;
using System.Text.Json;
-namespace Grand.Business.Marketing.Tests.Services.PushNotifications
+namespace Grand.Business.Marketing.Tests.Services.PushNotifications;
+
+[TestClass]
+public class PushNotificationsServiceTests
{
- [TestClass()]
- public class PushNotificationsServiceTests
+ private Mock<ILogger<PushNotificationsService>> _loggerMock;
+ private Mock<IMediator> _mediatorMock;
+ private PushNotificationsService _pushNotificationsService;
+ private IRepository<PushMessage> _repositoryPushMessage;
+ private IRepository<PushRegistration> _repositoryPushRegistration;
+
+
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryPushRegistration = new MongoDBRepositoryTest<PushRegistration>();
+ _repositoryPushMessage = new MongoDBRepositoryTest<PushMessage>();
+ _mediatorMock = new Mock<IMediator>();
+ _loggerMock = new Mock<ILogger<PushNotificationsService>>();
+
+ var mockMessageHandler = new Mock<HttpMessageHandler>();
+
+ var output = JsonSerializer.Serialize(new JsonResponse { success = 1, failure = 0, canonical_ids = 1 });
+
+ mockMessageHandler.Protected()
+ .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(),
+ ItExpr.IsAny<CancellationToken>())
+ .ReturnsAsync(new HttpResponseMessage {
+ StatusCode = HttpStatusCode.OK,
+ Content = new StringContent(output)
+ });
+ var httpClient = new HttpClient(mockMessageHandler.Object);
+
+ _pushNotificationsService = new PushNotificationsService(_repositoryPushRegistration, _repositoryPushMessage,
+ _mediatorMock.Object, new PushNotificationsSettings(),
+ _loggerMock.Object, httpClient);
+ }
+
+ [TestMethod]
+ public async Task InsertPushReceiverTest()
+ {
+ //Act
+ await _pushNotificationsService.InsertPushReceiver(new PushRegistration());
+ //Assert
+ Assert.IsTrue(_repositoryPushRegistration.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task DeletePushReceiverTest()
+ {
+ //Arrange
+ var pushRegistration = new PushRegistration();
+ await _pushNotificationsService.InsertPushReceiver(pushRegistration);
+
+ //Act
+ await _pushNotificationsService.DeletePushReceiver(pushRegistration);
+
+ //Assert
+ Assert.IsFalse(_repositoryPushRegistration.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task GetPushReceiverByCustomerIdTest()
+ {
+ //Arrange
+ var pushRegistration = new PushRegistration { CustomerId = "1" };
+ await _pushNotificationsService.InsertPushReceiver(pushRegistration);
+
+ //Act
+ var result = await _pushNotificationsService.GetPushReceiverByCustomerId(pushRegistration.CustomerId);
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual("1", result.CustomerId);
+ }
+
+ [TestMethod]
+ public async Task UpdatePushReceiverTest()
+ {
+ //Arrange
+ var pushRegistration = new PushRegistration { CustomerId = "1" };
+ await _pushNotificationsService.InsertPushReceiver(pushRegistration);
+
+ //Act
+ pushRegistration.Allowed = true;
+ await _pushNotificationsService.UpdatePushReceiver(pushRegistration);
+
+ //Assert
+ Assert.IsTrue(_repositoryPushRegistration.Table.FirstOrDefault(x => x.Id == pushRegistration.Id).Allowed);
+ }
+
+ [TestMethod]
+ public async Task GetPushReceiversTest()
+ {
+ //Arrange
+ await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
+ await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
+
+ //Act
+ var result = await _pushNotificationsService.GetPushReceivers();
+
+ //Assert
+ Assert.AreEqual(2, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetAllowedReceiversTest()
+ {
+ //Arrange
+ await _pushNotificationsService.InsertPushReceiver(new PushRegistration());
+ await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
+
+ //Act
+ var result = await _pushNotificationsService.GetAllowedReceivers();
+
+ //Assert
+ Assert.AreEqual(1, result);
+ }
+
+ [TestMethod]
+ public async Task GetDeniedReceiversTest()
+ {
+ //Arrange
+ await _pushNotificationsService.InsertPushReceiver(new PushRegistration());
+ await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
+
+ //Act
+ var result = await _pushNotificationsService.GetDeniedReceivers();
+
+ //Assert
+ Assert.AreEqual(1, result);
+ }
+
+ [TestMethod]
+ public async Task InsertPushMessageTest()
+ {
+ //Act
+ await _pushNotificationsService.InsertPushMessage(new PushMessage());
+ //Assert
+ Assert.IsFalse(_repositoryPushRegistration.Table.Any());
+ }
+
+ [TestMethod]
+ public async Task GetPushMessagesTest()
+ {
+ //Arrange
+ await _pushNotificationsService.InsertPushMessage(new PushMessage());
+ await _pushNotificationsService.InsertPushMessage(new PushMessage());
+ await _pushNotificationsService.InsertPushMessage(new PushMessage());
+
+ //Act
+ var result = await _pushNotificationsService.GetPushMessages();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task GetPushReceiversTest1()
{
- private PushNotificationsService _pushNotificationsService;
- private IRepository<PushRegistration> _repositoryPushRegistration;
- private IRepository<PushMessage> _repositoryPushMessage;
- private Mock<IMediator> _mediatorMock;
- private Mock<ILogger<PushNotificationsService>> _loggerMock;
-
-
- [TestInitialize()]
- public void Init()
- {
- _repositoryPushRegistration = new MongoDBRepositoryTest<PushRegistration>();
- _repositoryPushMessage = new MongoDBRepositoryTest<PushMessage>();
- _mediatorMock = new Mock<IMediator>();
- _loggerMock = new Mock<ILogger<PushNotificationsService>>();
-
- var mockMessageHandler = new Mock<HttpMessageHandler>();
-
- var output = JsonSerializer.Serialize(new JsonResponse { success = 1, failure = 0, canonical_ids = 1 });
-
- mockMessageHandler.Protected()
- .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
- .ReturnsAsync(new HttpResponseMessage {
- StatusCode = HttpStatusCode.OK,
- Content = new StringContent(output)
- });
- var httpClient = new HttpClient(mockMessageHandler.Object);
-
- _pushNotificationsService = new PushNotificationsService(_repositoryPushRegistration, _repositoryPushMessage, _mediatorMock.Object, new PushNotificationsSettings(),
- _loggerMock.Object, httpClient);
- }
-
- [TestMethod()]
- public async Task InsertPushReceiverTest()
- {
- //Act
- await _pushNotificationsService.InsertPushReceiver(new PushRegistration());
- //Assert
- Assert.IsTrue(_repositoryPushRegistration.Table.Any());
- }
-
- [TestMethod()]
- public async Task DeletePushReceiverTest()
- {
- //Arrange
- var pushRegistration = new PushRegistration();
- await _pushNotificationsService.InsertPushReceiver(pushRegistration);
-
- //Act
- await _pushNotificationsService.DeletePushReceiver(pushRegistration);
-
- //Assert
- Assert.IsFalse(_repositoryPushRegistration.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetPushReceiverByCustomerIdTest()
- {
- //Arrange
- var pushRegistration = new PushRegistration { CustomerId = "1" };
- await _pushNotificationsService.InsertPushReceiver(pushRegistration);
-
- //Act
- var result = await _pushNotificationsService.GetPushReceiverByCustomerId(pushRegistration.CustomerId);
-
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual("1", result.CustomerId);
- }
-
- [TestMethod()]
- public async Task UpdatePushReceiverTest()
- {
- //Arrange
- var pushRegistration = new PushRegistration { CustomerId = "1" };
- await _pushNotificationsService.InsertPushReceiver(pushRegistration);
-
- //Act
- pushRegistration.Allowed = true;
- await _pushNotificationsService.UpdatePushReceiver(pushRegistration);
-
- //Assert
- Assert.IsTrue(_repositoryPushRegistration.Table.FirstOrDefault(x => x.Id == pushRegistration.Id).Allowed);
- }
-
- [TestMethod()]
- public async Task GetPushReceiversTest()
- {
- //Arrange
- await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
- await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
-
- //Act
- var result = await _pushNotificationsService.GetPushReceivers();
-
- //Assert
- Assert.AreEqual(2, result.Count);
- }
-
- [TestMethod()]
- public async Task GetAllowedReceiversTest()
- {
- //Arrange
- await _pushNotificationsService.InsertPushReceiver(new PushRegistration());
- await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
-
- //Act
- var result = await _pushNotificationsService.GetAllowedReceivers();
-
- //Assert
- Assert.AreEqual(1, result);
- }
-
- [TestMethod()]
- public async Task GetDeniedReceiversTest()
- {
- //Arrange
- await _pushNotificationsService.InsertPushReceiver(new PushRegistration());
- await _pushNotificationsService.InsertPushReceiver(new PushRegistration { Allowed = true });
-
- //Act
- var result = await _pushNotificationsService.GetDeniedReceivers();
-
- //Assert
- Assert.AreEqual(1, result);
- }
-
- [TestMethod()]
- public async Task InsertPushMessageTest()
- {
- //Act
- await _pushNotificationsService.InsertPushMessage(new PushMessage());
- //Assert
- Assert.IsFalse(_repositoryPushRegistration.Table.Any());
- }
-
- [TestMethod()]
- public async Task GetPushMessagesTest()
- {
- //Arrange
- await _pushNotificationsService.InsertPushMessage(new PushMessage());
- await _pushNotificationsService.InsertPushMessage(new PushMessage());
- await _pushNotificationsService.InsertPushMessage(new PushMessage());
-
- //Act
- var result = await _pushNotificationsService.GetPushMessages();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task GetPushReceiversTest1()
- {
- //Arrange
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
-
- //Act
- var result = await _pushNotificationsService.GetPushReceivers();
-
- //Assert
- Assert.AreEqual(3, result.Count);
- }
-
- [TestMethod()]
- public async Task SendPushNotificationTest()
- {
- //Arrange
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
- //Act
- var result = await _pushNotificationsService.SendPushNotification("my title", "sample text", "", "");
- //Assert
- Assert.IsTrue(result.Item1);
- }
-
-
- [TestMethod()]
- public async Task GetPushReceiverTest()
- {
- //Arrange
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Id = "1", Allowed = true });
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
- await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
-
- //Act
- var result = await _pushNotificationsService.GetPushReceiver("1");
-
- //Assert
- Assert.IsNotNull(result);
- Assert.IsTrue(result.Allowed);
- }
+ //Arrange
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+
+ //Act
+ var result = await _pushNotificationsService.GetPushReceivers();
+
+ //Assert
+ Assert.AreEqual(3, result.Count);
+ }
+
+ [TestMethod]
+ public async Task SendPushNotificationTest()
+ {
+ //Arrange
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+ //Act
+ var result = await _pushNotificationsService.SendPushNotification("my title", "sample text", "", "");
+ //Assert
+ Assert.IsTrue(result.Item1);
+ }
+
+
+ [TestMethod]
+ public async Task GetPushReceiverTest()
+ {
+ //Arrange
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Id = "1", Allowed = true });
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+ await _repositoryPushRegistration.InsertAsync(new PushRegistration { Allowed = true });
+
+ //Act
+ var result = await _pushNotificationsService.GetPushReceiver("1");
+
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.IsTrue(result.Allowed);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Marketing.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Marketing.Tests/Startup/StartupApplicationTests.cs
index c30f9b4e1..ff5aa29c4 100644
--- a/src/Tests/Grand.Business.Marketing.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Marketing.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Marketing.Tests.Startup
+namespace Grand.Business.Marketing.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs
index b5619bf83..99bc18a4a 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs
@@ -1,37 +1,36 @@
using Grand.Business.Core.Commands.Messages.Common;
using Grand.Business.Messages.Commands.Handlers.Common;
-using Grand.Domain.Common;
using Grand.Data;
+using Grand.Domain.Common;
using Grand.Domain.Messages;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Messages.Tests.Commands
+namespace Grand.Business.Messages.Tests.Commands;
+
+[TestClass]
+public class InsertContactUsCommandHandlerTests
{
- [TestClass]
- public class InsertContactUsCommandHandlerTests
- {
- private Mock<IRepository<ContactUs>> _repositoryMock;
- private InsertContactUsCommandHandler _handler;
+ private InsertContactUsCommandHandler _handler;
+ private Mock<IRepository<ContactUs>> _repositoryMock;
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<ContactUs>>();
- _handler = new InsertContactUsCommandHandler(_repositoryMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _repositoryMock = new Mock<IRepository<ContactUs>>();
+ _handler = new InsertContactUsCommandHandler(_repositoryMock.Object);
+ }
- [TestMethod]
- public async Task Handler_InsertEntity()
- {
- var command = new InsertContactUsCommand {
- ContactAttributeDescription = "d",
- Email = "[email protected]",
- ContactAttributes = new List<CustomAttribute>()
- };
+ [TestMethod]
+ public async Task Handler_InsertEntity()
+ {
+ var command = new InsertContactUsCommand {
+ ContactAttributeDescription = "d",
+ Email = "[email protected]",
+ ContactAttributes = new List<CustomAttribute>()
+ };
- await _handler.Handle(command, default);
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<ContactUs>()), Times.Once);
- }
+ await _handler.Handle(command, default);
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<ContactUs>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetBidsByProductIdQueryHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetBidsByProductIdQueryHandlerTests.cs
index 6f072b4df..9e464ad55 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetBidsByProductIdQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetBidsByProductIdQueryHandlerTests.cs
@@ -1,35 +1,34 @@
-using Grand.Business.Messages.Queries.Handlers;
+using Grand.Business.Core.Queries.Messages;
+using Grand.Business.Messages.Queries.Handlers;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Messages.Tests.Queries.Handlers
+namespace Grand.Business.Messages.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetBidsByProductIdQueryHandlerTests
{
+ private GetBidsByProductIdQueryHandler handler;
- [TestClass()]
- public class GetBidsByProductIdQueryHandlerTests
+ [TestInitialize]
+ public void Init()
{
- private GetBidsByProductIdQueryHandler handler;
-
- [TestInitialize()]
- public void Init()
- {
- var _repository = new MongoDBRepositoryTest<Bid>();
- _repository.Insert(new Bid { Id = "1", ProductId = "1" });
- _repository.Insert(new Bid());
- _repository.Insert(new Bid());
- _repository.Insert(new Bid());
+ var _repository = new MongoDBRepositoryTest<Bid>();
+ _repository.Insert(new Bid { Id = "1", ProductId = "1" });
+ _repository.Insert(new Bid());
+ _repository.Insert(new Bid());
+ _repository.Insert(new Bid());
- handler = new GetBidsByProductIdQueryHandler(_repository);
- }
+ handler = new GetBidsByProductIdQueryHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Act
- var result = await handler.Handle(new Core.Queries.Messages.GetBidsByProductIdQuery { ProductId = "1" }, CancellationToken.None);
- //Assert
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Act
+ var result = await handler.Handle(new GetBidsByProductIdQuery { ProductId = "1" }, CancellationToken.None);
+ //Assert
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetCustomerByIdQueryHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetCustomerByIdQueryHandlerTests.cs
index beeda8c3a..1797ca44f 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetCustomerByIdQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetCustomerByIdQueryHandlerTests.cs
@@ -1,38 +1,38 @@
-using Grand.Business.Messages.Queries.Handlers;
+using Grand.Business.Core.Queries.Messages;
+using Grand.Business.Messages.Queries.Handlers;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Messages.Tests.Queries.Handlers
+namespace Grand.Business.Messages.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetCustomerByIdQueryHandlerTests
{
- [TestClass()]
- public class GetCustomerByIdQueryHandlerTests
- {
- private GetCustomerByIdQueryHandler handler;
+ private GetCustomerByIdQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- var _repository = new MongoDBRepositoryTest<Customer>();
- _repository.Insert(new Customer { Id = "1" });
- _repository.Insert(new Customer());
- _repository.Insert(new Customer());
- _repository.Insert(new Customer());
- handler = new GetCustomerByIdQueryHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ var _repository = new MongoDBRepositoryTest<Customer>();
+ _repository.Insert(new Customer { Id = "1" });
+ _repository.Insert(new Customer());
+ _repository.Insert(new Customer());
+ _repository.Insert(new Customer());
+ handler = new GetCustomerByIdQueryHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Assert
- var customerQuery = new Core.Queries.Messages.GetCustomerByIdQuery {
- Id = "1"
- };
- //Act
- var result = await handler.Handle(customerQuery, CancellationToken.None);
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Assert
+ var customerQuery = new GetCustomerByIdQuery {
+ Id = "1"
+ };
+ //Act
+ var result = await handler.Handle(customerQuery, CancellationToken.None);
- //Assert
- Assert.IsNotNull(result);
- }
+ //Assert
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetProductByIdQueryHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetProductByIdQueryHandlerTests.cs
index cdcd0b6ee..661011c8a 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetProductByIdQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetProductByIdQueryHandlerTests.cs
@@ -1,35 +1,34 @@
-using Grand.Business.Messages.Queries.Handlers;
+using Grand.Business.Core.Queries.Messages;
+using Grand.Business.Messages.Queries.Handlers;
using Grand.Data.Tests.MongoDb;
using Grand.Domain.Catalog;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Messages.Tests.Queries.Handlers
-{
- [TestClass()]
- public class GetProductByIdQueryHandlerTests
- {
- private GetProductByIdQueryHandler handler;
+namespace Grand.Business.Messages.Tests.Queries.Handlers;
- [TestInitialize()]
- public void Init()
- {
- var _repository = new MongoDBRepositoryTest<Product>();
- _repository.Insert(new Product { Id = "1" });
- _repository.Insert(new Product());
- _repository.Insert(new Product());
- _repository.Insert(new Product());
+[TestClass]
+public class GetProductByIdQueryHandlerTests
+{
+ private GetProductByIdQueryHandler handler;
- handler = new GetProductByIdQueryHandler(_repository);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ var _repository = new MongoDBRepositoryTest<Product>();
+ _repository.Insert(new Product { Id = "1" });
+ _repository.Insert(new Product());
+ _repository.Insert(new Product());
+ _repository.Insert(new Product());
- [TestMethod()]
- public async Task HandleTest()
- {
- //Act
- var result = await handler.Handle(new Core.Queries.Messages.GetProductByIdQuery { Id = "1" }, CancellationToken.None);
- //Assert
- Assert.IsNotNull(result);
- }
+ handler = new GetProductByIdQueryHandler(_repository);
}
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Act
+ var result = await handler.Handle(new GetProductByIdQuery { Id = "1" }, CancellationToken.None);
+ //Assert
+ Assert.IsNotNull(result);
+ }
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs
index 272659359..fbf7cf2cc 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Queries/Handlers/GetVendorByIdQueryHandlerTests.cs
@@ -1,32 +1,33 @@
-using Grand.Business.Messages.Queries.Handlers;
-using Grand.Data.Tests.MongoDb;
+using Grand.Business.Core.Queries.Messages;
+using Grand.Business.Messages.Queries.Handlers;
using Grand.Data;
+using Grand.Data.Tests.MongoDb;
using Grand.Domain.Vendors;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Messages.Tests.Queries.Handlers
+namespace Grand.Business.Messages.Tests.Queries.Handlers;
+
+[TestClass]
+public class GetVendorByIdQueryHandlerTests
{
- [TestClass()]
- public class GetVendorByIdQueryHandlerTests
+ private IRepository<Vendor> _repository;
+ private GetVendorByIdQueryHandler handler;
+
+ [TestInitialize]
+ public void Init()
{
- private IRepository<Vendor> _repository;
- private GetVendorByIdQueryHandler handler;
- [TestInitialize()]
- public void Init()
- {
- _repository = new MongoDBRepositoryTest<Vendor>();
- handler = new GetVendorByIdQueryHandler(_repository);
- }
+ _repository = new MongoDBRepositoryTest<Vendor>();
+ handler = new GetVendorByIdQueryHandler(_repository);
+ }
- [TestMethod()]
- public async Task HandleTest()
- {
- //Arrange
- await _repository.InsertAsync(new Vendor { Id = "1" });
- //Act
- var result = await handler.Handle(new Core.Queries.Messages.GetVendorByIdQuery { Id = "1" }, CancellationToken.None);
- //Arrange
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public async Task HandleTest()
+ {
+ //Arrange
+ await _repository.InsertAsync(new Vendor { Id = "1" });
+ //Act
+ var result = await handler.Handle(new GetVendorByIdQuery { Id = "1" }, CancellationToken.None);
+ //Arrange
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/EmailAccountServiceTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/EmailAccountServiceTests.cs
index c617b22f6..e18867652 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/EmailAccountServiceTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/EmailAccountServiceTests.cs
@@ -8,62 +8,60 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Messages.Tests.Services
-{
- [TestClass]
- public class EmailAccountServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IRepository<EmailAccount>> _repository;
- private EmailAccountService _service;
+namespace Grand.Business.Messages.Tests.Services;
- [TestInitialize]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _mediatorMock = new Mock<IMediator>();
- _repository = new Mock<IRepository<EmailAccount>>();
- _service = new EmailAccountService(_repository.Object, _cacheMock.Object, _mediatorMock.Object);
- }
+[TestClass]
+public class EmailAccountServiceTests
+{
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<EmailAccount>> _repository;
+ private EmailAccountService _service;
- [TestMethod]
- public async Task InsertEmailAccount_InvokeExpectedMethods()
- {
- await _service.InsertEmailAccount(new EmailAccount());
- _repository.Verify(c => c.InsertAsync(It.IsAny<EmailAccount>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<EmailAccount>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _mediatorMock = new Mock<IMediator>();
+ _repository = new Mock<IRepository<EmailAccount>>();
+ _service = new EmailAccountService(_repository.Object, _cacheMock.Object, _mediatorMock.Object);
+ }
- [TestMethod]
- public async Task UpdateEmailAccount_InvokeExpectedMethods()
- {
- await _service.UpdateEmailAccount(new EmailAccount());
- _repository.Verify(c => c.UpdateAsync(It.IsAny<EmailAccount>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<EmailAccount>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertEmailAccount_InvokeExpectedMethods()
+ {
+ await _service.InsertEmailAccount(new EmailAccount());
+ _repository.Verify(c => c.InsertAsync(It.IsAny<EmailAccount>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<EmailAccount>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public async Task DeleteEmailAccount_InvokeExpectedMethods()
- {
+ [TestMethod]
+ public async Task UpdateEmailAccount_InvokeExpectedMethods()
+ {
+ await _service.UpdateEmailAccount(new EmailAccount());
+ _repository.Verify(c => c.UpdateAsync(It.IsAny<EmailAccount>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<EmailAccount>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- _cacheMock.Setup(c => c.GetAsync<List<EmailAccount>>(It.IsAny<string>(), It.IsAny<Func<Task<List<EmailAccount>>>>()))
- .Returns(Task.FromResult(new List<EmailAccount> { new EmailAccount(), new EmailAccount() }));
- await _service.DeleteEmailAccount(new EmailAccount());
- _repository.Verify(c => c.DeleteAsync(It.IsAny<EmailAccount>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<EmailAccount>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteEmailAccount_InvokeExpectedMethods()
+ {
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<EmailAccount>>>>()))
+ .Returns(Task.FromResult(new List<EmailAccount> { new(), new() }));
+ await _service.DeleteEmailAccount(new EmailAccount());
+ _repository.Verify(c => c.DeleteAsync(It.IsAny<EmailAccount>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<EmailAccount>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public void DeleteEmailAccount_ExistOnlyOneAccount_ThrowException()
- {
- //we can't delete account if exist only one
- _cacheMock.Setup(c => c.GetAsync<List<EmailAccount>>(It.IsAny<string>(), It.IsAny<Func<Task<List<EmailAccount>>>>()))
- .Returns(Task.FromResult(new List<EmailAccount> { new EmailAccount() }));
- Assert.ThrowsExceptionAsync<GrandException>(async () => await _service.DeleteEmailAccount(new EmailAccount()));
- }
+ [TestMethod]
+ public void DeleteEmailAccount_ExistOnlyOneAccount_ThrowException()
+ {
+ //we can't delete account if exist only one
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<EmailAccount>>>>()))
+ .Returns(Task.FromResult(new List<EmailAccount> { new() }));
+ Assert.ThrowsExceptionAsync<GrandException>(async () => await _service.DeleteEmailAccount(new EmailAccount()));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/EmailSenderTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/EmailSenderTests.cs
index 911247ae2..6a293919a 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/EmailSenderTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/EmailSenderTests.cs
@@ -1,32 +1,34 @@
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.Core.Interfaces.Storage;
using Grand.Business.Messages.Services;
+using Grand.Domain.Messages;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Net.Sockets;
-namespace Grand.Business.Messages.Tests.Services
+namespace Grand.Business.Messages.Tests.Services;
+
+[TestClass]
+public class EmailSenderTests
{
- [TestClass()]
- public class EmailSenderTests
- {
- private EmailSender _sender;
- private Mock<IDownloadService> _downloadService;
- private Mock<IMimeMappingService> _mimeMappingService;
+ private Mock<IDownloadService> _downloadService;
+ private Mock<IMimeMappingService> _mimeMappingService;
+ private EmailSender _sender;
- [TestInitialize()]
- public void Init()
- {
- _downloadService = new Mock<IDownloadService>();
- _mimeMappingService = new Mock<IMimeMappingService>();
+ [TestInitialize]
+ public void Init()
+ {
+ _downloadService = new Mock<IDownloadService>();
+ _mimeMappingService = new Mock<IMimeMappingService>();
- _sender = new EmailSender(_downloadService.Object, _mimeMappingService.Object);
- }
+ _sender = new EmailSender(_downloadService.Object, _mimeMappingService.Object);
+ }
- [TestMethod()]
- public void SendEmailTest()
- {
- Assert.ThrowsExceptionAsync<SocketException>(async () => await _sender.SendEmail(new Domain.Messages.EmailAccount { Host = "[email protected]" }, "subject", "body", "[email protected]", "admin store", "[email protected]", "Customer name"));
- }
+ [TestMethod]
+ public void SendEmailTest()
+ {
+ Assert.ThrowsExceptionAsync<SocketException>(async () =>
+ await _sender.SendEmail(new EmailAccount { Host = "[email protected]" }, "subject", "body", "[email protected]",
+ "admin store", "[email protected]", "Customer name"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/LiquidObjectBuilderTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/LiquidObjectBuilderTests.cs
index 6e4c13269..fcd6e87f0 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/LiquidObjectBuilderTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/LiquidObjectBuilderTests.cs
@@ -7,41 +7,43 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Messages.Tests.Services
+namespace Grand.Business.Messages.Tests.Services;
+
+[TestClass]
+public class LiquidObjectBuilderTests
{
- [TestClass]
- public class LiquidObjectBuilderTests
- {
- private Mock<IMediator> _mediatorMock;
+ private Mock<IMediator> _mediatorMock;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ }
- [TestMethod]
- public async Task BuilderTest()
- {
- var builder = new LiquidObjectBuilder(_mediatorMock.Object);
- var vendor = new Vendor { Id = "VendorId", Name = "vendorName" };
- var product = new Product { Id = "productId", Name = "ProductName" };
- var vendorReview = new VendorReview { Id = "RevId" };
- _mediatorMock.Setup(c => c.Send<LiquidVendor>(It.IsAny<IRequest<LiquidVendor>>(), default)).ReturnsAsync(new LiquidVendor(vendor));
+ [TestMethod]
+ public async Task BuilderTest()
+ {
+ var builder = new LiquidObjectBuilder(_mediatorMock.Object);
+ var vendor = new Vendor { Id = "VendorId", Name = "vendorName" };
+ var product = new Product { Id = "productId", Name = "ProductName" };
+ var vendorReview = new VendorReview { Id = "RevId" };
+ _mediatorMock.Setup(c => c.Send(It.IsAny<IRequest<LiquidVendor>>(), default))
+ .ReturnsAsync(new LiquidVendor(vendor));
- var liquidObject = await builder
- .AddVendorReviewTokens(vendor, vendorReview)
- .AddVendorTokens(vendor, new Language())
- .AddOutOfStockTokens(product, new OutOfStockSubscription(), new Store(), new DomainHost { Url = "https://localhost:44350/" }, new Language())
- .BuildAsync();
+ var liquidObject = await builder
+ .AddVendorReviewTokens(vendor, vendorReview)
+ .AddVendorTokens(vendor, new Language())
+ .AddOutOfStockTokens(product, new OutOfStockSubscription(), new Store(),
+ new DomainHost { Url = "https://localhost:44350/" }, new Language())
+ .BuildAsync();
- Assert.IsTrue(liquidObject.Vendor != null);
- Assert.IsTrue((liquidObject.Vendor as LiquidVendor).Name.Equals(vendor.Name));
- Assert.IsNotNull(liquidObject.VendorReview as LiquidVendorReview);
- Assert.IsTrue((liquidObject.VendorReview as LiquidVendorReview).VendorName.Equals(vendor.Name));
- Assert.IsTrue((liquidObject.OutOfStockSubscription as LiquidOutOfStockSubscription).ProductName.Equals(product.Name));
- _mediatorMock.Verify(c => c.Publish(It.IsAny<INotification>(), default), Times.Exactly(3));
- }
+ Assert.IsTrue(liquidObject.Vendor != null);
+ Assert.IsTrue((liquidObject.Vendor as LiquidVendor).Name.Equals(vendor.Name));
+ Assert.IsNotNull(liquidObject.VendorReview as LiquidVendorReview);
+ Assert.IsTrue((liquidObject.VendorReview as LiquidVendorReview).VendorName.Equals(vendor.Name));
+ Assert.IsTrue(
+ (liquidObject.OutOfStockSubscription as LiquidOutOfStockSubscription).ProductName.Equals(product.Name));
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<INotification>(), default), Times.Exactly(3));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs b/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs
index 4e4befc94..986df3619 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/MessageProviderServiceTest.cs
@@ -16,105 +16,107 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Messages.Tests.Services
+namespace Grand.Business.Messages.Tests.Services;
+
+[TestClass]
+public class MessageProviderServiceTest
{
- [TestClass()]
- public class MessageProviderServiceTest
+ private Mock<CommonSettings> _commonSetting;
+ private Mock<IEmailAccountService> _emailAccountServiceMock;
+ private Mock<EmailAccountSettings> _emailAccountSettingsMock;
+ private Mock<IGroupService> _groupService;
+ private Mock<ILanguageService> _languageServiceMock;
+ private Mock<IMediator> _mediatorMock;
+ private MessageProviderService _messageService;
+ private Mock<IMessageTemplateService> _messageTemplateServiceMock;
+ private Mock<IMessageTokenProvider> _messageTokenProviderMock;
+ private Product _product;
+ private Mock<IQueuedEmailService> _queuedEmailServiceMock;
+ private Mock<IStoreHelper> _storeHelperServiceMock;
+ private Mock<IStoreService> _storeServiceMock;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _messageTemplateServiceMock = new Mock<IMessageTemplateService>();
+ _messageTemplateServiceMock.Setup(x => x.GetMessageTemplateByName(It.IsAny<string>(), It.IsAny<string>()))
+ .Returns(Task.FromResult(new MessageTemplate { IsActive = true }));
+
+ _queuedEmailServiceMock = new Mock<IQueuedEmailService>();
+ _groupService = new Mock<IGroupService>();
+ _languageServiceMock = new Mock<ILanguageService>();
+ _languageServiceMock.Setup(x => x.GetLanguageById(It.IsAny<string>())).Returns(Task.FromResult(new Language()));
+ _languageServiceMock.Setup(x => x.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(
+ Task.FromResult(
+ new List<Language> { new() { Name = "English" }, new() { Name = "Polish" } } as IList<Language>));
+
+ _emailAccountServiceMock = new Mock<IEmailAccountService>();
+ _emailAccountServiceMock.Setup(x => x.GetAllEmailAccounts())
+ .Returns(Task.FromResult(
+ new List<EmailAccount> { new() { Email = "[email protected]" } } as IList<EmailAccount>));
+
+ _messageTokenProviderMock = new Mock<IMessageTokenProvider>();
+
+ _storeServiceMock = new Mock<IStoreService>();
+ _storeServiceMock.Setup(x => x.GetStoreById(It.IsAny<string>()))
+ .Returns(Task.FromResult(new Store { Url = "https://localhost:44350/" }));
+ _storeServiceMock.Setup(x => x.GetAllStores()).Returns(Task.FromResult(new List<Store>() as IList<Store>));
+
+ _storeHelperServiceMock = new Mock<IStoreHelper>();
+
+ _mediatorMock = new Mock<IMediator>();
+ _mediatorMock.Setup(x => x.Send(It.IsAny<GetCustomerByIdQuery>(), default))
+ .Returns(Task.FromResult(new Customer { Email = "[email protected]" }));
+
+ _emailAccountSettingsMock = new Mock<EmailAccountSettings>();
+ _commonSetting = new Mock<CommonSettings>();
+
+ _messageService = new MessageProviderService(
+ _messageTemplateServiceMock.Object,
+ _queuedEmailServiceMock.Object,
+ _languageServiceMock.Object,
+ _emailAccountServiceMock.Object,
+ _storeServiceMock.Object,
+ _storeHelperServiceMock.Object,
+ _groupService.Object,
+ _mediatorMock.Object,
+ _emailAccountSettingsMock.Object,
+ _commonSetting.Object);
+ _product = new Product();
+ }
+
+ [TestMethod]
+ public async Task CallInsertQueuedEmailMethod()
+ {
+ var result = await _messageService.SendOutBidCustomerMessage(new Product(), "123", new Bid());
+ _queuedEmailServiceMock.Verify(x => x.InsertQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once());
+ }
+
+ [TestMethod]
+ public async Task SendOutBidCustomerNotificationMethodReturnCorrectResult()
+ {
+ var result = await _messageService.SendOutBidCustomerMessage(new Product(), "123", new Bid());
+ Assert.AreEqual(result, 1);
+ }
+
+ [TestMethod]
+ public async Task SendNewVendorAccountApplyStoreOwnerNotificationRetunsCorrectResult()
+ {
+ var result = await _messageService.SendNewVendorAccountApplyStoreOwnerMessage(new Customer(), new Vendor(),
+ new Store { Url = "https://localhost:44350/" }, "123");
+ Assert.AreEqual(result, 1);
+ }
+
+ [TestMethod]
+ public async Task SendNotificationMethodToEmailIsNull()
{
- private Mock<IMessageTemplateService> _messageTemplateServiceMock;
- private Mock<IQueuedEmailService> _queuedEmailServiceMock;
- private Mock<IGroupService> _groupService;
- private Mock<ILanguageService> _languageServiceMock;
- private Mock<IEmailAccountService> _emailAccountServiceMock;
- private Mock<IMessageTokenProvider> _messageTokenProviderMock;
- private Mock<IStoreService> _storeServiceMock;
- private Mock<IStoreHelper> _storeHelperServiceMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<EmailAccountSettings> _emailAccountSettingsMock;
- private Mock<CommonSettings> _commonSetting;
- private MessageProviderService _messageService;
- private Product _product;
-
- [TestInitialize()]
- public void Init()
- {
- _messageTemplateServiceMock = new Mock<IMessageTemplateService>();
- _messageTemplateServiceMock.Setup(x => x.GetMessageTemplateByName(It.IsAny<string>(), It.IsAny<string>()))
- .Returns(Task.FromResult(new MessageTemplate { IsActive = true }));
-
- _queuedEmailServiceMock = new Mock<IQueuedEmailService>();
- _groupService = new Mock<IGroupService>();
- _languageServiceMock = new Mock<ILanguageService>();
- _languageServiceMock.Setup(x => x.GetLanguageById(It.IsAny<string>())).Returns(Task.FromResult(new Language()));
- _languageServiceMock.Setup(x => x.GetAllLanguages(It.IsAny<bool>(), It.IsAny<string>())).Returns(Task.FromResult(
- new List<Language> { new Language { Name = "English" }, new Language { Name = "Polish" } } as IList<Language>));
-
- _emailAccountServiceMock = new Mock<IEmailAccountService>();
- _emailAccountServiceMock.Setup(x => x.GetAllEmailAccounts())
- .Returns(Task.FromResult(new List<EmailAccount> { new EmailAccount { Email = "[email protected]" } } as IList<EmailAccount>));
-
- _messageTokenProviderMock = new Mock<IMessageTokenProvider>();
-
- _storeServiceMock = new Mock<IStoreService>();
- _storeServiceMock.Setup(x => x.GetStoreById(It.IsAny<string>())).Returns(Task.FromResult(new Store { Url = "https://localhost:44350/" }));
- _storeServiceMock.Setup(x => x.GetAllStores()).Returns(Task.FromResult(new List<Store>() as IList<Store>));
-
- _storeHelperServiceMock = new Mock<IStoreHelper>();
-
- _mediatorMock = new Mock<IMediator>();
- _mediatorMock.Setup(x => x.Send(It.IsAny<GetCustomerByIdQuery>(), default))
- .Returns(Task.FromResult(new Customer { Email = "[email protected]" }));
-
- _emailAccountSettingsMock = new Mock<EmailAccountSettings>();
- _commonSetting = new Mock<CommonSettings>();
-
- _messageService = new MessageProviderService(
- _messageTemplateServiceMock.Object,
- _queuedEmailServiceMock.Object,
- _languageServiceMock.Object,
- _emailAccountServiceMock.Object,
- _storeServiceMock.Object,
- _storeHelperServiceMock.Object,
- _groupService.Object,
- _mediatorMock.Object,
- _emailAccountSettingsMock.Object,
- _commonSetting.Object);
- _product = new Product();
-
- }
-
- [TestMethod()]
- public async Task CallInsertQueuedEmailMethod()
- {
- var result = await _messageService.SendOutBidCustomerMessage(new Product(), "123", new Bid());
- _queuedEmailServiceMock.Verify(x => x.InsertQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once());
- }
-
- [TestMethod()]
- public async Task SendOutBidCustomerNotificationMethodReturnCorrectResult()
- {
- var result = await _messageService.SendOutBidCustomerMessage(new Product(), "123", new Bid());
- Assert.AreEqual(result, 1);
- }
-
- [TestMethod()]
- public async Task SendNewVendorAccountApplyStoreOwnerNotificationRetunsCorrectResult()
- {
- var result = await _messageService.SendNewVendorAccountApplyStoreOwnerMessage(new Customer(), new Vendor(), new Store { Url = "https://localhost:44350/" }, "123");
- Assert.AreEqual(result, 1);
- }
-
- [TestMethod()]
- public async Task SendNotificationMethodToEmailIsNull()
- {
- var result = await _messageService.SendNotification(messageTemplate: new MessageTemplate(),
- emailAccount: new EmailAccount(),
- languageId: "123",
- liquidObject: new LiquidObject(),
- toName: "The God",
- toEmailAddress: null);
-
- Assert.AreEqual(result, 0);
- }
+ var result = await _messageService.SendNotification(new MessageTemplate(),
+ new EmailAccount(),
+ "123",
+ new LiquidObject(),
+ toName: "The God",
+ toEmailAddress: null);
+
+ Assert.AreEqual(result, 0);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/MessageTemplateServiceTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/MessageTemplateServiceTests.cs
index 65cd7bc5f..fe59e61b8 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/MessageTemplateServiceTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/MessageTemplateServiceTests.cs
@@ -1,7 +1,7 @@
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Messages.Services;
-using Grand.Domain.Catalog;
using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Messages;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
@@ -10,76 +10,76 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Messages.Tests.Services
+namespace Grand.Business.Messages.Tests.Services;
+
+[TestClass]
+public class MessageTemplateServiceTests
{
- [TestClass]
- public class MessageTemplateServiceTests
- {
- private Mock<ICacheBase> _cacheMock;
- private Mock<IAclService> _aclService;
- private Mock<IRepository<MessageTemplate>> _repositoryMock;
- private Mock<IMediator> _mediatorMock;
- private CatalogSettings _settings;
- private MessageTemplateService _service;
+ private Mock<IAclService> _aclService;
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<MessageTemplate>> _repositoryMock;
+ private MessageTemplateService _service;
+ private CatalogSettings _settings;
- [TestInitialize]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _aclService = new Mock<IAclService>();
- _repositoryMock = new Mock<IRepository<MessageTemplate>>();
- _mediatorMock = new Mock<IMediator>();
- _settings = new CatalogSettings();
- var accessControlConfig = new AccessControlConfig();
- _service = new MessageTemplateService(_cacheMock.Object, _aclService.Object, _repositoryMock.Object, _mediatorMock.Object, accessControlConfig);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _aclService = new Mock<IAclService>();
+ _repositoryMock = new Mock<IRepository<MessageTemplate>>();
+ _mediatorMock = new Mock<IMediator>();
+ _settings = new CatalogSettings();
+ var accessControlConfig = new AccessControlConfig();
+ _service = new MessageTemplateService(_cacheMock.Object, _aclService.Object, _repositoryMock.Object,
+ _mediatorMock.Object, accessControlConfig);
+ }
- [TestMethod]
- public void CopyMessageTemplate_NullArrguemnt_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.CopyMessageTemplate(null));
- }
+ [TestMethod]
+ public void CopyMessageTemplate_NullArrguemnt_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.CopyMessageTemplate(null));
+ }
- [TestMethod]
- public async Task CopyMessageTemplate_InsertCopyEntity()
- {
- var template = new MessageTemplate {
- Id = "id1",
- Name = "Name"
- };
+ [TestMethod]
+ public async Task CopyMessageTemplate_InsertCopyEntity()
+ {
+ var template = new MessageTemplate {
+ Id = "id1",
+ Name = "Name"
+ };
- var result = await _service.CopyMessageTemplate(template);
- Assert.AreEqual(template.Name, result.Name);
- Assert.AreNotEqual(template.Id, result.Id);
- //should be insert into db
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<MessageTemplate>()), Times.Once);
- }
+ var result = await _service.CopyMessageTemplate(template);
+ Assert.AreEqual(template.Name, result.Name);
+ Assert.AreNotEqual(template.Id, result.Id);
+ //should be insert into db
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<MessageTemplate>()), Times.Once);
+ }
- [TestMethod]
- public async Task InsertMessageTemplate_InvokeExpectedMethods()
- {
- await _service.InsertMessageTemplate(new MessageTemplate());
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<MessageTemplate>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MessageTemplate>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertMessageTemplate_InvokeExpectedMethods()
+ {
+ await _service.InsertMessageTemplate(new MessageTemplate());
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<MessageTemplate>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<MessageTemplate>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public async Task UpdateMessageTemplate_InvokeExpectedMethods()
- {
- await _service.UpdateMessageTemplate(new MessageTemplate());
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MessageTemplate>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MessageTemplate>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateMessageTemplate_InvokeExpectedMethods()
+ {
+ await _service.UpdateMessageTemplate(new MessageTemplate());
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<MessageTemplate>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<MessageTemplate>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
+ }
- [TestMethod]
- public async Task DeleteMessageTemplate_InvokeExpectedMethods()
- {
- await _service.DeleteMessageTemplate(new MessageTemplate());
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MessageTemplate>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MessageTemplate>>(), default), Times.Once);
- _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteMessageTemplate_InvokeExpectedMethods()
+ {
+ await _service.DeleteMessageTemplate(new MessageTemplate());
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<MessageTemplate>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<MessageTemplate>>(), default), Times.Once);
+ _cacheMock.Verify(c => c.RemoveByPrefix(It.IsAny<string>(), It.IsAny<bool>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/MessageTokenProviderTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/MessageTokenProviderTests.cs
index 94b57e3f8..862884cc2 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/MessageTokenProviderTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/MessageTokenProviderTests.cs
@@ -1,30 +1,30 @@
using Grand.Business.Messages.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Messages.Tests.Services
+namespace Grand.Business.Messages.Tests.Services;
+
+[TestClass]
+public class MessageTokenProviderTests
{
- [TestClass()]
- public class MessageTokenProviderTests
+ private MessageTokenProvider _provider;
+
+ [TestInitialize]
+ public void Init()
{
- private MessageTokenProvider _provider;
+ _provider = new MessageTokenProvider();
+ }
- [TestInitialize()]
- public void Init()
- {
- _provider = new MessageTokenProvider();
- }
+ [TestMethod]
+ public void GetListOfAllowedTokensTest()
+ {
+ var tokens = _provider.GetListOfAllowedTokens();
+ Assert.IsTrue(tokens.Any());
+ }
- [TestMethod()]
- public void GetListOfAllowedTokensTest()
- {
- var tokens = _provider.GetListOfAllowedTokens();
- Assert.IsTrue(tokens.Any());
- }
- [TestMethod()]
- public void GetListOfCampaignAllowedTokensTest()
- {
- var tokens = _provider.GetListOfCampaignAllowedTokens();
- Assert.IsTrue(tokens.Any());
- }
+ [TestMethod]
+ public void GetListOfCampaignAllowedTokensTest()
+ {
+ var tokens = _provider.GetListOfCampaignAllowedTokens();
+ Assert.IsTrue(tokens.Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/MimeMappingServiceTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/MimeMappingServiceTests.cs
index 2c0c45204..74da21b3a 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/MimeMappingServiceTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/MimeMappingServiceTests.cs
@@ -1,30 +1,29 @@
using Grand.Business.Messages.Services;
+using Microsoft.AspNetCore.StaticFiles;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Messages.Tests.Services
-{
- [TestClass]
- public class MimeMappingServiceTests
- {
- private MimeMappingService _service;
+namespace Grand.Business.Messages.Tests.Services;
- [TestInitialize]
- public void Init()
- {
- _service = new MimeMappingService(new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider());
- }
+[TestClass]
+public class MimeMappingServiceTests
+{
+ private MimeMappingService _service;
- [TestMethod]
- public void Map_ReturnExpectedValue()
- {
+ [TestInitialize]
+ public void Init()
+ {
+ _service = new MimeMappingService(new FileExtensionContentTypeProvider());
+ }
- Assert.AreEqual("text/plain", _service.Map("file.txt"));
- Assert.AreEqual("video/x-msvideo", _service.Map("file.avi"));
- Assert.AreEqual("application/vnd.microsoft.portable-executable", _service.Map("file.exe"));
- Assert.AreEqual("image/jpeg", _service.Map("file.jpg"));
- Assert.AreEqual("image/gif", _service.Map("file.gif"));
- Assert.AreEqual("image/png", _service.Map("file.png"));
- Assert.AreEqual("application/octet-stream", _service.Map("file.wirdtype"));
- }
+ [TestMethod]
+ public void Map_ReturnExpectedValue()
+ {
+ Assert.AreEqual("text/plain", _service.Map("file.txt"));
+ Assert.AreEqual("video/x-msvideo", _service.Map("file.avi"));
+ Assert.AreEqual("application/vnd.microsoft.portable-executable", _service.Map("file.exe"));
+ Assert.AreEqual("image/jpeg", _service.Map("file.jpg"));
+ Assert.AreEqual("image/gif", _service.Map("file.gif"));
+ Assert.AreEqual("image/png", _service.Map("file.png"));
+ Assert.AreEqual("application/octet-stream", _service.Map("file.wirdtype"));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/QueuedEmailServiceTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/QueuedEmailServiceTests.cs
index 5e8923978..6588fc909 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Services/QueuedEmailServiceTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Services/QueuedEmailServiceTests.cs
@@ -6,82 +6,86 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Messages.Tests.Services
+namespace Grand.Business.Messages.Tests.Services;
+
+[TestClass]
+public class QueuedEmailServiceTests
{
- [TestClass]
- public class QueuedEmailServiceTests
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<QueuedEmail>> _repository;
+ private QueuedEmailService _service;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<IRepository<QueuedEmail>> _repository;
- private Mock<IMediator> _mediatorMock;
- private QueuedEmailService _service;
+ _repository = new Mock<IRepository<QueuedEmail>>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new QueuedEmailService(_repository.Object, _mediatorMock.Object);
+ }
- [TestInitialize]
- public void Init()
- {
- _repository = new Mock<IRepository<QueuedEmail>>();
- _mediatorMock = new Mock<IMediator>();
- _service = new QueuedEmailService(_repository.Object, _mediatorMock.Object);
- }
+ [TestMethod]
+ public async Task GetQueuedEmailByIdTest()
+ {
+ await _service.GetQueuedEmailById("1");
+ _repository.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
- [TestMethod()]
- public async Task GetQueuedEmailByIdTest()
- {
- await _service.GetQueuedEmailById("1");
- _repository.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ [TestMethod]
+ public async Task InsertQueuedEmail_ValidArgument_InvokeExpectedMethods()
+ {
+ await _service.InsertQueuedEmail(new QueuedEmail());
+ _repository.Verify(c => c.InsertAsync(It.IsAny<QueuedEmail>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<QueuedEmail>>(), default), Times.Once);
+ }
- }
- [TestMethod()]
- public async Task InsertQueuedEmail_ValidArgument_InvokeExpectedMethods()
- {
- await _service.InsertQueuedEmail(new QueuedEmail());
- _repository.Verify(c => c.InsertAsync(It.IsAny<QueuedEmail>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<QueuedEmail>>(), default), Times.Once);
- }
+ [TestMethod]
+ public void InsertQueuedEmail_NullArguemnt_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
+ await _service.InsertQueuedEmail(new QueuedEmail()));
+ }
- [TestMethod]
- public void InsertQueuedEmail_NullArguemnt_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertQueuedEmail(new QueuedEmail()));
- }
+ [TestMethod]
+ public async Task UpdateQueuedEmail_ValidArgument_InvokeExpectedMethods()
+ {
+ await _service.UpdateQueuedEmail(new QueuedEmail());
+ _repository.Verify(c => c.UpdateAsync(It.IsAny<QueuedEmail>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<QueuedEmail>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task UpdateQueuedEmail_ValidArgument_InvokeExpectedMethods()
- {
- await _service.UpdateQueuedEmail(new QueuedEmail());
- _repository.Verify(c => c.UpdateAsync(It.IsAny<QueuedEmail>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<QueuedEmail>>(), default), Times.Once);
- }
+ [TestMethod]
+ public void UpdateQueuedEmai_NullArguemnt_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
+ await _service.UpdateQueuedEmail(new QueuedEmail()));
+ }
+
+ [TestMethod]
+ public async Task DeleteQueuedEmail_ValidArgument_InvokeExpectedMethods()
+ {
+ await _service.DeleteQueuedEmail(new QueuedEmail());
+ _repository.Verify(c => c.DeleteAsync(It.IsAny<QueuedEmail>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<QueuedEmail>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateQueuedEmai_NullArguemnt_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateQueuedEmail(new QueuedEmail()));
- }
+ [TestMethod]
+ public async Task DeleteCustomerEmail_ValidArgument_InvokeExpectedMethods()
+ {
+ await _service.DeleteCustomerEmail("[email protected]");
+ _repository.Verify(c => c.DeleteAsync(It.IsAny<IEnumerable<QueuedEmail>>()), Times.Once);
+ }
- [TestMethod()]
- public async Task DeleteQueuedEmail_ValidArgument_InvokeExpectedMethods()
- {
+ [TestMethod]
+ public async Task DeleteAllEmails_ValidArgument_InvokeExpectedMethods()
+ {
+ await _service.DeleteAllEmails();
+ _repository.Verify(c => c.ClearAsync(), Times.Once);
+ }
- await _service.DeleteQueuedEmail(new QueuedEmail());
- _repository.Verify(c => c.DeleteAsync(It.IsAny<QueuedEmail>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<QueuedEmail>>(), default), Times.Once);
- }
- [TestMethod()]
- public async Task DeleteCustomerEmail_ValidArgument_InvokeExpectedMethods()
- {
- await _service.DeleteCustomerEmail("[email protected]");
- _repository.Verify(c => c.DeleteAsync(It.IsAny<IEnumerable<QueuedEmail>>()), Times.Once);
- }
- [TestMethod()]
- public async Task DeleteAllEmails_ValidArgument_InvokeExpectedMethods()
- {
- await _service.DeleteAllEmails();
- _repository.Verify(c => c.ClearAsync(), Times.Once);
- }
- [TestMethod]
- public void DeleteQueuedEmai_NullArguemnt_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteQueuedEmail(new QueuedEmail()));
- }
+ [TestMethod]
+ public void DeleteQueuedEmai_NullArguemnt_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () =>
+ await _service.DeleteQueuedEmail(new QueuedEmail()));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Messages.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Messages.Tests/Startup/StartupApplicationTests.cs
index 8362a44b1..377e69e72 100644
--- a/src/Tests/Grand.Business.Messages.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Messages.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Messages.Tests.Startup
+namespace Grand.Business.Messages.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Storage.Tests/Extensions/ExtensionsTests.cs b/src/Tests/Grand.Business.Storage.Tests/Extensions/ExtensionsTests.cs
index ed237e641..b15b36369 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Extensions/ExtensionsTests.cs
+++ b/src/Tests/Grand.Business.Storage.Tests/Extensions/ExtensionsTests.cs
@@ -3,24 +3,23 @@ using Microsoft.AspNetCore.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Storage.Tests.Extensions
+namespace Grand.Business.Storage.Tests.Extensions;
+
+[TestClass]
+public class ExtensionsTests
{
- [TestClass]
- public class ExtensionsTests
+ [TestMethod]
+ public void GetDownloadBits_ReturnExpectedValue()
{
- [TestMethod]
- public void GetDownloadBits_ReturnExpectedValue()
+ var file = new Mock<IFormFile>();
+ MemoryStream test_Stream = null;
+ byte[] expected = null;
+ using (test_Stream = new MemoryStream(Encoding.UTF8.GetBytes("whatever")))
{
- var file = new Mock<IFormFile>();
- MemoryStream test_Stream = null;
- byte[] expected = null;
- using (test_Stream = new MemoryStream(Encoding.UTF8.GetBytes("whatever")))
- {
- expected = test_Stream.ToArray();
- file.Setup(c => c.OpenReadStream()).Returns(test_Stream);
- var result = file.Object.GetDownloadBits();
- Assert.IsTrue(result.SequenceEqual(expected));
- }
+ expected = test_Stream.ToArray();
+ file.Setup(c => c.OpenReadStream()).Returns(test_Stream);
+ var result = file.Object.GetDownloadBits();
+ Assert.IsTrue(result.SequenceEqual(expected));
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/DefaultMediaFileStoreTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/DefaultMediaFileStoreTests.cs
index 43f1273da..955899aa4 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Services/DefaultMediaFileStoreTests.cs
+++ b/src/Tests/Grand.Business.Storage.Tests/Services/DefaultMediaFileStoreTests.cs
@@ -1,210 +1,212 @@
using Grand.Business.Storage.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using TestContext = NUnit.Framework.TestContext;
-namespace Grand.Business.Storage.Tests.Services
+namespace Grand.Business.Storage.Tests.Services;
+
+[TestClass]
+public class DefaultMediaFileStoreTests
{
- [TestClass()]
- public class DefaultMediaFileStoreTests
- {
- private DefaultMediaFileStore _defaultMediaFileStore;
- private string myFile = "sample.txt";
-
- [TestInitialize]
- public void Init()
- {
- _defaultMediaFileStore =
- new DefaultMediaFileStore(
- new FileSystemStore(NUnit.Framework.TestContext.CurrentContext.TestDirectory));
- }
-
- [TestMethod()]
- public async Task GetFileInfoTest()
- {
- //Act
- var result = await _defaultMediaFileStore.GetFileInfo(myFile);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(result.Name, myFile);
- }
-
- [TestMethod()]
- public void GetDirectoryInfoTest()
- {
- //Act
- var result = _defaultMediaFileStore.GetDirectoryInfo("Upload");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(result.Name, "Upload");
- }
-
- [TestMethod()]
- public async Task GetPhysicalDirectoryInfoTest()
- {
- //Act
- var result = await _defaultMediaFileStore.GetPhysicalDirectoryInfo("Upload");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(result.Name, "Upload");
- Assert.IsTrue(result.IsDirectory);
- }
-
- [TestMethod()]
- public void GetDirectoryContentTest()
- {
- //Act
- var result = _defaultMediaFileStore.GetDirectoryContent("Upload");
- //Assert
- Assert.AreEqual(1, result.Count);
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public void TryCreateDirectoryTest()
- {
- //Act
- var result = _defaultMediaFileStore.TryCreateDirectory("Test");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- [Ignore] //TMP
- public async Task TryRenameDirectoryTest()
- {
- //Arrange
- _defaultMediaFileStore.TryCreateDirectory("Test");
- await _defaultMediaFileStore.TryDeleteDirectory("Test2");
- //Act
- var result = await _defaultMediaFileStore.TryRenameDirectory("Test", "Test2");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task TryDeleteFileTest()
- {
- //Arrange
- await _defaultMediaFileStore.WriteAllText("file078.txt", "test");
- //Act
- var result = await _defaultMediaFileStore.TryDeleteFile("file078.txt");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task TryDeleteDirectoryTest()
- {
- //Arrange
- _defaultMediaFileStore.TryCreateDirectory("Test");
-
- //Act
- var result = await _defaultMediaFileStore.TryDeleteDirectory("Test");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task MoveFileTest()
- {
- //Arrange
- await _defaultMediaFileStore.WriteAllText("file1998.txt", "test");
- await _defaultMediaFileStore.TryDeleteFile("file2197.txt");
-
- //Act
- await _defaultMediaFileStore.MoveFile("file1998.txt", "file2197.txt");
- var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo("file2197.txt");
-
- //Assert
- Assert.IsNotNull(fileStoreEntry);
- Assert.AreEqual("file2197.txt", fileStoreEntry.Name);
- }
-
- [TestMethod()]
- public async Task CopyFileTest()
- {
- //Arrange
- await _defaultMediaFileStore.WriteAllText("file178.txt", "test");
- await _defaultMediaFileStore.TryDeleteFile("file297.txt");
- //Act
- await _defaultMediaFileStore.CopyFile("file178.txt", "file297.txt");
- var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo("file297.txt");
-
- //Assert
- Assert.IsNotNull(fileStoreEntry);
- Assert.AreEqual("file297.txt", fileStoreEntry.Name);
- }
-
- [TestMethod()]
- public async Task RenameFileTest()
- {
- //Arrange
- await _defaultMediaFileStore.WriteAllText("file678.txt", "test");
- await _defaultMediaFileStore.TryDeleteFile("file897.txt");
- //Act
- await _defaultMediaFileStore.RenameFile("file678.txt", "file897.txt");
- var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo("file897.txt");
-
- //Assert
- Assert.IsNotNull(fileStoreEntry);
- Assert.AreEqual("file897.txt", fileStoreEntry.Name);
- }
-
- [TestMethod()]
- public async Task GetFileStreamTest()
- {
- //Arrange
- var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo(myFile);
- //Act
- var stream = await _defaultMediaFileStore.GetFileStream(fileStoreEntry);
- //Assert
- stream.Position = 0;
- using StreamReader reader = new StreamReader(stream, Encoding.UTF8);
- var text = reader.ReadToEnd();
- Assert.AreEqual("test", text);
- }
-
- [TestMethod()]
- public async Task GetFileStreamTest1()
- {
- //Arrange
- var result = await _defaultMediaFileStore.CreateFileFromStream("file456.txt", new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
- //Act
- var stream = await _defaultMediaFileStore.GetFileStream("file456.txt");
- //Assert
- stream.Position = 0;
- using StreamReader reader = new StreamReader(stream, Encoding.UTF8);
- var text = reader.ReadToEnd();
- Assert.AreEqual("test", text);
- }
-
- [TestMethod()]
- public async Task CreateFileFromStreamTest()
- {
- //Act
- var result = await _defaultMediaFileStore.CreateFileFromStream("file456.txt", new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
- //Assert
- Assert.AreEqual("file456.txt", result);
- }
-
- [TestMethod()]
- public async Task ReadAllTextTest()
- {
- await _defaultMediaFileStore.WriteAllText("file123.txt", "test");
- //Act
- var result = await _defaultMediaFileStore.ReadAllText("file123.txt");
- //Assert
- Assert.AreEqual("test", result);
- }
-
- [TestMethod()]
- public async Task WriteAllTextTest()
- {
- //Act
- await _defaultMediaFileStore.WriteAllText("file111.txt", "test");
-
- //Assert
- var result = await _defaultMediaFileStore.ReadAllText("file111.txt");
- Assert.AreEqual("test", result);
- }
+ private readonly string myFile = "sample.txt";
+ private DefaultMediaFileStore _defaultMediaFileStore;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _defaultMediaFileStore =
+ new DefaultMediaFileStore(
+ new FileSystemStore(TestContext.CurrentContext.TestDirectory));
+ }
+
+ [TestMethod]
+ public async Task GetFileInfoTest()
+ {
+ //Act
+ var result = await _defaultMediaFileStore.GetFileInfo(myFile);
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.Name, myFile);
+ }
+
+ [TestMethod]
+ public void GetDirectoryInfoTest()
+ {
+ //Act
+ var result = _defaultMediaFileStore.GetDirectoryInfo("Upload");
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.Name, "Upload");
+ }
+
+ [TestMethod]
+ public async Task GetPhysicalDirectoryInfoTest()
+ {
+ //Act
+ var result = await _defaultMediaFileStore.GetPhysicalDirectoryInfo("Upload");
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.Name, "Upload");
+ Assert.IsTrue(result.IsDirectory);
+ }
+
+ [TestMethod]
+ public void GetDirectoryContentTest()
+ {
+ //Act
+ var result = _defaultMediaFileStore.GetDirectoryContent("Upload");
+ //Assert
+ Assert.AreEqual(1, result.Count);
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public void TryCreateDirectoryTest()
+ {
+ //Act
+ var result = _defaultMediaFileStore.TryCreateDirectory("Test");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ [Ignore] //TMP
+ public async Task TryRenameDirectoryTest()
+ {
+ //Arrange
+ _defaultMediaFileStore.TryCreateDirectory("Test");
+ await _defaultMediaFileStore.TryDeleteDirectory("Test2");
+ //Act
+ var result = await _defaultMediaFileStore.TryRenameDirectory("Test", "Test2");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task TryDeleteFileTest()
+ {
+ //Arrange
+ await _defaultMediaFileStore.WriteAllText("file078.txt", "test");
+ //Act
+ var result = await _defaultMediaFileStore.TryDeleteFile("file078.txt");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task TryDeleteDirectoryTest()
+ {
+ //Arrange
+ _defaultMediaFileStore.TryCreateDirectory("Test");
+
+ //Act
+ var result = await _defaultMediaFileStore.TryDeleteDirectory("Test");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task MoveFileTest()
+ {
+ //Arrange
+ await _defaultMediaFileStore.WriteAllText("file1998.txt", "test");
+ await _defaultMediaFileStore.TryDeleteFile("file2197.txt");
+
+ //Act
+ await _defaultMediaFileStore.MoveFile("file1998.txt", "file2197.txt");
+ var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo("file2197.txt");
+
+ //Assert
+ Assert.IsNotNull(fileStoreEntry);
+ Assert.AreEqual("file2197.txt", fileStoreEntry.Name);
+ }
+
+ [TestMethod]
+ public async Task CopyFileTest()
+ {
+ //Arrange
+ await _defaultMediaFileStore.WriteAllText("file178.txt", "test");
+ await _defaultMediaFileStore.TryDeleteFile("file297.txt");
+ //Act
+ await _defaultMediaFileStore.CopyFile("file178.txt", "file297.txt");
+ var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo("file297.txt");
+
+ //Assert
+ Assert.IsNotNull(fileStoreEntry);
+ Assert.AreEqual("file297.txt", fileStoreEntry.Name);
+ }
+
+ [TestMethod]
+ public async Task RenameFileTest()
+ {
+ //Arrange
+ await _defaultMediaFileStore.WriteAllText("file678.txt", "test");
+ await _defaultMediaFileStore.TryDeleteFile("file897.txt");
+ //Act
+ await _defaultMediaFileStore.RenameFile("file678.txt", "file897.txt");
+ var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo("file897.txt");
+
+ //Assert
+ Assert.IsNotNull(fileStoreEntry);
+ Assert.AreEqual("file897.txt", fileStoreEntry.Name);
+ }
+
+ [TestMethod]
+ public async Task GetFileStreamTest()
+ {
+ //Arrange
+ var fileStoreEntry = await _defaultMediaFileStore.GetFileInfo(myFile);
+ //Act
+ var stream = await _defaultMediaFileStore.GetFileStream(fileStoreEntry);
+ //Assert
+ stream.Position = 0;
+ using var reader = new StreamReader(stream, Encoding.UTF8);
+ var text = reader.ReadToEnd();
+ Assert.AreEqual("test", text);
+ }
+
+ [TestMethod]
+ public async Task GetFileStreamTest1()
+ {
+ //Arrange
+ var result = await _defaultMediaFileStore.CreateFileFromStream("file456.txt",
+ new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
+ //Act
+ var stream = await _defaultMediaFileStore.GetFileStream("file456.txt");
+ //Assert
+ stream.Position = 0;
+ using var reader = new StreamReader(stream, Encoding.UTF8);
+ var text = reader.ReadToEnd();
+ Assert.AreEqual("test", text);
+ }
+
+ [TestMethod]
+ public async Task CreateFileFromStreamTest()
+ {
+ //Act
+ var result = await _defaultMediaFileStore.CreateFileFromStream("file456.txt",
+ new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
+ //Assert
+ Assert.AreEqual("file456.txt", result);
+ }
+
+ [TestMethod]
+ public async Task ReadAllTextTest()
+ {
+ await _defaultMediaFileStore.WriteAllText("file123.txt", "test");
+ //Act
+ var result = await _defaultMediaFileStore.ReadAllText("file123.txt");
+ //Assert
+ Assert.AreEqual("test", result);
+ }
+
+ [TestMethod]
+ public async Task WriteAllTextTest()
+ {
+ //Act
+ await _defaultMediaFileStore.WriteAllText("file111.txt", "test");
+
+ //Assert
+ var result = await _defaultMediaFileStore.ReadAllText("file111.txt");
+ Assert.AreEqual("test", result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/DownloadServiceTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/DownloadServiceTests.cs
index 170c52539..b4af9e8ff 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Services/DownloadServiceTests.cs
+++ b/src/Tests/Grand.Business.Storage.Tests/Services/DownloadServiceTests.cs
@@ -6,74 +6,74 @@ using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Storage.Tests.Services
+namespace Grand.Business.Storage.Tests.Services;
+
+[TestClass]
+public class DownloadServiceTests
{
- [TestClass]
- public class DownloadServiceTests
- {
- private Mock<IMediator> _mediatorMock;
- private Mock<IRepository<Download>> _repositoryMock;
- private Mock<IStoreFilesContext> _storeFilesContext;
- private DownloadService _service;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Download>> _repositoryMock;
+ private DownloadService _service;
+ private Mock<IStoreFilesContext> _storeFilesContext;
- [TestInitialize]
- public void Init()
- {
- _mediatorMock = new Mock<IMediator>();
- _repositoryMock = new Mock<IRepository<Download>>();
- _storeFilesContext = new Mock<IStoreFilesContext>();
- _service = new DownloadService(_repositoryMock.Object, _storeFilesContext.Object, _mediatorMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _mediatorMock = new Mock<IMediator>();
+ _repositoryMock = new Mock<IRepository<Download>>();
+ _storeFilesContext = new Mock<IStoreFilesContext>();
+ _service = new DownloadService(_repositoryMock.Object, _storeFilesContext.Object, _mediatorMock.Object);
+ }
- [TestMethod]
- public async Task GetDownloadById_InvokeExpectedMethod()
- {
- _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new Download { DownloadUrl = "url", UseDownloadUrl = true }));
- var result = await _service.GetDownloadById("id");
- _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- Assert.AreEqual(result.DownloadUrl, "url");
- }
+ [TestMethod]
+ public async Task GetDownloadById_InvokeExpectedMethod()
+ {
+ _repositoryMock.Setup(c => c.GetByIdAsync(It.IsAny<string>()))
+ .Returns(Task.FromResult(new Download { DownloadUrl = "url", UseDownloadUrl = true }));
+ var result = await _service.GetDownloadById("id");
+ _repositoryMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ Assert.AreEqual(result.DownloadUrl, "url");
+ }
- [TestMethod]
- public async Task InsertDownload_InvokeExpectedMethod()
- {
- await _service.InsertDownload(new Download { UseDownloadUrl = true });
- _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Download>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Download>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertDownload_InvokeExpectedMethod()
+ {
+ await _service.InsertDownload(new Download { UseDownloadUrl = true });
+ _repositoryMock.Verify(c => c.InsertAsync(It.IsAny<Download>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Download>>(), default), Times.Once);
+ }
- [TestMethod]
- public void InsertDownload_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertDownload(null));
- }
+ [TestMethod]
+ public void InsertDownload_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.InsertDownload(null));
+ }
- [TestMethod]
- public async Task UpdateDownload_InvokeExpectedMethod()
- {
- await _service.UpdateDownload(new Download { UseDownloadUrl = true });
- _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Download>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Download>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task UpdateDownload_InvokeExpectedMethod()
+ {
+ await _service.UpdateDownload(new Download { UseDownloadUrl = true });
+ _repositoryMock.Verify(c => c.UpdateAsync(It.IsAny<Download>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Download>>(), default), Times.Once);
+ }
- [TestMethod]
- public void UpdateDownload_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateDownload(null));
- }
+ [TestMethod]
+ public void UpdateDownload_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.UpdateDownload(null));
+ }
- [TestMethod]
- public async Task DeleteDownload_InvokeExpectedMethod()
- {
- await _service.DeleteDownload(new Download { UseDownloadUrl = true });
- _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Download>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Download>>(), default), Times.Once);
- }
+ [TestMethod]
+ public async Task DeleteDownload_InvokeExpectedMethod()
+ {
+ await _service.DeleteDownload(new Download { UseDownloadUrl = true });
+ _repositoryMock.Verify(c => c.DeleteAsync(It.IsAny<Download>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Download>>(), default), Times.Once);
+ }
- [TestMethod]
- public void DeleteDownload_NullArgument_ThrowException()
- {
- Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteDownload(null));
- }
+ [TestMethod]
+ public void DeleteDownload_NullArgument_ThrowException()
+ {
+ Assert.ThrowsExceptionAsync<ArgumentNullException>(async () => await _service.DeleteDownload(null));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/FileSystemStoreTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/FileSystemStoreTests.cs
index 3c69c399e..f46121fb7 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Services/FileSystemStoreTests.cs
+++ b/src/Tests/Grand.Business.Storage.Tests/Services/FileSystemStoreTests.cs
@@ -1,210 +1,212 @@
using Grand.Business.Storage.Services;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using TestContext = NUnit.Framework.TestContext;
-namespace Grand.Business.Storage.Tests.Services
+namespace Grand.Business.Storage.Tests.Services;
+
+[TestClass]
+public class FileSystemStoreTests
{
- [TestClass()]
- public class FileSystemStoreTests
- {
- private FileSystemStore _store;
- private string myFile = "sample.txt";
-
- [TestInitialize]
- public void Init()
- {
- _store = new FileSystemStore(NUnit.Framework.TestContext.CurrentContext.TestDirectory);
- }
-
-
- [TestMethod()]
- public async Task GetFileInfoTest()
- {
- //Act
- var result = await _store.GetFileInfo(myFile);
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(result.Name, myFile);
- }
-
- [TestMethod()]
- public void GetDirectoryInfoTest()
- {
- //Act
- var result = _store.GetDirectoryInfo("Upload");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(result.Name, "Upload");
- }
-
- [TestMethod()]
- public async Task GetPhysicalDirectoryInfoTest()
- {
- //Act
- var result = await _store.GetPhysicalDirectoryInfo("Upload");
- //Assert
- Assert.IsNotNull(result);
- Assert.AreEqual(result.Name, "Upload");
- Assert.IsTrue(result.IsDirectory);
- }
-
- [TestMethod()]
- public void GetDirectoryContentTest()
- {
- //Act
- var result = _store.GetDirectoryContent("Upload");
- //Assert
- Assert.AreEqual(1, result.Count);
- Assert.IsTrue(result.Any());
- }
-
- [TestMethod()]
- public void TryCreateDirectoryTest()
- {
- //Act
- var result = _store.TryCreateDirectory("Test");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- [Ignore] //TMP
- public async Task TryRenameDirectoryTest()
- {
- //Arrange
- _store.TryCreateDirectory("Test");
- await _store.TryDeleteDirectory("Test2");
- //Act
- var result = await _store.TryRenameDirectory("Test", "Test2");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task TryDeleteFileTest()
- {
- //Arrange
- await _store.WriteAllText("file078.txt", "test");
- //Act
- var result = await _store.TryDeleteFile("file078.txt");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task TryDeleteDirectoryTest()
- {
- //Arrange
- _store.TryCreateDirectory("Test");
-
- //Act
- var result = await _store.TryDeleteDirectory("Test");
- //Assert
- Assert.IsTrue(result);
- }
-
- [TestMethod()]
- public async Task MoveFileTest()
- {
- //Arrange
- await _store.WriteAllText("file1998.txt", "test");
- await _store.TryDeleteFile("file2197.txt");
-
- //Act
- await _store.MoveFile("file1998.txt", "file2197.txt");
- var fileStoreEntry = await _store.GetFileInfo("file2197.txt");
-
- //Assert
- Assert.IsNotNull(fileStoreEntry);
- Assert.AreEqual("file2197.txt", fileStoreEntry.Name);
- }
-
- [TestMethod()]
- public async Task CopyFileTest()
- {
- //Arrange
- await _store.WriteAllText("file178.txt", "test");
- await _store.TryDeleteFile("file297.txt");
- //Act
- await _store.CopyFile("file178.txt", "file297.txt");
- var fileStoreEntry = await _store.GetFileInfo("file297.txt");
-
- //Assert
- Assert.IsNotNull(fileStoreEntry);
- Assert.AreEqual("file297.txt", fileStoreEntry.Name);
- }
-
- [TestMethod()]
- public async Task RenameFileTest()
- {
- //Arrange
- await _store.WriteAllText("file678.txt", "test");
- await _store.TryDeleteFile("file897.txt");
- //Act
- await _store.RenameFile("file678.txt", "file897.txt");
- var fileStoreEntry = await _store.GetFileInfo("file897.txt");
-
- //Assert
- Assert.IsNotNull(fileStoreEntry);
- Assert.AreEqual("file897.txt", fileStoreEntry.Name);
- }
-
-
- [TestMethod()]
- public async Task GetFileStreamTest()
- {
- //Arrange
- var fileStoreEntry = await _store.GetFileInfo(myFile);
- //Act
- var stream = await _store.GetFileStream(fileStoreEntry);
- //Assert
- stream.Position = 0;
- using StreamReader reader = new StreamReader(stream, Encoding.UTF8);
- var text = reader.ReadToEnd();
- Assert.AreEqual("test", text);
- }
-
- [TestMethod()]
- public async Task GetFileStreamTest1()
- {
- //Arrange
- var result = await _store.CreateFileFromStream("file456.txt", new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
- //Act
- var stream = await _store.GetFileStream("file456.txt");
- //Assert
- stream.Position = 0;
- using StreamReader reader = new StreamReader(stream, Encoding.UTF8);
- var text = reader.ReadToEnd();
- Assert.AreEqual("test", text);
- }
-
- [TestMethod()]
- public async Task CreateFileFromStreamTest()
- {
- //Act
- var result = await _store.CreateFileFromStream("file456.txt", new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
- //Assert
- Assert.AreEqual("file456.txt", result);
- }
-
- [TestMethod()]
- public async Task ReadAllTextTest()
- {
- await _store.WriteAllText("file123.txt", "test");
- //Act
- var result = await _store.ReadAllText("file123.txt");
- //Assert
- Assert.AreEqual("test", result);
- }
-
- [TestMethod()]
- public async Task WriteAllTextTest()
- {
- //Act
- await _store.WriteAllText("file111.txt", "test");
-
- //Assert
- var result = await _store.ReadAllText("file111.txt");
- Assert.AreEqual("test", result);
- }
+ private readonly string myFile = "sample.txt";
+ private FileSystemStore _store;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _store = new FileSystemStore(TestContext.CurrentContext.TestDirectory);
+ }
+
+
+ [TestMethod]
+ public async Task GetFileInfoTest()
+ {
+ //Act
+ var result = await _store.GetFileInfo(myFile);
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.Name, myFile);
+ }
+
+ [TestMethod]
+ public void GetDirectoryInfoTest()
+ {
+ //Act
+ var result = _store.GetDirectoryInfo("Upload");
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.Name, "Upload");
+ }
+
+ [TestMethod]
+ public async Task GetPhysicalDirectoryInfoTest()
+ {
+ //Act
+ var result = await _store.GetPhysicalDirectoryInfo("Upload");
+ //Assert
+ Assert.IsNotNull(result);
+ Assert.AreEqual(result.Name, "Upload");
+ Assert.IsTrue(result.IsDirectory);
+ }
+
+ [TestMethod]
+ public void GetDirectoryContentTest()
+ {
+ //Act
+ var result = _store.GetDirectoryContent("Upload");
+ //Assert
+ Assert.AreEqual(1, result.Count);
+ Assert.IsTrue(result.Any());
+ }
+
+ [TestMethod]
+ public void TryCreateDirectoryTest()
+ {
+ //Act
+ var result = _store.TryCreateDirectory("Test");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ [Ignore] //TMP
+ public async Task TryRenameDirectoryTest()
+ {
+ //Arrange
+ _store.TryCreateDirectory("Test");
+ await _store.TryDeleteDirectory("Test2");
+ //Act
+ var result = await _store.TryRenameDirectory("Test", "Test2");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task TryDeleteFileTest()
+ {
+ //Arrange
+ await _store.WriteAllText("file078.txt", "test");
+ //Act
+ var result = await _store.TryDeleteFile("file078.txt");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task TryDeleteDirectoryTest()
+ {
+ //Arrange
+ _store.TryCreateDirectory("Test");
+
+ //Act
+ var result = await _store.TryDeleteDirectory("Test");
+ //Assert
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public async Task MoveFileTest()
+ {
+ //Arrange
+ await _store.WriteAllText("file1998.txt", "test");
+ await _store.TryDeleteFile("file2197.txt");
+
+ //Act
+ await _store.MoveFile("file1998.txt", "file2197.txt");
+ var fileStoreEntry = await _store.GetFileInfo("file2197.txt");
+
+ //Assert
+ Assert.IsNotNull(fileStoreEntry);
+ Assert.AreEqual("file2197.txt", fileStoreEntry.Name);
+ }
+
+ [TestMethod]
+ public async Task CopyFileTest()
+ {
+ //Arrange
+ await _store.WriteAllText("file178.txt", "test");
+ await _store.TryDeleteFile("file297.txt");
+ //Act
+ await _store.CopyFile("file178.txt", "file297.txt");
+ var fileStoreEntry = await _store.GetFileInfo("file297.txt");
+
+ //Assert
+ Assert.IsNotNull(fileStoreEntry);
+ Assert.AreEqual("file297.txt", fileStoreEntry.Name);
+ }
+
+ [TestMethod]
+ public async Task RenameFileTest()
+ {
+ //Arrange
+ await _store.WriteAllText("file678.txt", "test");
+ await _store.TryDeleteFile("file897.txt");
+ //Act
+ await _store.RenameFile("file678.txt", "file897.txt");
+ var fileStoreEntry = await _store.GetFileInfo("file897.txt");
+
+ //Assert
+ Assert.IsNotNull(fileStoreEntry);
+ Assert.AreEqual("file897.txt", fileStoreEntry.Name);
+ }
+
+
+ [TestMethod]
+ public async Task GetFileStreamTest()
+ {
+ //Arrange
+ var fileStoreEntry = await _store.GetFileInfo(myFile);
+ //Act
+ var stream = await _store.GetFileStream(fileStoreEntry);
+ //Assert
+ stream.Position = 0;
+ using var reader = new StreamReader(stream, Encoding.UTF8);
+ var text = reader.ReadToEnd();
+ Assert.AreEqual("test", text);
+ }
+
+ [TestMethod]
+ public async Task GetFileStreamTest1()
+ {
+ //Arrange
+ var result =
+ await _store.CreateFileFromStream("file456.txt", new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
+ //Act
+ var stream = await _store.GetFileStream("file456.txt");
+ //Assert
+ stream.Position = 0;
+ using var reader = new StreamReader(stream, Encoding.UTF8);
+ var text = reader.ReadToEnd();
+ Assert.AreEqual("test", text);
+ }
+
+ [TestMethod]
+ public async Task CreateFileFromStreamTest()
+ {
+ //Act
+ var result =
+ await _store.CreateFileFromStream("file456.txt", new MemoryStream(Encoding.UTF8.GetBytes("test")), true);
+ //Assert
+ Assert.AreEqual("file456.txt", result);
+ }
+
+ [TestMethod]
+ public async Task ReadAllTextTest()
+ {
+ await _store.WriteAllText("file123.txt", "test");
+ //Act
+ var result = await _store.ReadAllText("file123.txt");
+ //Assert
+ Assert.AreEqual("test", result);
+ }
+
+ [TestMethod]
+ public async Task WriteAllTextTest()
+ {
+ //Act
+ await _store.WriteAllText("file111.txt", "test");
+
+ //Assert
+ var result = await _store.ReadAllText("file111.txt");
+ Assert.AreEqual("test", result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs b/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs
index 1ba832ff4..92894d858 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs
+++ b/src/Tests/Grand.Business.Storage.Tests/Services/PictureServiceTests.cs
@@ -11,125 +11,132 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.Storage.Tests.Services
+namespace Grand.Business.Storage.Tests.Services;
+
+[TestClass]
+public class PictureServiceTests
{
- [TestClass]
- public class PictureServiceTests
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<ILogger<PictureService>> _logerMock;
+ private Mock<IMediaFileStore> _mediaFileStoreMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<Picture>> _repoMock;
+ private PictureService _service;
+
+ private MediaSettings _settings;
+ private StorageSettings _storagesettings;
+ private Mock<IWebHostEnvironment> _webHostMock;
+ private Mock<IWorkContext> _workContextMock;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<IRepository<Picture>> _repoMock;
- private Mock<ILogger<PictureService>> _logerMock;
- private Mock<IMediator> _mediatorMock;
- private Mock<IWebHostEnvironment> _webHostMock;
- private Mock<IWorkContext> _workContextMock;
- private Mock<ICacheBase> _cacheMock;
- private Mock<IMediaFileStore> _mediaFileStoreMock;
+ _webHostMock = new Mock<IWebHostEnvironment>();
+ _repoMock = new Mock<IRepository<Picture>>();
+ _logerMock = new Mock<ILogger<PictureService>>();
+ _mediatorMock = new Mock<IMediator>();
+ _workContextMock = new Mock<IWorkContext>();
+ _cacheMock = new Mock<ICacheBase>();
+ _mediaFileStoreMock = new Mock<IMediaFileStore>();
+ _settings = new MediaSettings();
+ _storagesettings = new StorageSettings();
+ _service = new PictureService(_repoMock.Object, _logerMock.Object, _mediatorMock.Object, _cacheMock.Object,
+ _mediaFileStoreMock.Object, _settings, _storagesettings);
+ }
- private MediaSettings _settings;
- private StorageSettings _storagesettings;
- private PictureService _service;
+ [TestMethod]
+ public async Task GetPictureById_InvokeExpectedMethods()
+ {
+ await _service.GetPictureById("1");
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Picture>>>()), Times.Once);
+ }
- [TestInitialize]
- public void Init()
- {
- _webHostMock = new Mock<IWebHostEnvironment>();
- _repoMock = new Mock<IRepository<Picture>>();
- _logerMock = new Mock<ILogger<PictureService>>();
- _mediatorMock = new Mock<IMediator>();
- _workContextMock = new Mock<IWorkContext>();
- _cacheMock = new Mock<ICacheBase>();
- _mediaFileStoreMock = new Mock<IMediaFileStore>();
- _settings = new MediaSettings();
- _storagesettings = new StorageSettings();
- _service = new PictureService(_repoMock.Object, _logerMock.Object, _mediatorMock.Object, _cacheMock.Object, _mediaFileStoreMock.Object, _settings, _storagesettings);
- }
- [TestMethod]
- public async Task GetPictureById_InvokeExpectedMethods()
- {
- await _service.GetPictureById("1");
- _cacheMock.Verify(c => c.GetAsync<Picture>(It.IsAny<string>(), It.IsAny<Func<Task<Picture>>>()), Times.Once);
- }
- [TestMethod]
- public async Task LoadPictureBinary_FromDb()
- {
- _storagesettings.PictureStoreInDb = true;
- _repoMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new Picture { PictureBinary =
+ [TestMethod]
+ public async Task LoadPictureBinary_FromDb()
+ {
+ _storagesettings.PictureStoreInDb = true;
+ _repoMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new Picture {
+ PictureBinary =
[]
- }));
- await _service.LoadPictureBinary(new Picture());
- _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- }
+ }));
+ await _service.LoadPictureBinary(new Picture());
+ _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
- [TestMethod]
- public async Task LoadPictureBinary_FromDb_InvokeRepository()
- {
- _repoMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new Picture { PictureBinary =
+ [TestMethod]
+ public async Task LoadPictureBinary_FromDb_InvokeRepository()
+ {
+ _repoMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new Picture {
+ PictureBinary =
[]
- }));
- await _service.LoadPictureBinary(new Picture(), true);
- _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
- }
+ }));
+ await _service.LoadPictureBinary(new Picture(), true);
+ _repoMock.Verify(c => c.GetByIdAsync(It.IsAny<string>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task LoadPictureBinary_FromFile_ReturnEmptyBytes()
+ {
+ _webHostMock.Setup(c => c.WebRootPath).Returns("~root/");
+ var result = await _service.LoadPictureBinary(new Picture { Id = "id", MimeType = "image/jpeg" }, false);
+ //we can't mock static class like File.Exist so, should return empty array
+ Assert.IsTrue(result.Length == 0);
+ }
- [TestMethod]
- public async Task LoadPictureBinary_FromFile_ReturnEmptyBytes()
- {
- _webHostMock.Setup(c => c.WebRootPath).Returns("~root/");
- var result = await _service.LoadPictureBinary(new Picture { Id = "id", MimeType = "image/jpeg" }, false);
- //we can't mock static class like File.Exist so, should return empty array
- Assert.IsTrue(result.Length == 0);
- }
+ [TestMethod]
+ public async Task GetPictureUrl_InovkeCacheQuery()
+ {
+ await _service.GetPictureUrl("picture id");
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<string>>>()), Times.Once);
+ }
- [TestMethod]
- public async Task GetPictureUrl_InovkeCacheQuery()
- {
- await _service.GetPictureUrl("picture id");
- _cacheMock.Verify(c => c.GetAsync<string>(It.IsAny<string>(), It.IsAny<Func<Task<string>>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task InsertPicture_InvokeExpectedMethods()
+ {
+ _storagesettings.PictureStoreInDb = true;
+ await _service.InsertPicture([], "image/jpeg", "image", validateBinary: false);
+ _repoMock.Verify(c => c.InsertAsync(It.IsAny<Picture>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Picture>>(), default), Times.Once);
+ }
- [TestMethod]
- public async Task InsertPicture_InvokeExpectedMethods()
- {
- _storagesettings.PictureStoreInDb = true;
- await _service.InsertPicture([], "image/jpeg", "image", validateBinary: false);
- _repoMock.Verify(c => c.InsertAsync(It.IsAny<Picture>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityInserted<Picture>>(), default), Times.Once);
- }
- [TestMethod]
- public async Task UpdatePicture_InvokeExpectedMethods_PublishEvent()
- {
- _storagesettings.PictureStoreInDb = true;
- _cacheMock.Setup(c => c.GetAsync<Picture>(It.IsAny<string>(), It.IsAny<Func<Task<Picture>>>())).Returns(Task.FromResult(new Picture()));
- _repoMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new Picture { PictureBinary =
+ [TestMethod]
+ public async Task UpdatePicture_InvokeExpectedMethods_PublishEvent()
+ {
+ _storagesettings.PictureStoreInDb = true;
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<Picture>>>()))
+ .Returns(Task.FromResult(new Picture()));
+ _repoMock.Setup(c => c.GetByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(new Picture {
+ PictureBinary =
[]
- }));
- await _service.UpdatePicture("1", [], "image/jpeg", "image", validateBinary: false);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Picture>>(), default), Times.Once);
- }
- [TestMethod]
- public async Task UpdatePicture_PictureModel_InvokeExpectedMethods()
- {
- _storagesettings.PictureStoreInDb = true;
- await _service.UpdatePicture(new Picture());
- _repoMock.Verify(c => c.UpdateAsync(It.IsAny<Picture>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Picture>>(), default), Times.Once);
- }
+ }));
+ await _service.UpdatePicture("1", [], "image/jpeg", "image", validateBinary: false);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Picture>>(), default), Times.Once);
+ }
- [TestMethod]
- public void GetPictureSeName_ReturnExpectedValue()
- {
- Assert.AreEqual("productname", _service.GetPictureSeName("productName"));
- Assert.AreEqual("product-name", _service.GetPictureSeName("product-Name"));
- Assert.AreEqual("product-name", _service.GetPictureSeName("Product-Name"));
- Assert.AreEqual("productname-2", _service.GetPictureSeName("ProductName-2"));
- }
+ [TestMethod]
+ public async Task UpdatePicture_PictureModel_InvokeExpectedMethods()
+ {
+ _storagesettings.PictureStoreInDb = true;
+ await _service.UpdatePicture(new Picture());
+ _repoMock.Verify(c => c.UpdateAsync(It.IsAny<Picture>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityUpdated<Picture>>(), default), Times.Once);
+ }
- [TestMethod()]
- public async Task DeletePicture_ValidArguments_InvokeRepositoryAndPublishEvent()
- {
- await _service.DeletePicture(new Picture());
- _repoMock.Verify(c => c.DeleteAsync(It.IsAny<Picture>()), Times.Once);
- _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Picture>>(), default(CancellationToken)), Times.Once);
- }
+ [TestMethod]
+ public void GetPictureSeName_ReturnExpectedValue()
+ {
+ Assert.AreEqual("productname", _service.GetPictureSeName("productName"));
+ Assert.AreEqual("product-name", _service.GetPictureSeName("product-Name"));
+ Assert.AreEqual("product-name", _service.GetPictureSeName("Product-Name"));
+ Assert.AreEqual("productname-2", _service.GetPictureSeName("ProductName-2"));
+ }
+ [TestMethod]
+ public async Task DeletePicture_ValidArguments_InvokeRepositoryAndPublishEvent()
+ {
+ await _service.DeletePicture(new Picture());
+ _repoMock.Verify(c => c.DeleteAsync(It.IsAny<Picture>()), Times.Once);
+ _mediatorMock.Verify(c => c.Publish(It.IsAny<EntityDeleted<Picture>>(), default), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Storage.Tests/Startup/StartupApplicationTests.cs b/src/Tests/Grand.Business.Storage.Tests/Startup/StartupApplicationTests.cs
index bb2310549..26c8ea06c 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Startup/StartupApplicationTests.cs
+++ b/src/Tests/Grand.Business.Storage.Tests/Startup/StartupApplicationTests.cs
@@ -3,30 +3,29 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.Storage.Tests.Startup
+namespace Grand.Business.Storage.Tests.Startup;
+
+[TestClass]
+public class StartupApplicationTests
{
- [TestClass()]
- public class StartupApplicationTests
- {
- StartupApplication _application;
- ServiceCollection _serviceCollection;
- IConfiguration _configuration;
+ private StartupApplication _application;
+ private IConfiguration _configuration;
+ private ServiceCollection _serviceCollection;
- [TestInitialize]
- public void Init()
- {
- _serviceCollection = new ServiceCollection();
- _configuration = new ConfigurationBuilder().Build();
- _application = new StartupApplication();
+ [TestInitialize]
+ public void Init()
+ {
+ _serviceCollection = new ServiceCollection();
+ _configuration = new ConfigurationBuilder().Build();
+ _application = new StartupApplication();
+ }
- }
- [TestMethod()]
- public void ConfigureServicesTest()
- {
- //Act
- _application.ConfigureServices(_serviceCollection, _configuration);
- //Assert
- Assert.IsTrue(_serviceCollection.Count > 0);
- }
+ [TestMethod]
+ public void ConfigureServicesTest()
+ {
+ //Act
+ _application.ConfigureServices(_serviceCollection, _configuration);
+ //Assert
+ Assert.IsTrue(_serviceCollection.Count > 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.Storage.Tests/Upload/index.html b/src/Tests/Grand.Business.Storage.Tests/Upload/index.html
index 755f822ea..cfb660742 100644
--- a/src/Tests/Grand.Business.Storage.Tests/Upload/index.html
+++ b/src/Tests/Grand.Business.Storage.Tests/Upload/index.html
@@ -2,7 +2,7 @@
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
- <meta charset="utf-8" />
+ <meta charset="utf-8"/>
<title></title>
</head>
<body>
diff --git a/src/Tests/Grand.Business.System.Tests/Commands/SendOutBidCustomerNotificationCommandHandlerTests.cs b/src/Tests/Grand.Business.System.Tests/Commands/SendOutBidCustomerNotificationCommandHandlerTests.cs
index 0f9c81229..f9beb8e16 100644
--- a/src/Tests/Grand.Business.System.Tests/Commands/SendOutBidCustomerNotificationCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Commands/SendOutBidCustomerNotificationCommandHandlerTests.cs
@@ -2,34 +2,35 @@
using Grand.Business.Core.Interfaces.Messages;
using Grand.Business.System.Commands.Handlers.Catalog;
using Grand.Domain.Catalog;
+using Grand.Domain.Localization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Commands
+namespace Grand.Business.System.Tests.Commands;
+
+[TestClass]
+public class SendOutBidCustomerNotificationCommandHandlerTests
{
- [TestClass]
- public class SendOutBidCustomerNotificationCommandHandlerTests
- {
- private Mock<IMessageProviderService> _messageProviderMock;
- private SendOutBidCustomerNotificationCommandHandler _handler;
+ private SendOutBidCustomerNotificationCommandHandler _handler;
+ private Mock<IMessageProviderService> _messageProviderMock;
- [TestInitialize]
- public void Init()
- {
- _messageProviderMock = new Mock<IMessageProviderService>();
- _handler = new SendOutBidCustomerNotificationCommandHandler(_messageProviderMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _messageProviderMock = new Mock<IMessageProviderService>();
+ _handler = new SendOutBidCustomerNotificationCommandHandler(_messageProviderMock.Object);
+ }
- [TestMethod]
- public async Task Handle_InvokeExpectedMethod()
- {
- var command = new SendOutBidCustomerCommand {
- Product = new Domain.Catalog.Product(),
- Bid = new Domain.Catalog.Bid(),
- Language = new Domain.Localization.Language()
- };
- await _handler.Handle(command, default);
- _messageProviderMock.Verify(c => c.SendOutBidCustomerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()));
- }
+ [TestMethod]
+ public async Task Handle_InvokeExpectedMethod()
+ {
+ var command = new SendOutBidCustomerCommand {
+ Product = new Product(),
+ Bid = new Bid(),
+ Language = new Language()
+ };
+ await _handler.Handle(command, default);
+ _messageProviderMock.Verify(c =>
+ c.SendOutBidCustomerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Commands/SendQuantityBelowStoreOwnerNotificationCommandHandlerTests.cs b/src/Tests/Grand.Business.System.Tests/Commands/SendQuantityBelowStoreOwnerNotificationCommandHandlerTests.cs
index a0420a823..4fb2c5dcc 100644
--- a/src/Tests/Grand.Business.System.Tests/Commands/SendQuantityBelowStoreOwnerNotificationCommandHandlerTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Commands/SendQuantityBelowStoreOwnerNotificationCommandHandlerTests.cs
@@ -6,37 +6,39 @@ using Grand.Domain.Localization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Commands
+namespace Grand.Business.System.Tests.Commands;
+
+[TestClass]
+public class SendQuantityBelowStoreOwnerNotificationCommandHandlerTests
{
- [TestClass]
- public class SendQuantityBelowStoreOwnerNotificationCommandHandlerTests
- {
- private Mock<IMessageProviderService> _messageProviderMock;
- private LanguageSettings _settings;
- private SendQuantityBelowStoreOwnerNotificationCommandHandler _handler;
+ private SendQuantityBelowStoreOwnerNotificationCommandHandler _handler;
+ private Mock<IMessageProviderService> _messageProviderMock;
+ private LanguageSettings _settings;
- [TestInitialize]
- public void Init()
- {
- _messageProviderMock = new Mock<IMessageProviderService>();
- _settings = new LanguageSettings();
- _handler = new SendQuantityBelowStoreOwnerNotificationCommandHandler(_messageProviderMock.Object, _settings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _messageProviderMock = new Mock<IMessageProviderService>();
+ _settings = new LanguageSettings();
+ _handler = new SendQuantityBelowStoreOwnerNotificationCommandHandler(_messageProviderMock.Object, _settings);
+ }
- [TestMethod]
- public async Task Handle_InvokeExpectedMethods()
- {
- _settings.DefaultAdminLanguageId = "1";
- var command = new SendQuantityBelowStoreOwnerCommand {
- Product = new Domain.Catalog.Product(),
- ProductAttributeCombination = null
- };
+ [TestMethod]
+ public async Task Handle_InvokeExpectedMethods()
+ {
+ _settings.DefaultAdminLanguageId = "1";
+ var command = new SendQuantityBelowStoreOwnerCommand {
+ Product = new Product(),
+ ProductAttributeCombination = null
+ };
- await _handler.Handle(command, default);
- _messageProviderMock.Verify(c => c.SendQuantityBelowStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>()), Times.Once);
- command.ProductAttributeCombination = new ProductAttributeCombination();
- await _handler.Handle(command, default);
- _messageProviderMock.Verify(c => c.SendQuantityBelowStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<ProductAttributeCombination>(), It.IsAny<string>()), Times.Once);
- }
+ await _handler.Handle(command, default);
+ _messageProviderMock.Verify(c => c.SendQuantityBelowStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>()),
+ Times.Once);
+ command.ProductAttributeCombination = new ProductAttributeCombination();
+ await _handler.Handle(command, default);
+ _messageProviderMock.Verify(
+ c => c.SendQuantityBelowStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<ProductAttributeCombination>(),
+ It.IsAny<string>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/Admin/AdminSiteMapServiceTests.cs b/src/Tests/Grand.Business.System.Tests/Services/Admin/AdminSiteMapServiceTests.cs
index 9ca81bbe6..1dde782a9 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/Admin/AdminSiteMapServiceTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/Admin/AdminSiteMapServiceTests.cs
@@ -1,36 +1,35 @@
using Grand.Business.System.Services.Admin;
-using Grand.Domain.Admin;
using Grand.Data;
+using Grand.Domain.Admin;
using Grand.Infrastructure.Caching;
using MediatR;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Services.Admin
+namespace Grand.Business.System.Tests.Services.Admin;
+
+[TestClass]
+public class AdminSiteMapServiceTests
{
- [TestClass]
- public class AdminSiteMapServiceTests
+ private Mock<ICacheBase> _cacheMock;
+ private Mock<IMediator> _mediatorMock;
+ private Mock<IRepository<AdminSiteMap>> _repositoryMock;
+ private AdminSiteMapService _service;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<IRepository<AdminSiteMap>> _repositoryMock;
- private Mock<ICacheBase> _cacheMock;
- private AdminSiteMapService _service;
- private Mock<IMediator> _mediatorMock;
-
- [TestInitialize]
- public void Init()
- {
- _repositoryMock = new Mock<IRepository<AdminSiteMap>>();
- _cacheMock = new Mock<ICacheBase>();
- _mediatorMock = new Mock<IMediator>();
- _service = new AdminSiteMapService(_repositoryMock.Object,_cacheMock.Object, _mediatorMock.Object);
- }
+ _repositoryMock = new Mock<IRepository<AdminSiteMap>>();
+ _cacheMock = new Mock<ICacheBase>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new AdminSiteMapService(_repositoryMock.Object, _cacheMock.Object, _mediatorMock.Object);
+ }
- [TestMethod]
- public async Task GetSiteMap_InvokeExpectedMethods()
- {
- _cacheMock.Setup(c => c.GetAsync<List<AdminSiteMap>>(It.IsAny<string>(), It.IsAny<Func<Task<List<AdminSiteMap>>>>()));
- var result = await _service.GetSiteMap();
- _cacheMock.Verify(c => c.GetAsync<List<AdminSiteMap>>(It.IsAny<string>(), It.IsAny<Func<Task<List<AdminSiteMap>>>>()), Times.Once);
- }
+ [TestMethod]
+ public async Task GetSiteMap_InvokeExpectedMethods()
+ {
+ _cacheMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<AdminSiteMap>>>>()));
+ var result = await _service.GetSiteMap();
+ _cacheMock.Verify(c => c.GetAsync(It.IsAny<string>(), It.IsAny<Func<Task<List<AdminSiteMap>>>>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/CancelOrderScheduledTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/CancelOrderScheduledTaskTests.cs
index 596e06650..5bca3e066 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/CancelOrderScheduledTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/CancelOrderScheduledTaskTests.cs
@@ -4,37 +4,36 @@ using Grand.Domain.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Services.BackgroundService
+namespace Grand.Business.System.Tests.Services.BackgroundService;
+
+[TestClass]
+public class CancelOrderScheduledTaskTests
{
- [TestClass]
- public class CancelOrderScheduledTaskTests
- {
- private Mock<IOrderService> _orderServiceMock;
- private SystemSettings _settings;
- private CancelOrderScheduledTask _task;
+ private Mock<IOrderService> _orderServiceMock;
+ private SystemSettings _settings;
+ private CancelOrderScheduledTask _task;
- [TestInitialize]
- public void Init()
- {
- _orderServiceMock = new Mock<IOrderService>();
- _settings = new SystemSettings();
- _task = new CancelOrderScheduledTask(_settings, _orderServiceMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _orderServiceMock = new Mock<IOrderService>();
+ _settings = new SystemSettings();
+ _task = new CancelOrderScheduledTask(_settings, _orderServiceMock.Object);
+ }
- [TestMethod]
- public async Task Execute_InvokeExpectedMethods()
- {
- _settings.DaysToCancelUnpaidOrder = 1;
- await _task.Execute();
- _orderServiceMock.Verify(c => c.CancelExpiredOrders(It.IsAny<DateTime>()), Times.Once);
- }
+ [TestMethod]
+ public async Task Execute_InvokeExpectedMethods()
+ {
+ _settings.DaysToCancelUnpaidOrder = 1;
+ await _task.Execute();
+ _orderServiceMock.Verify(c => c.CancelExpiredOrders(It.IsAny<DateTime>()), Times.Once);
+ }
- [TestMethod]
- public async Task Execute_SettingsNotHaveValue_NotInvokeAnyMethods()
- {
- _settings.DaysToCancelUnpaidOrder = null;
- await _task.Execute();
- _orderServiceMock.Verify(c => c.CancelExpiredOrders(It.IsAny<DateTime>()), Times.Never);
- }
+ [TestMethod]
+ public async Task Execute_SettingsNotHaveValue_NotInvokeAnyMethods()
+ {
+ _settings.DaysToCancelUnpaidOrder = null;
+ await _task.Execute();
+ _orderServiceMock.Verify(c => c.CancelExpiredOrders(It.IsAny<DateTime>()), Times.Never);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/ClearCacheScheduleTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/ClearCacheScheduleTaskTests.cs
index 522b37130..76e5cb6f0 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/ClearCacheScheduleTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/ClearCacheScheduleTaskTests.cs
@@ -3,26 +3,25 @@ using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Services.BackgroundService
+namespace Grand.Business.System.Tests.Services.BackgroundService;
+
+[TestClass]
+public class ClearCacheScheduleTaskTests
{
- [TestClass]
- public class ClearCacheScheduleTaskTests
- {
- private Mock<ICacheBase> _cacheMock;
- private ClearCacheScheduleTask _task;
+ private Mock<ICacheBase> _cacheMock;
+ private ClearCacheScheduleTask _task;
- [TestInitialize]
- public void Init()
- {
- _cacheMock = new Mock<ICacheBase>();
- _task = new ClearCacheScheduleTask(_cacheMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _cacheMock = new Mock<ICacheBase>();
+ _task = new ClearCacheScheduleTask(_cacheMock.Object);
+ }
- [TestMethod]
- public async Task Execute_InvokeExpectedMethod()
- {
- await _task.Execute();
- _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
- }
+ [TestMethod]
+ public async Task Execute_InvokeExpectedMethod()
+ {
+ await _task.Execute();
+ _cacheMock.Verify(c => c.Clear(It.IsAny<bool>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/DeleteGuestsScheduleTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/DeleteGuestsScheduleTaskTests.cs
index 06512c3ad..3ab21cd00 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/DeleteGuestsScheduleTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/DeleteGuestsScheduleTaskTests.cs
@@ -4,30 +4,29 @@ using Grand.Domain.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Services.BackgroundService
-{
- [TestClass]
- public class DeleteGuestsScheduleTaskTests
- {
- private Mock<ICustomerService> _customerServiceMock;
- private SystemSettings _settings;
- private DeleteGuestsScheduleTask _task;
+namespace Grand.Business.System.Tests.Services.BackgroundService;
- [TestInitialize]
- public void Init()
- {
- _customerServiceMock = new Mock<ICustomerService>();
- _settings = new SystemSettings();
- _task = new DeleteGuestsScheduleTask(_customerServiceMock.Object, _settings);
- }
+[TestClass]
+public class DeleteGuestsScheduleTaskTests
+{
+ private Mock<ICustomerService> _customerServiceMock;
+ private SystemSettings _settings;
+ private DeleteGuestsScheduleTask _task;
- [TestMethod]
- public async Task Execute_InovkeExpectedMethod()
- {
- _settings.DeleteGuestTaskOlderThanMinutes = 0;
- await _task.Execute();
- _customerServiceMock.Verify(c => c.DeleteGuestCustomers(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<bool>()), Times.Once);
+ [TestInitialize]
+ public void Init()
+ {
+ _customerServiceMock = new Mock<ICustomerService>();
+ _settings = new SystemSettings();
+ _task = new DeleteGuestsScheduleTask(_customerServiceMock.Object, _settings);
+ }
- }
+ [TestMethod]
+ public async Task Execute_InovkeExpectedMethod()
+ {
+ _settings.DeleteGuestTaskOlderThanMinutes = 0;
+ await _task.Execute();
+ _customerServiceMock.Verify(
+ c => c.DeleteGuestCustomers(It.IsAny<DateTime?>(), It.IsAny<DateTime?>(), It.IsAny<bool>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs
index 0f7ed5f1a..1ae8003b5 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs
@@ -2,6 +2,7 @@
using Grand.Business.Core.Interfaces.Checkout.Orders;
using Grand.Business.Core.Interfaces.Customers;
using Grand.Business.Core.Interfaces.Messages;
+using Grand.Business.Core.Utilities.Checkout;
using Grand.Business.System.Services.BackgroundServices.ScheduleTasks;
using Grand.Domain;
using Grand.Domain.Catalog;
@@ -9,90 +10,106 @@ using Grand.Domain.Common;
using Grand.Domain.Customers;
using Grand.Domain.Localization;
using Grand.Domain.Orders;
+using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-using Grand.Business.Core.Utilities.Checkout;
-using Microsoft.Extensions.Logging;
-namespace Grand.Business.System.Tests.Services.BackgroundService
+namespace Grand.Business.System.Tests.Services.BackgroundService;
+
+[TestClass]
+public class EndAuctionsTaskTests
{
- [TestClass]
- public class EndAuctionsTaskTests
- {
- private Mock<IAuctionService> _auctionMock;
- private Mock<IMessageProviderService> _messageProviderMock;
- private Mock<IShoppingCartService> _shoppingCartMock;
- private Mock<ICustomerService> _customerServiceMock;
- private Mock<ILogger<EndAuctionsTask>> _loggerMock;
- private LanguageSettings _settings;
- private EndAuctionsTask _task;
+ private Mock<IAuctionService> _auctionMock;
+ private Mock<ICustomerService> _customerServiceMock;
+ private Mock<ILogger<EndAuctionsTask>> _loggerMock;
+ private Mock<IMessageProviderService> _messageProviderMock;
+ private LanguageSettings _settings;
+ private Mock<IShoppingCartService> _shoppingCartMock;
+ private EndAuctionsTask _task;
- [TestInitialize]
- public void Init()
- {
- _auctionMock = new Mock<IAuctionService>();
- _messageProviderMock = new Mock<IMessageProviderService>();
- _shoppingCartMock = new Mock<IShoppingCartService>();
- _customerServiceMock = new Mock<ICustomerService>();
- _loggerMock = new Mock<ILogger<EndAuctionsTask>>();
- _settings = new LanguageSettings();
- _task = new EndAuctionsTask(_auctionMock.Object, _messageProviderMock.Object, _settings, _shoppingCartMock.Object, _customerServiceMock.Object,
- _loggerMock.Object);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _auctionMock = new Mock<IAuctionService>();
+ _messageProviderMock = new Mock<IMessageProviderService>();
+ _shoppingCartMock = new Mock<IShoppingCartService>();
+ _customerServiceMock = new Mock<ICustomerService>();
+ _loggerMock = new Mock<ILogger<EndAuctionsTask>>();
+ _settings = new LanguageSettings();
+ _task = new EndAuctionsTask(_auctionMock.Object, _messageProviderMock.Object, _settings,
+ _shoppingCartMock.Object, _customerServiceMock.Object,
+ _loggerMock.Object);
+ }
- [TestMethod]
- public async Task Execute_NotBids_InvokeExpectedMethos()
- {
- _auctionMock.Setup(c => c.GetAuctionsToEnd()).ReturnsAsync(new List<Product> { new Product { Id = "id" } });
- _auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<Bid>());
- await _task.Execute();
- _auctionMock.Verify(c => c.UpdateAuctionEnded(It.IsAny<Product>(), It.IsAny<bool>(), It.IsAny<bool>()), Times.Once);
- _messageProviderMock.Verify(c => c.SendAuctionEndedStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()), Times.Once);
- }
+ [TestMethod]
+ public async Task Execute_NotBids_InvokeExpectedMethos()
+ {
+ _auctionMock.Setup(c => c.GetAuctionsToEnd()).ReturnsAsync(new List<Product> { new() { Id = "id" } });
+ _auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
+ .ReturnsAsync(() => new PagedList<Bid>());
+ await _task.Execute();
+ _auctionMock.Verify(c => c.UpdateAuctionEnded(It.IsAny<Product>(), It.IsAny<bool>(), It.IsAny<bool>()),
+ Times.Once);
+ _messageProviderMock.Verify(
+ c => c.SendAuctionEndedStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()),
+ Times.Once);
+ }
- [TestMethod]
- public async Task Execute_HasWarnings_InvokeExpectedMethos()
- {
- _auctionMock.Setup(c => c.GetAuctionsToEnd()).ReturnsAsync(new List<Product> { new Product { Id = "id" } });
- _auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<Bid> { new Bid() });
- _shoppingCartMock.Setup(c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<ShoppingCartType>(), It.IsAny<string>(),
+ [TestMethod]
+ public async Task Execute_HasWarnings_InvokeExpectedMethos()
+ {
+ _auctionMock.Setup(c => c.GetAuctionsToEnd()).ReturnsAsync(new List<Product> { new() { Id = "id" } });
+ _auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
+ .ReturnsAsync(() => new PagedList<Bid> { new() });
+ _shoppingCartMock.Setup(c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<ShoppingCartType>(),
+ It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<IList<CustomAttribute>>(), It.IsAny<double?>(), It.IsAny<DateTime?>(),
- It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(),
It.IsAny<ShoppingCartValidatorOptions>()))
- .ReturnsAsync((new List<string> { "warning" }, null));
- await _task.Execute();
+ .ReturnsAsync((new List<string> { "warning" }, null));
+ await _task.Execute();
- _loggerMock.Verify(c => c.Log(
- It.IsAny<LogLevel>(),
- It.IsAny<EventId>(),
- It.IsAny<It.IsAnyType>(),
- It.IsAny<Exception>(),
- (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
- }
+ _loggerMock.Verify(c => c.Log(
+ It.IsAny<LogLevel>(),
+ It.IsAny<EventId>(),
+ It.IsAny<It.IsAnyType>(),
+ It.IsAny<Exception>(),
+ (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
+ }
- [TestMethod]
- public async Task Execute_Valid_InvokeExpectedMethos()
- {
- _auctionMock.Setup(c => c.GetAuctionsToEnd()).ReturnsAsync(new List<Product> { new Product { Id = "id" } });
- _auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<Bid> { new Bid() });
- _shoppingCartMock.Setup(c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<ShoppingCartType>(), It.IsAny<string>(),
+ [TestMethod]
+ public async Task Execute_Valid_InvokeExpectedMethos()
+ {
+ _auctionMock.Setup(c => c.GetAuctionsToEnd()).ReturnsAsync(new List<Product> { new() { Id = "id" } });
+ _auctionMock.Setup(c => c.GetBidsByProductId(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()))
+ .ReturnsAsync(() => new PagedList<Bid> { new() });
+ _shoppingCartMock.Setup(c => c.AddToCart(It.IsAny<Customer>(), It.IsAny<string>(), It.IsAny<ShoppingCartType>(),
+ It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<IList<CustomAttribute>>(), It.IsAny<double?>(), It.IsAny<DateTime?>(),
- It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ShoppingCartValidatorOptions>()))
- .ReturnsAsync((new List<string>(), null));
- await _task.Execute();
+ It.IsAny<DateTime?>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<ShoppingCartValidatorOptions>()))
+ .ReturnsAsync((new List<string>(), null));
+ await _task.Execute();
- _loggerMock.Verify(c => c.Log(
- It.IsAny<LogLevel>(),
- It.IsAny<EventId>(),
- It.IsAny<It.IsAnyType>(),
- It.IsAny<Exception>(),
- (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Never);
- _auctionMock.Verify(c => c.UpdateBid(It.IsAny<Bid>()), Times.Once);
- _auctionMock.Verify(c => c.UpdateAuctionEnded(It.IsAny<Product>(), It.IsAny<bool>(), It.IsAny<bool>()), Times.Once);
- _messageProviderMock.Verify(c => c.SendAuctionEndedStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()), Times.Once);
- _messageProviderMock.Verify(c => c.SendAuctionWinEndedCustomerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()), Times.Once);
- _messageProviderMock.Verify(c => c.SendAuctionEndedLostCustomerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()), Times.Once);
- }
+ _loggerMock.Verify(c => c.Log(
+ It.IsAny<LogLevel>(),
+ It.IsAny<EventId>(),
+ It.IsAny<It.IsAnyType>(),
+ It.IsAny<Exception>(),
+ (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Never);
+ _auctionMock.Verify(c => c.UpdateBid(It.IsAny<Bid>()), Times.Once);
+ _auctionMock.Verify(c => c.UpdateAuctionEnded(It.IsAny<Product>(), It.IsAny<bool>(), It.IsAny<bool>()),
+ Times.Once);
+ _messageProviderMock.Verify(
+ c => c.SendAuctionEndedStoreOwnerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()),
+ Times.Once);
+ _messageProviderMock.Verify(
+ c => c.SendAuctionWinEndedCustomerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()),
+ Times.Once);
+ _messageProviderMock.Verify(
+ c => c.SendAuctionEndedLostCustomerMessage(It.IsAny<Product>(), It.IsAny<string>(), It.IsAny<Bid>()),
+ Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs
index d16116a17..969089d9b 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs
@@ -6,64 +6,70 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Services.BackgroundService
+namespace Grand.Business.System.Tests.Services.BackgroundService;
+
+[TestClass]
+public class QueuedMessagesSendScheduleTaskTests
{
- [TestClass]
- public class QueuedMessagesSendScheduleTaskTests
+ private Mock<IEmailAccountService> _emailAccountServiceMock;
+ private Mock<IEmailSender> _emailSenderMock;
+ private Mock<ILogger<QueuedMessagesSendScheduleTask>> _loggerMock;
+ private Mock<IQueuedEmailService> _queuedEmailServiceMock;
+ private QueuedMessagesSendScheduleTask _task;
+
+ [TestInitialize]
+ public void Init()
{
- private Mock<IQueuedEmailService> _queuedEmailServiceMock;
- private Mock<IEmailSender> _emailSenderMock;
- private Mock<IEmailAccountService> _emailAccountServiceMock;
- private Mock<ILogger<QueuedMessagesSendScheduleTask>> _loggerMock;
- private QueuedMessagesSendScheduleTask _task;
+ _queuedEmailServiceMock = new Mock<IQueuedEmailService>();
+ _emailSenderMock = new Mock<IEmailSender>();
+ _emailAccountServiceMock = new Mock<IEmailAccountService>();
+ _loggerMock = new Mock<ILogger<QueuedMessagesSendScheduleTask>>();
+ _task = new QueuedMessagesSendScheduleTask(_queuedEmailServiceMock.Object, _emailSenderMock.Object,
+ _loggerMock.Object, _emailAccountServiceMock.Object);
+ }
- [TestInitialize]
- public void Init()
- {
- _queuedEmailServiceMock = new Mock<IQueuedEmailService>();
- _emailSenderMock = new Mock<IEmailSender>();
- _emailAccountServiceMock = new Mock<IEmailAccountService>();
- _loggerMock = new Mock<ILogger<QueuedMessagesSendScheduleTask>>();
- _task = new QueuedMessagesSendScheduleTask(_queuedEmailServiceMock.Object, _emailSenderMock.Object, _loggerMock.Object, _emailAccountServiceMock.Object);
- }
+ [TestMethod]
+ public async Task Execute_InovekExpectedMethods()
+ {
+ _queuedEmailServiceMock.Setup(c => c.SearchEmails(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<DateTime?>(),
+ It.IsAny<DateTime?>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<int>(), It.IsAny<bool>(),
+ It.IsAny<int>(), It.IsAny<string>(),
+ It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<QueuedEmail>
+ { new() { Bcc = "bcc", CC = "cc", EmailAccountId = "id" } });
+ _emailAccountServiceMock.Setup(c => c.GetEmailAccountById(It.IsAny<string>())).ReturnsAsync(new EmailAccount());
- [TestMethod]
- public async Task Execute_InovekExpectedMethods()
- {
- _queuedEmailServiceMock.Setup(c => c.SearchEmails(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<DateTime?>(),
- It.IsAny<DateTime?>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<int>(), It.IsAny<string>(),
- It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<QueuedEmail> { new QueuedEmail { Bcc = "bcc", CC = "cc", EmailAccountId = "id" } });
- _emailAccountServiceMock.Setup(c => c.GetEmailAccountById(It.IsAny<string>())).ReturnsAsync(new EmailAccount());
+ await _task.Execute();
+ _emailSenderMock.Verify(c => c.SendEmail(It.IsAny<EmailAccount>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()
+ , It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>()), Times.Once);
- await _task.Execute();
- _emailSenderMock.Verify(c => c.SendEmail(It.IsAny<EmailAccount>(), It.IsAny<string>(), It.IsAny<string>(),
- It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()
- , It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>(),
- It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>()), Times.Once);
+ _queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once);
+ }
- _queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once);
- }
+ [TestMethod]
+ public async Task Execute_ThrowExecption_InovekExpectedMethodsAndInsertLog()
+ {
+ _queuedEmailServiceMock.Setup(c => c.SearchEmails(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<DateTime?>(),
+ It.IsAny<DateTime?>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<int>(), It.IsAny<bool>(),
+ It.IsAny<int>(), It.IsAny<string>(),
+ It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<QueuedEmail>
+ { new() { Bcc = "bcc", CC = "cc", EmailAccountId = "id" } });
+ _emailAccountServiceMock.Setup(c => c.GetEmailAccountById(It.IsAny<string>())).ReturnsAsync(new EmailAccount());
+ _emailSenderMock.Setup(c => c.SendEmail(It.IsAny<EmailAccount>(), It.IsAny<string>(), It.IsAny<string>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()
+ , It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>(),
+ It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>())).ThrowsAsync(new Exception());
- [TestMethod]
- public async Task Execute_ThrowExecption_InovekExpectedMethodsAndInsertLog()
- {
- _queuedEmailServiceMock.Setup(c => c.SearchEmails(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<DateTime?>(),
- It.IsAny<DateTime?>(), It.IsAny<bool>(), It.IsAny<bool>(), It.IsAny<int>(), It.IsAny<bool>(), It.IsAny<int>(), It.IsAny<string>(),
- It.IsAny<int>(), It.IsAny<int>())).ReturnsAsync(() => new PagedList<QueuedEmail> { new QueuedEmail { Bcc = "bcc", CC = "cc", EmailAccountId = "id" } });
- _emailAccountServiceMock.Setup(c => c.GetEmailAccountById(It.IsAny<string>())).ReturnsAsync(new EmailAccount());
- _emailSenderMock.Setup(c => c.SendEmail(It.IsAny<EmailAccount>(), It.IsAny<string>(), It.IsAny<string>(),
- It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()
- , It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>(),
- It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>())).ThrowsAsync(new Exception());
-
- await _task.Execute();
- _loggerMock.Verify(c => c.Log(
- It.IsAny<LogLevel>(),
- It.IsAny<EventId>(),
- It.IsAny<It.IsAnyType>(),
- It.IsAny<Exception>(),
- (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
- _queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once);
- }
+ await _task.Execute();
+ _loggerMock.Verify(c => c.Log(
+ It.IsAny<LogLevel>(),
+ It.IsAny<EventId>(),
+ It.IsAny<It.IsAnyType>(),
+ It.IsAny<Exception>(),
+ (Func<It.IsAnyType, Exception, string>)It.IsAny<object>()), Times.Once);
+ _queuedEmailServiceMock.Verify(c => c.UpdateQueuedEmail(It.IsAny<QueuedEmail>()), Times.Once);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/UpdateExchangeRateScheduleTaskTests.cs b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/UpdateExchangeRateScheduleTaskTests.cs
index 4685511de..740293bae 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/UpdateExchangeRateScheduleTaskTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/BackgroundService/UpdateExchangeRateScheduleTaskTests.cs
@@ -4,46 +4,48 @@ using Grand.Domain.Directory;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Services.BackgroundService
+namespace Grand.Business.System.Tests.Services.BackgroundService;
+
+[TestClass]
+public class UpdateExchangeRateScheduleTaskTests
{
- [TestClass]
- public class UpdateExchangeRateScheduleTaskTests
- {
- private Mock<ICurrencyService> _currencyServiceMock;
- private Mock<IExchangeRateService> _exchangeRateServiceMock;
- private CurrencySettings _settings;
- private UpdateExchangeRateScheduleTask _task;
+ private Mock<ICurrencyService> _currencyServiceMock;
+ private Mock<IExchangeRateService> _exchangeRateServiceMock;
+ private CurrencySettings _settings;
+ private UpdateExchangeRateScheduleTask _task;
- [TestInitialize]
- public void Init()
- {
- _currencyServiceMock = new Mock<ICurrencyService>();
- _exchangeRateServiceMock = new Mock<IExchangeRateService>();
- _settings = new CurrencySettings();
- _task = new UpdateExchangeRateScheduleTask(_currencyServiceMock.Object, _exchangeRateServiceMock.Object, _settings);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _currencyServiceMock = new Mock<ICurrencyService>();
+ _exchangeRateServiceMock = new Mock<IExchangeRateService>();
+ _settings = new CurrencySettings();
+ _task = new UpdateExchangeRateScheduleTask(_currencyServiceMock.Object, _exchangeRateServiceMock.Object,
+ _settings);
+ }
- [TestMethod]
- public async Task Execute_InvokeExpectedMethods()
- {
- _settings.AutoUpdateEnabled = true;
- _currencyServiceMock.Setup(c => c.GetPrimaryExchangeRateCurrency()).ReturnsAsync(new Currency { CurrencyCode = "EU" });
- _exchangeRateServiceMock.Setup(c => c.GetCurrencyLiveRates(It.IsAny<string>()))
- .ReturnsAsync(new List<ExchangeRate> { new ExchangeRate { CurrencyCode = "PL", Rate = 10 } });
- _currencyServiceMock.Setup(c => c.GetCurrencyByCode(It.IsAny<string>())).ReturnsAsync(new Currency { Rate = 10 });
- await _task.Execute();
+ [TestMethod]
+ public async Task Execute_InvokeExpectedMethods()
+ {
+ _settings.AutoUpdateEnabled = true;
+ _currencyServiceMock.Setup(c => c.GetPrimaryExchangeRateCurrency())
+ .ReturnsAsync(new Currency { CurrencyCode = "EU" });
+ _exchangeRateServiceMock.Setup(c => c.GetCurrencyLiveRates(It.IsAny<string>()))
+ .ReturnsAsync(new List<ExchangeRate> { new() { CurrencyCode = "PL", Rate = 10 } });
+ _currencyServiceMock.Setup(c => c.GetCurrencyByCode(It.IsAny<string>()))
+ .ReturnsAsync(new Currency { Rate = 10 });
+ await _task.Execute();
- _currencyServiceMock.Verify(c => c.UpdateCurrency(It.IsAny<Currency>()), Times.Once);
- }
+ _currencyServiceMock.Verify(c => c.UpdateCurrency(It.IsAny<Currency>()), Times.Once);
+ }
- [TestMethod]
- public async Task Execute_AutoUpdateNotEnable_NotInvokeMethods()
- {
- _settings.AutoUpdateEnabled = false;
- await _task.Execute();
- _currencyServiceMock.Verify(c => c.GetPrimaryExchangeRateCurrency(), Times.Never);
- _exchangeRateServiceMock.Verify(c => c.GetCurrencyLiveRates(It.IsAny<string>()), Times.Never);
- _currencyServiceMock.Verify(c => c.UpdateCurrency(It.IsAny<Currency>()), Times.Never);
- }
+ [TestMethod]
+ public async Task Execute_AutoUpdateNotEnable_NotInvokeMethods()
+ {
+ _settings.AutoUpdateEnabled = false;
+ await _task.Execute();
+ _currencyServiceMock.Verify(c => c.GetPrimaryExchangeRateCurrency(), Times.Never);
+ _exchangeRateServiceMock.Verify(c => c.GetCurrencyLiveRates(It.IsAny<string>()), Times.Never);
+ _currencyServiceMock.Verify(c => c.UpdateCurrency(It.IsAny<Currency>()), Times.Never);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/ExportImport/ExportManagerTests.cs b/src/Tests/Grand.Business.System.Tests/Services/ExportImport/ExportManagerTests.cs
index ae5abfb88..575560c28 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/ExportImport/ExportManagerTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/ExportImport/ExportManagerTests.cs
@@ -161,8 +161,9 @@
// var result = _exportManager.ExportNewsletterSubscribersToTxt(list);
// Assert.AreEqual("[email protected],True,12.04.2021 00:00:00,s1,\r\[email protected],False,20.04.2021 00:00:00,s2,\r\[email protected],True,21.04.2021 00:00:00,s3,\r\n", result);
-
+
// }
// */
// }
//}
+
diff --git a/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationManagerTests.cs b/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationManagerTests.cs
index a85a7a7e3..d0510780a 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationManagerTests.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationManagerTests.cs
@@ -1,25 +1,23 @@
using Grand.Infrastructure.Migrations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Business.System.Tests.Services.Migrations
-{
- [TestClass]
- public class MigrationManagerTests
- {
- private MigrationManager _migrationManager;
+namespace Grand.Business.System.Tests.Services.Migrations;
- [TestInitialize]
- public void Init()
- {
- _migrationManager = new MigrationManager();
- }
+[TestClass]
+public class MigrationManagerTests
+{
+ private MigrationManager _migrationManager;
- [TestMethod]
- public void GetCurrentMigrations_Exists()
- {
- var migrations = _migrationManager.GetCurrentMigrations();
- Assert.IsTrue(migrations.Count() > 0);
- }
+ [TestInitialize]
+ public void Init()
+ {
+ _migrationManager = new MigrationManager();
+ }
+ [TestMethod]
+ public void GetCurrentMigrations_Exists()
+ {
+ var migrations = _migrationManager.GetCurrentMigrations();
+ Assert.IsTrue(migrations.Count() > 0);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs b/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs
index 2400192ac..6cf8d7b52 100644
--- a/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs
+++ b/src/Tests/Grand.Business.System.Tests/Services/Migrations/MigrationProcessTest.cs
@@ -5,37 +5,35 @@ using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Business.System.Tests.Services.Migrations
-{
- [TestClass()]
- public class MigrationProcessTest
- {
- private Mock<IRepository<MigrationDb>> _repository;
- private MigrationProcess _service;
- private Mock<IDatabaseContext> _dbContext;
- private Mock<ILogger<MigrationProcess>> _loggerMock;
- private IServiceProvider _serviceProvider;
+namespace Grand.Business.System.Tests.Services.Migrations;
- [TestInitialize]
- public void Init()
- {
- var serviceProvider = new Mock<IServiceProvider>();
- _serviceProvider = serviceProvider.Object;
+[TestClass]
+public class MigrationProcessTest
+{
+ private Mock<IDatabaseContext> _dbContext;
+ private Mock<ILogger<MigrationProcess>> _loggerMock;
+ private Mock<IRepository<MigrationDb>> _repository;
+ private MigrationProcess _service;
+ private IServiceProvider _serviceProvider;
- _repository = new Mock<IRepository<MigrationDb>>();
- _dbContext = new Mock<IDatabaseContext>();
- _loggerMock = new Mock<ILogger<MigrationProcess>>();
- _service = new MigrationProcess(_dbContext.Object, _serviceProvider, _loggerMock.Object, _repository.Object);
- }
- //TODO
- /*
- [TestMethod]
- public void RunMigrationProcess_CheckInsertMigrationDb()
- {
- _service.RunMigrationProcess();
- _repository.Verify(c => c.Insert(It.IsAny<MigrationDb>()), Times.AtLeastOnce);
- }
- */
+ [TestInitialize]
+ public void Init()
+ {
+ var serviceProvider = new Mock<IServiceProvider>();
+ _serviceProvider = serviceProvider.Object;
+ _repository = new Mock<IRepository<MigrationDb>>();
+ _dbContext = new Mock<IDatabaseContext>();
+ _loggerMock = new Mock<ILogger<MigrationProcess>>();
+ _service = new MigrationProcess(_dbContext.Object, _serviceProvider, _loggerMock.Object, _repository.Object);
+ }
+ //TODO
+ /*
+ [TestMethod]
+ public void RunMigrationProcess_CheckInsertMigrationDb()
+ {
+ _service.RunMigrationProcess();
+ _repository.Verify(c => c.Insert(It.IsAny<MigrationDb>()), Times.AtLeastOnce);
}
-}
+ */
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Data.Tests/AuditInfoProvider.cs b/src/Tests/Grand.Data.Tests/AuditInfoProvider.cs
index 0e8b2f15d..c4409abfc 100644
--- a/src/Tests/Grand.Data.Tests/AuditInfoProvider.cs
+++ b/src/Tests/Grand.Data.Tests/AuditInfoProvider.cs
@@ -2,10 +2,6 @@
public class AuditInfoProvider : IAuditInfoProvider
{
- public AuditInfoProvider()
- {
- }
-
public string GetCurrentUser()
{
return "user";
diff --git a/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryMock.cs b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryMock.cs
index 539f3bee4..93330677a 100644
--- a/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryMock.cs
+++ b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryMock.cs
@@ -1,16 +1,15 @@
-using Grand.Domain;
-using Grand.Data.LiteDb;
+using Grand.Data.LiteDb;
+using Grand.Domain;
using LiteDB;
-namespace Grand.Data.Tests.LiteDb
+namespace Grand.Data.Tests.LiteDb;
+
+public class LiteDBRepositoryMock<T> : LiteDBRepository<T>, IRepository<T> where T : BaseEntity
{
- public class LiteDBRepositoryMock<T> : LiteDBRepository<T>, IRepository<T> where T : BaseEntity
+ public LiteDBRepositoryMock() : base(Guid.NewGuid().ToString(), new AuditInfoProvider())
{
- public LiteDBRepositoryMock(): base(Guid.NewGuid().ToString(), new AuditInfoProvider())
- {
- _database = new LiteDatabase(new MemoryStream());
- _database.DropCollection(typeof(T).Name);
- _collection = _database.GetCollection<T>(typeof(T).Name);
- }
+ _database = new LiteDatabase(new MemoryStream());
+ _database.DropCollection(typeof(T).Name);
+ _collection = _database.GetCollection<T>(typeof(T).Name);
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryTests.cs b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryTests.cs
index b140dfec2..6a7092a15 100644
--- a/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryTests.cs
+++ b/src/Tests/Grand.Data.Tests/LiteDb/LiteDbRepositoryTests.cs
@@ -1,540 +1,554 @@
-using Grand.SharedKernel.Extensions;
+using Grand.Domain.Common;
+using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Data.Tests.LiteDb
+namespace Grand.Data.Tests.LiteDb;
+
+[TestClass]
+public class LiteDbRepositoryTests
{
- [TestClass()]
- public class LiteDbRepositoryTests
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = "";
+ }
+
+ [TestMethod]
+ public void Insert_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ //Act
+ myRepository.Insert(product);
+ //Assert
+ Assert.AreEqual(1, myRepository.Table.Count());
+ Assert.IsTrue(myRepository.Table.FirstOrDefault(x => x.Id == "1")!.CreatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task InsertAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var product = new SampleCollection { Id = "11" };
+ //Act
+ await myRepository.InsertAsync(product);
+ var p = myRepository.GetById("11");
+ //Assert
+ Assert.IsNotNull(p);
+ Assert.AreEqual(1, myRepository.Table.Count());
+ Assert.IsTrue(p.CreatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task GetById_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ var p = myRepository.GetById("1");
+
+ Assert.IsNotNull(p);
+ }
+
+ [TestMethod]
+ public async Task GetByIdAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ var p = await myRepository.GetByIdAsync("1");
+
+ Assert.IsNotNull(p);
+ }
+
+ [TestMethod]
+ public async Task GetOneAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ var p = await myRepository.GetOneAsync(x => x.Id == "1");
+
+ Assert.IsNotNull(p);
+ }
+
+ [TestMethod]
+ public async Task GetOneAsync_ToLowerInvariant_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ var p = await myRepository.GetOneAsync(x => x.Id == "1".ToLowerInvariant());
+
+ Assert.IsNotNull(p);
+ }
+
+ [TestMethod]
+ public async Task ClearAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ await myRepository.ClearAsync();
+
+ Assert.IsTrue(myRepository.Table.Count() == 0);
+ }
+
+ [TestMethod]
+ public async Task AddToSet_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ await myRepository.AddToSet("1", x => x.UserFields,
+ new UserField { Key = "key", Value = "value", StoreId = "" });
+
+ //Act
+ await myRepository.AddToSet("1", x => x.UserFields,
+ new UserField { Key = "key2", Value = "value2", StoreId = "" });
+ var p = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p.UserFields.Count == 2);
+ Assert.IsTrue(p.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task Delete_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ myRepository.Delete(product);
+
+ var p = myRepository.GetById("1");
+
+ Assert.IsNull(p);
+ }
+
+ [TestMethod]
+ public async Task DeleteAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var product = new SampleCollection { Id = "1" };
+ await myRepository.InsertAsync(product);
+
+ await myRepository.DeleteAsync(product);
+
+ var p = myRepository.GetById("1");
+
+ Assert.IsNull(p);
+ }
+
+ [TestMethod]
+ public async Task DeleteManyAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+
+ await myRepository.InsertAsync(new SampleCollection { Id = "1", Name = "Test" });
+ await myRepository.InsertAsync(new SampleCollection { Id = "2", Name = "Test" });
+ await myRepository.InsertAsync(new SampleCollection { Id = "3", Name = "Test2" });
+
+ await myRepository.DeleteManyAsync(x => x.Name == "Test");
+
+ Assert.IsTrue(myRepository.Table.Count() == 1);
+ }
+
+ [TestMethod]
+ public async Task Pull_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() {
+ Id = "2", Name = "Test2",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+ //Act
+ await myRepository.Pull("1", x => x.Phones, "Phone2");
+ var p = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p.Phones.Count == 2);
+ Assert.IsTrue(p.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task Pull_Many_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() {
+ Id = "2", Name = "Test2",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+
+ //Act
+ await myRepository.Pull(string.Empty, x => x.Phones, "Phone2");
+
+ var p1 = myRepository.GetById("1");
+ var p2 = myRepository.GetById("2");
+ var p3 = myRepository.GetById("3");
+
+ //Assert
+ Assert.IsTrue(p1.Phones.Count == 2 && p2.Phones.Count == 2 && p3.Phones.Count == 0);
+ Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p1.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task PullFilter_1_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value1", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+ //Act
+ await myRepository.PullFilter("1", x => x.UserFields, x => x.Value == "value");
+
+ var p1 = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.UserFields.Count == 2);
+ Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p1.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task PullFilter_2_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+
+ //Act
+ await myRepository.PullFilter("1", x => x.UserFields, x => x.Value, "value");
+
+ var p1 = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.UserFields.Count == 1);
+ Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p1.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task PullFilter_2_Many_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() {
+ Id = "2", Name = "Test2",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value1", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+
+ //Act
+ await myRepository.PullFilter(string.Empty, x => x.UserFields, x => x.Value, "value");
+
+ var p1 = myRepository.GetById("1");
+ var p2 = myRepository.GetById("2");
+
+ //Assert
+ Assert.IsTrue(p1.UserFields.Count == 1 && p2.UserFields.Count == 2);
+ Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p1.UpdatedBy == "user");
+ }
+
+
+ [TestMethod]
+ public void Update_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+
+ var p1_update = products.FirstOrDefault();
+ p1_update.Name = "update";
+
+ //Act
+ myRepository.Update(p1_update);
+
+ var p1 = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.Name == "update");
+ Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p1.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task UpdateAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+
+ var p1_update = products.FirstOrDefault();
+ p1_update.Name = "update";
+ //Act
+ await myRepository.UpdateAsync(p1_update);
+
+ var p1 = myRepository.GetById("1");
+ //Assert
+ Assert.IsTrue(p1.Name == "update");
+ Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p1.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task UpdateField_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+ //Act
+ await myRepository.UpdateField("1", x => x.Name, "update");
+
+ var p1 = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.Name == "update");
+ Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p1.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task IncField_MongoRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ var sample = new SampleCollection { Id = "1", Name = "Test" };
+ await myRepository.InsertAsync(sample);
+
+ await myRepository.IncField("1", x => x.Count, 1);
+ await myRepository.IncField("1", x => x.Count, 1);
+ await myRepository.IncField("1", x => x.Count, 1);
+
+ var p1 = myRepository.GetById("1");
+
+ Assert.IsTrue(p1.Count == 3);
+ }
+
+ [TestMethod]
+ public async Task UpdateManyAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+
+ //Act
+ await myRepository.UpdateManyAsync(x => x.Name == "Test",
+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
+
+ var pUpdated = myRepository.Table.Where(x => x.Name == "UpdateTest");
+
+ //Asser
+ Assert.IsTrue(pUpdated.Count() == 2);
+ Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task UpdateOneAsync_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+ //Act
+ await myRepository.UpdateOneAsync(x => x.Name == "Test",
+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
+
+ var pUpdated = myRepository.Table.Where(x => x.Name == "UpdateTest");
+
+ //Assert
+ Assert.IsTrue(pUpdated.Count() == 1);
+ Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task UpdateToSet_LiteRepository_Success()
+ {
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+
+ //Act
+ await myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key, "key",
+ new UserField { Key = "key", Value = "update", StoreId = "1" });
+ var p = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p.UserFields!.FirstOrDefault(x => x.Key == "key")!.Value == "update");
+ Assert.IsTrue(p.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p.UpdatedBy == "user");
+ }
+
+ [TestMethod]
+ public async Task UpdateToSet_2_LiteRepository_Success()
{
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = "";
- }
-
- [TestMethod()]
- public void Insert_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
-
- //Arrange
- var product = new SampleCollection { Id = "1" };
- //Act
- myRepository.Insert(product);
- //Assert
- Assert.AreEqual(1, myRepository.Table.Count());
- Assert.IsTrue(myRepository.Table.FirstOrDefault(x => x.Id == "1")!.CreatedBy == "user");
- }
-
- [TestMethod()]
- public async Task InsertAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var product = new SampleCollection { Id = "11" };
- //Act
- await myRepository.InsertAsync(product);
- var p = myRepository.GetById("11");
- //Assert
- Assert.IsNotNull(p);
- Assert.AreEqual(1, myRepository.Table.Count());
- Assert.IsTrue(p.CreatedBy == "user");
- }
-
- [TestMethod()]
- public async Task GetById_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- var p = myRepository.GetById("1");
-
- Assert.IsNotNull(p);
- }
-
- [TestMethod()]
- public async Task GetByIdAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- var p = await myRepository.GetByIdAsync("1");
-
- Assert.IsNotNull(p);
- }
-
- [TestMethod()]
- public async Task GetOneAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- var p = await myRepository.GetOneAsync(x => x.Id == "1");
-
- Assert.IsNotNull(p);
- }
- [TestMethod()]
- public async Task GetOneAsync_ToLowerInvariant_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- var p = await myRepository.GetOneAsync(x => x.Id == "1".ToLowerInvariant());
-
- Assert.IsNotNull(p);
- }
- [TestMethod()]
- public async Task ClearAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- await myRepository.ClearAsync();
-
- Assert.IsTrue(myRepository.Table.Count() == 0);
- }
-
- [TestMethod()]
- public async Task AddToSet_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- await myRepository.AddToSet("1", x => x.UserFields,
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" });
-
- //Act
- await myRepository.AddToSet("1", x => x.UserFields,
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" });
- var p = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p.UserFields.Count == 2);
- Assert.IsTrue(p.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p.UpdatedBy == "user");
-
- }
-
- [TestMethod()]
- public async Task Delete_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- myRepository.Delete(product);
-
- var p = myRepository.GetById("1");
-
- Assert.IsNull(p);
- }
-
- [TestMethod()]
- public async Task DeleteAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var product = new SampleCollection { Id = "1" };
- await myRepository.InsertAsync(product);
-
- await myRepository.DeleteAsync(product);
-
- var p = myRepository.GetById("1");
-
- Assert.IsNull(p);
- }
- [TestMethod()]
- public async Task DeleteManyAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
-
- await myRepository.InsertAsync(new SampleCollection { Id = "1", Name = "Test" });
- await myRepository.InsertAsync(new SampleCollection { Id = "2", Name = "Test" });
- await myRepository.InsertAsync(new SampleCollection { Id = "3", Name = "Test2" });
-
- await myRepository.DeleteManyAsync(x => x.Name == "Test");
-
- Assert.IsTrue(myRepository.Table.Count() == 1);
- }
-
- [TestMethod()]
- public async Task Pull_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- Phones = new [] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection { Id = "2", Name = "Test2",
- Phones = new [] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
- //Act
- await myRepository.Pull("1", x => x.Phones, "Phone2");
- var p = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p.Phones.Count == 2);
- Assert.IsTrue(p.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p.UpdatedBy == "user");
- }
- [TestMethod()]
- public async Task Pull_Many_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- Phones = new [] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection { Id = "2", Name = "Test2",
- Phones = new [] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
-
- //Act
- await myRepository.Pull(String.Empty, x => x.Phones, "Phone2");
-
- var p1 = myRepository.GetById("1");
- var p2 = myRepository.GetById("2");
- var p3 = myRepository.GetById("3");
-
- //Assert
- Assert.IsTrue(p1.Phones.Count == 2 && p2.Phones.Count == 2 && p3.Phones.Count == 0);
- Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p1.UpdatedBy == "user");
-
- }
-
- [TestMethod()]
- public async Task PullFilter_1_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value1", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
- //Act
- await myRepository.PullFilter("1", x => x.UserFields, x => x.Value == "value");
-
- var p1 = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.UserFields.Count == 2);
- Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p1.UpdatedBy == "user");
-
- }
-
- [TestMethod()]
- public async Task PullFilter_2_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
-
- //Act
- await myRepository.PullFilter("1", x => x.UserFields, x => x.Value, "value");
-
- var p1 = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.UserFields.Count == 1);
- Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p1.UpdatedBy == "user");
-
- }
- [TestMethod()]
- public async Task PullFilter_2_Many_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test2",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value1", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
+ var myRepository = new LiteDBRepositoryMock<SampleCollection>();
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
}
},
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
-
- //Act
- await myRepository.PullFilter(String.Empty, x => x.UserFields, x => x.Value, "value");
-
- var p1 = myRepository.GetById("1");
- var p2 = myRepository.GetById("2");
-
- //Assert
- Assert.IsTrue(p1.UserFields.Count == 1 && p2.UserFields.Count == 2);
- Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p1.UpdatedBy == "user");
- }
-
-
- [TestMethod()]
- public void Update_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
-
- var p1_update = products.FirstOrDefault();
- p1_update.Name = "update";
-
- //Act
- myRepository.Update(p1_update);
-
- var p1 = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.Name == "update");
- Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p1.UpdatedBy == "user");
-
- }
- [TestMethod()]
- public async Task UpdateAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
-
- var p1_update = products.FirstOrDefault();
- p1_update.Name = "update";
- //Act
- await myRepository.UpdateAsync(p1_update);
-
- var p1 = myRepository.GetById("1");
- //Assert
- Assert.IsTrue(p1.Name == "update");
- Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p1.UpdatedBy == "user");
- }
-
- [TestMethod()]
- public async Task UpdateField_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
- //Act
- await myRepository.UpdateField("1", x => x.Name, "update");
-
- var p1 = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.Name == "update");
- Assert.IsTrue(p1.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p1.UpdatedBy == "user");
-
- }
- [TestMethod()]
- public async Task IncField_MongoRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- var sample = new SampleCollection { Id = "1", Name = "Test" };
- await myRepository.InsertAsync(sample);
-
- await myRepository.IncField("1", x => x.Count, 1);
- await myRepository.IncField("1", x => x.Count, 1);
- await myRepository.IncField("1", x => x.Count, 1);
-
- var p1 = myRepository.GetById("1");
-
- Assert.IsTrue(p1.Count == 3);
- }
- [TestMethod()]
- public async Task UpdateManyAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
-
- //Act
- await myRepository.UpdateManyAsync(x => x.Name == "Test",
- UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
-
- var pUpdated = myRepository.Table.Where(x => x.Name == "UpdateTest");
-
- //Asser
- Assert.IsTrue(pUpdated.Count() == 2);
- Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedOnUtc.HasValue);
- Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedBy == "user");
-
- }
-
- [TestMethod()]
- public async Task UpdateOneAsync_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
- //Act
- await myRepository.UpdateOneAsync(x => x.Name == "Test",
- UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
-
- var pUpdated = myRepository.Table.Where(x => x.Name == "UpdateTest");
-
- //Assert
- Assert.IsTrue(pUpdated.Count() == 1);
- Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedOnUtc.HasValue);
- Assert.IsTrue(pUpdated.FirstOrDefault()!.UpdatedBy == "user");
-
- }
- [TestMethod()]
- public async Task UpdateToSet_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
-
- //Act
- await myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key, "key", new Domain.Common.UserField { Key = "key", Value = "update", StoreId = "1" });
- var p = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p.UserFields!.FirstOrDefault(x => x.Key == "key")!.Value == "update");
- Assert.IsTrue(p.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p.UpdatedBy == "user");
-
- }
-
- [TestMethod()]
- public async Task UpdateToSet_2_LiteRepository_Success()
- {
- var myRepository = new LiteDBRepositoryMock<SampleCollection>();
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- } },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test3" }
-
- };
- products.ForEach(x => myRepository.Insert(x));
- //Act
- await myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key == "key", new Domain.Common.UserField { Key = "key", Value = "update", StoreId = "1" });
-
- var p = myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p.UserFields!.FirstOrDefault(x => x.Key == "key")!.Value == "update");
- Assert.IsTrue(p.UpdatedOnUtc.HasValue);
- Assert.IsTrue(p.UpdatedBy == "user");
-
- }
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => myRepository.Insert(x));
+ //Act
+ await myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key == "key",
+ new UserField { Key = "key", Value = "update", StoreId = "1" });
+
+ var p = myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p.UserFields!.FirstOrDefault(x => x.Key == "key")!.Value == "update");
+ Assert.IsTrue(p.UpdatedOnUtc.HasValue);
+ Assert.IsTrue(p.UpdatedBy == "user");
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Data.Tests/MongoDb/CoreTestConfiguration.cs b/src/Tests/Grand.Data.Tests/MongoDb/CoreTestConfiguration.cs
index 05cbd47af..90f8d0f8e 100644
--- a/src/Tests/Grand.Data.Tests/MongoDb/CoreTestConfiguration.cs
+++ b/src/Tests/Grand.Data.Tests/MongoDb/CoreTestConfiguration.cs
@@ -1,17 +1,17 @@
/* Copyright 2010-2015 MongoDB Inc.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
using MongoDB.Driver;
using MongoDB.Driver.Core.Clusters;
@@ -23,253 +23,214 @@ using System.Diagnostics;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
+namespace Grand.Data.Tests.MongoDb;
-namespace Grand.Data.Tests.MongoDb
+public static class CoreTestConfiguration
{
- public static class CoreTestConfiguration
+ public static void TearDown()
{
- #region static
- // static fields
- private static Lazy<ICluster> __cluster = new Lazy<ICluster>(CreateCluster, isThreadSafe: true);
- private static ConnectionString __connectionString = GetConnectionString();
- private static DatabaseNamespace __databaseNamespace = GetDatabaseNamespace();
- private static MessageEncoderSettings __messageEncoderSettings = new MessageEncoderSettings();
- private static TraceSource __traceSource;
+ if (__cluster.IsValueCreated)
+ {
+ // TODO: DropDatabase
+ //DropDatabase();
+ __cluster.Value.Dispose();
+ __cluster = new Lazy<ICluster>(CreateCluster, true);
+ }
+ }
- // static properties
- public static ICluster Cluster => __cluster.Value;
+ #region static
- public static ConnectionString ConnectionString => __connectionString;
+ // static fields
+ private static Lazy<ICluster> __cluster = new(CreateCluster, true);
- public static DatabaseNamespace DatabaseNamespace => __databaseNamespace;
+ // static properties
+ public static ICluster Cluster => __cluster.Value;
- public static MessageEncoderSettings MessageEncoderSettings => __messageEncoderSettings;
+ public static ConnectionString ConnectionString { get; } = GetConnectionString();
- public static TraceSource TraceSource => __traceSource;
+ public static DatabaseNamespace DatabaseNamespace { get; } = GetDatabaseNamespace();
- // static methods
- public static ClusterBuilder ConfigureCluster()
- {
- return ConfigureCluster(new ClusterBuilder());
- }
+ public static MessageEncoderSettings MessageEncoderSettings { get; } = new();
- public static ClusterBuilder ConfigureCluster(ClusterBuilder builder)
- {
- var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
- if (serverSelectionTimeoutString == null)
- {
- serverSelectionTimeoutString = "30000";
- }
+ public static TraceSource TraceSource { get; private set; }
- builder = builder
- .ConfigureWithConnectionString(__connectionString)
- .ConfigureCluster(c => c.With(serverSelectionTimeout: TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString))));
+ // static methods
+ public static ClusterBuilder ConfigureCluster()
+ {
+ return ConfigureCluster(new ClusterBuilder());
+ }
- if (__connectionString.Tls.HasValue && __connectionString.Tls.Value)
- {
- var certificateFilename = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_FILE");
- if (certificateFilename != null)
- {
- builder.ConfigureSsl(ssl =>
- {
- var password = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_PASS");
- X509Certificate cert;
- if (password == null)
- {
- cert = new X509Certificate2(certificateFilename);
- }
- else
- {
- cert = new X509Certificate2(certificateFilename, password);
- }
- return ssl.With(
- clientCertificates: new[] { cert });
- });
- }
- }
+ public static ClusterBuilder ConfigureCluster(ClusterBuilder builder)
+ {
+ var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
+ if (serverSelectionTimeoutString == null) serverSelectionTimeoutString = "30000";
- return ConfigureLogging(builder);
- }
+ builder = builder
+ .ConfigureWithConnectionString(ConnectionString)
+ .ConfigureCluster(c =>
+ c.With(serverSelectionTimeout: TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString))));
- public static ClusterBuilder ConfigureLogging(ClusterBuilder builder)
+ if (ConnectionString.Tls.HasValue && ConnectionString.Tls.Value)
{
- var environmentVariable = Environment.GetEnvironmentVariable("MONGO_LOGGING");
- if (environmentVariable == null)
- {
- return builder;
- }
+ var certificateFilename = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_FILE");
+ if (certificateFilename != null)
+ builder.ConfigureSsl(ssl =>
+ {
+ var password = Environment.GetEnvironmentVariable("MONGO_SSL_CERT_PASS");
+ X509Certificate cert;
+ if (password == null)
+ cert = new X509Certificate2(certificateFilename);
+ else
+ cert = new X509Certificate2(certificateFilename, password);
+ return ssl.With(
+ clientCertificates: new[] { cert });
+ });
+ }
- SourceLevels defaultLevel;
- if (!Enum.TryParse<SourceLevels>(environmentVariable, ignoreCase: true, result: out defaultLevel))
- {
- return builder;
- }
+ return ConfigureLogging(builder);
+ }
- __traceSource = new TraceSource("mongodb-tests", defaultLevel);
- __traceSource.Listeners.Clear();
- return builder.TraceWith(__traceSource);
- }
+ public static ClusterBuilder ConfigureLogging(ClusterBuilder builder)
+ {
+ var environmentVariable = Environment.GetEnvironmentVariable("MONGO_LOGGING");
+ if (environmentVariable == null) return builder;
- public static ICluster CreateCluster()
- {
- var hasWritableServer = 0;
- var builder = ConfigureCluster();
- var cluster = builder.BuildCluster();
- cluster.DescriptionChanged += (o, e) =>
- {
- var anyWritableServer = e.NewClusterDescription.Servers.Any(
- description => description.Type.IsWritable());
- if (__traceSource != null)
- {
- __traceSource.TraceEvent(TraceEventType.Information, 0, "CreateCluster: DescriptionChanged event handler called.");
- __traceSource.TraceEvent(TraceEventType.Information, 0, $"CreateCluster: anyWritableServer = {anyWritableServer}.");
- __traceSource.TraceEvent(TraceEventType.Information, 0, $"CreateCluster: new description: {e.NewClusterDescription}.");
- }
- Interlocked.Exchange(ref hasWritableServer, anyWritableServer ? 1 : 0);
- };
- if (__traceSource != null)
- {
- __traceSource.TraceEvent(TraceEventType.Information, 0, "CreateCluster: initializing cluster.");
- }
- cluster.Initialize();
+ SourceLevels defaultLevel;
+ if (!Enum.TryParse(environmentVariable, true, out defaultLevel)) return builder;
- // wait until the cluster has connected to a writable server
- SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref hasWritableServer, 0, 0) != 0, TimeSpan.FromSeconds(30));
- if (Interlocked.CompareExchange(ref hasWritableServer, 0, 0) == 0)
- {
- var message =
- $"Test cluster has no writable server. Client view of the cluster is {cluster.Description}.";
- throw new Exception(message);
- }
+ TraceSource = new TraceSource("mongodb-tests", defaultLevel);
+ TraceSource.Listeners.Clear();
+ return builder.TraceWith(TraceSource);
+ }
- if (__traceSource != null)
+ public static ICluster CreateCluster()
+ {
+ var hasWritableServer = 0;
+ var builder = ConfigureCluster();
+ var cluster = builder.BuildCluster();
+ cluster.DescriptionChanged += (o, e) =>
+ {
+ var anyWritableServer = e.NewClusterDescription.Servers.Any(
+ description => description.Type.IsWritable());
+ if (TraceSource != null)
{
- __traceSource.TraceEvent(TraceEventType.Information, 0, "CreateCluster: writable server found.");
+ TraceSource.TraceEvent(TraceEventType.Information, 0,
+ "CreateCluster: DescriptionChanged event handler called.");
+ TraceSource.TraceEvent(TraceEventType.Information, 0,
+ $"CreateCluster: anyWritableServer = {anyWritableServer}.");
+ TraceSource.TraceEvent(TraceEventType.Information, 0,
+ $"CreateCluster: new description: {e.NewClusterDescription}.");
}
- return cluster;
- }
+ Interlocked.Exchange(ref hasWritableServer, anyWritableServer ? 1 : 0);
+ };
+ if (TraceSource != null)
+ TraceSource.TraceEvent(TraceEventType.Information, 0, "CreateCluster: initializing cluster.");
+ cluster.Initialize();
- public static CollectionNamespace GetCollectionNamespaceForTestFixture()
+ // wait until the cluster has connected to a writable server
+ SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref hasWritableServer, 0, 0) != 0,
+ TimeSpan.FromSeconds(30));
+ if (Interlocked.CompareExchange(ref hasWritableServer, 0, 0) == 0)
{
- var testFixtureType = GetTestFixtureTypeFromCallStack();
- var collectionName = TruncateCollectionNameIfTooLong(__databaseNamespace, testFixtureType.Name);
- return new CollectionNamespace(__databaseNamespace, collectionName);
+ var message =
+ $"Test cluster has no writable server. Client view of the cluster is {cluster.Description}.";
+ throw new Exception(message);
}
- public static CollectionNamespace GetCollectionNamespaceForTestMethod()
- {
- var testMethodInfo = GetTestMethodInfoFromCallStack();
- var collectionName = TruncateCollectionNameIfTooLong(__databaseNamespace, testMethodInfo.DeclaringType.Name + "-" + testMethodInfo.Name);
- return new CollectionNamespace(__databaseNamespace, collectionName);
- }
+ if (TraceSource != null)
+ TraceSource.TraceEvent(TraceEventType.Information, 0, "CreateCluster: writable server found.");
- private static ConnectionString GetConnectionString()
- {
- return new ConnectionString(Environment.GetEnvironmentVariable("MONGO_URI") ?? "mongodb://localhost");
- }
-
- private static DatabaseNamespace GetDatabaseNamespace()
- {
- if (!string.IsNullOrEmpty(__connectionString.DatabaseName))
- {
- return new DatabaseNamespace(__connectionString.DatabaseName);
- }
+ return cluster;
+ }
- var timestamp = DateTime.Now.ToString("MMddHHmm");
- return new DatabaseNamespace("Tests" + timestamp);
- }
+ public static CollectionNamespace GetCollectionNamespaceForTestFixture()
+ {
+ var testFixtureType = GetTestFixtureTypeFromCallStack();
+ var collectionName = TruncateCollectionNameIfTooLong(DatabaseNamespace, testFixtureType.Name);
+ return new CollectionNamespace(DatabaseNamespace, collectionName);
+ }
- public static DatabaseNamespace GetDatabaseNamespaceForTestFixture()
- {
- var testFixtureType = GetTestFixtureTypeFromCallStack();
- var databaseName = TruncateDatabaseNameIfTooLong(__databaseNamespace.DatabaseName + "-" + testFixtureType.Name);
- if (databaseName.Length >= 64)
- {
- databaseName = databaseName.Substring(0, 63);
- }
- return new DatabaseNamespace(databaseName);
- }
+ public static CollectionNamespace GetCollectionNamespaceForTestMethod()
+ {
+ var testMethodInfo = GetTestMethodInfoFromCallStack();
+ var collectionName = TruncateCollectionNameIfTooLong(DatabaseNamespace,
+ testMethodInfo.DeclaringType.Name + "-" + testMethodInfo.Name);
+ return new CollectionNamespace(DatabaseNamespace, collectionName);
+ }
+ private static ConnectionString GetConnectionString()
+ {
+ return new ConnectionString(Environment.GetEnvironmentVariable("MONGO_URI") ?? "mongodb://localhost");
+ }
+ private static DatabaseNamespace GetDatabaseNamespace()
+ {
+ if (!string.IsNullOrEmpty(ConnectionString.DatabaseName))
+ return new DatabaseNamespace(ConnectionString.DatabaseName);
+ var timestamp = DateTime.Now.ToString("MMddHHmm");
+ return new DatabaseNamespace("Tests" + timestamp);
+ }
- private static Type GetTestFixtureTypeFromCallStack()
- {
- var stackTrace = new StackTrace();
- for (var index = 0; index < stackTrace.FrameCount; index++)
- {
- var frame = stackTrace.GetFrame(index);
- var methodInfo = frame.GetMethod();
- var declaringType = methodInfo.DeclaringType;
- var testFixtureAttribute = declaringType.GetCustomAttribute<TestFixtureAttribute>(inherit: false);
- if (testFixtureAttribute != null)
- {
- return declaringType;
- }
- }
+ public static DatabaseNamespace GetDatabaseNamespaceForTestFixture()
+ {
+ var testFixtureType = GetTestFixtureTypeFromCallStack();
+ var databaseName = TruncateDatabaseNameIfTooLong(DatabaseNamespace.DatabaseName + "-" + testFixtureType.Name);
+ if (databaseName.Length >= 64) databaseName = databaseName.Substring(0, 63);
+ return new DatabaseNamespace(databaseName);
+ }
- throw new Exception("No [TestFixture] found on the call stack.");
- }
- private static MethodInfo GetTestMethodInfoFromCallStack()
+ private static Type GetTestFixtureTypeFromCallStack()
+ {
+ var stackTrace = new StackTrace();
+ for (var index = 0; index < stackTrace.FrameCount; index++)
{
- var stackTrace = new StackTrace();
- for (var index = 0; index < stackTrace.FrameCount; index++)
- {
- var frame = stackTrace.GetFrame(index);
- var methodInfo = frame.GetMethod() as MethodInfo;
- if (methodInfo != null)
- {
- var testAttribute = methodInfo.GetCustomAttribute<TestAttribute>(inherit: false);
- if (testAttribute != null)
- {
- return methodInfo;
- }
- var testCaseAttribute = methodInfo.GetCustomAttribute<TestCaseAttribute>(inherit: false);
- if (testCaseAttribute != null)
- {
- return methodInfo;
- }
- }
- }
-
- throw new Exception("No [TestFixture] found on the call stack.");
+ var frame = stackTrace.GetFrame(index);
+ var methodInfo = frame.GetMethod();
+ var declaringType = methodInfo.DeclaringType;
+ var testFixtureAttribute = declaringType.GetCustomAttribute<TestFixtureAttribute>(false);
+ if (testFixtureAttribute != null) return declaringType;
}
- private static string TruncateCollectionNameIfTooLong(DatabaseNamespace databaseNamespace, string collectionName)
+ throw new Exception("No [TestFixture] found on the call stack.");
+ }
+
+ private static MethodInfo GetTestMethodInfoFromCallStack()
+ {
+ var stackTrace = new StackTrace();
+ for (var index = 0; index < stackTrace.FrameCount; index++)
{
- var fullNameLength = databaseNamespace.DatabaseName.Length + 1 + collectionName.Length;
- if (fullNameLength < 123)
+ var frame = stackTrace.GetFrame(index);
+ var methodInfo = frame.GetMethod() as MethodInfo;
+ if (methodInfo != null)
{
- return collectionName;
+ var testAttribute = methodInfo.GetCustomAttribute<TestAttribute>(false);
+ if (testAttribute != null) return methodInfo;
+ var testCaseAttribute = methodInfo.GetCustomAttribute<TestCaseAttribute>(false);
+ if (testCaseAttribute != null) return methodInfo;
}
-
- var maxCollectionNameLength = 123 - (databaseNamespace.DatabaseName.Length + 1);
- return collectionName.Substring(0, maxCollectionNameLength);
}
- private static string TruncateDatabaseNameIfTooLong(string databaseName)
- {
- if (databaseName.Length < 64)
- {
- return databaseName;
- }
+ throw new Exception("No [TestFixture] found on the call stack.");
+ }
- return databaseName.Substring(0, 63);
- }
- #endregion
+ private static string TruncateCollectionNameIfTooLong(DatabaseNamespace databaseNamespace, string collectionName)
+ {
+ var fullNameLength = databaseNamespace.DatabaseName.Length + 1 + collectionName.Length;
+ if (fullNameLength < 123) return collectionName;
+ var maxCollectionNameLength = 123 - (databaseNamespace.DatabaseName.Length + 1);
+ return collectionName.Substring(0, maxCollectionNameLength);
+ }
- public static void TearDown()
- {
- if (__cluster.IsValueCreated)
- {
- // TODO: DropDatabase
- //DropDatabase();
- __cluster.Value.Dispose();
- __cluster = new Lazy<ICluster>(CreateCluster, isThreadSafe: true);
- }
- }
+ private static string TruncateDatabaseNameIfTooLong(string databaseName)
+ {
+ if (databaseName.Length < 64) return databaseName;
+
+ return databaseName.Substring(0, 63);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Data.Tests/MongoDb/DriverTestConfiguration.cs b/src/Tests/Grand.Data.Tests/MongoDb/DriverTestConfiguration.cs
index b01ee6ade..6deb57a78 100644
--- a/src/Tests/Grand.Data.Tests/MongoDb/DriverTestConfiguration.cs
+++ b/src/Tests/Grand.Data.Tests/MongoDb/DriverTestConfiguration.cs
@@ -1,57 +1,50 @@
-
-using MongoDB.Driver;
+using MongoDB.Driver;
-namespace Grand.Data.Tests.MongoDb
+namespace Grand.Data.Tests.MongoDb;
+
+/// <summary>
+/// A static class to handle online test configuration.
+/// </summary>
+public static class DriverTestConfiguration
{
- /// <summary>
- /// A static class to handle online test configuration.
- /// </summary>
- public static class DriverTestConfiguration
+ // private static fields
+ private static readonly Lazy<MongoClient> __client;
+
+ // static constructor
+ static DriverTestConfiguration()
{
- // private static fields
- private static Lazy<MongoClient> __client;
- private static CollectionNamespace __collectionNamespace;
- private static DatabaseNamespace __databaseNamespace;
-
- // static constructor
- static DriverTestConfiguration()
- {
- var connectionString = CoreTestConfiguration.ConnectionString.ToString();
- var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
-
- var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
- if (serverSelectionTimeoutString == null)
- {
- serverSelectionTimeoutString = "30000";
- }
- clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString));
- clientSettings.ClusterConfigurator = cb => CoreTestConfiguration.ConfigureLogging(cb);
-
- __client = new Lazy<MongoClient>(() => new MongoClient(clientSettings), true);
- __databaseNamespace = CoreTestConfiguration.DatabaseNamespace;
- __collectionNamespace = new CollectionNamespace(__databaseNamespace, "testcollection");
- }
-
- // public static properties
- /// <summary>
- /// Gets the test client.
- /// </summary>
- public static MongoClient Client => __client.Value;
-
- /// <summary>
- /// Gets the collection namespace.
- /// </summary>
- /// <value>
- /// The collection namespace.
- /// </value>
- public static CollectionNamespace CollectionNamespace => __collectionNamespace;
-
- /// <summary>
- /// Gets the database namespace.
- /// </summary>
- /// <value>
- /// The database namespace.
- /// </value>
- public static DatabaseNamespace DatabaseNamespace => __databaseNamespace;
+ var connectionString = CoreTestConfiguration.ConnectionString.ToString();
+ var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
+
+ var serverSelectionTimeoutString = Environment.GetEnvironmentVariable("MONGO_SERVER_SELECTION_TIMEOUT_MS");
+ if (serverSelectionTimeoutString == null) serverSelectionTimeoutString = "30000";
+ clientSettings.ServerSelectionTimeout = TimeSpan.FromMilliseconds(int.Parse(serverSelectionTimeoutString));
+ clientSettings.ClusterConfigurator = cb => CoreTestConfiguration.ConfigureLogging(cb);
+
+ __client = new Lazy<MongoClient>(() => new MongoClient(clientSettings), true);
+ DatabaseNamespace = CoreTestConfiguration.DatabaseNamespace;
+ CollectionNamespace = new CollectionNamespace(DatabaseNamespace, "testcollection");
}
-}
+
+ // public static properties
+ /// <summary>
+ /// Gets the test client.
+ /// </summary>
+ public static MongoClient Client => __client.Value;
+
+ /// <summary>
+ /// Gets the collection namespace.
+ /// </summary>
+ /// <value>
+ /// The collection namespace.
+ /// </value>
+ public static CollectionNamespace CollectionNamespace { get; }
+
+ /// <summary>
+ /// Gets the database namespace.
+ /// </summary>
+ /// <value>
+ /// The database namespace.
+ /// </value>
+ public static DatabaseNamespace DatabaseNamespace { get; }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Data.Tests/MongoDb/MongoDBRepositoryTest.cs b/src/Tests/Grand.Data.Tests/MongoDb/MongoDBRepositoryTest.cs
index 0e8f1a18e..18ecbc289 100644
--- a/src/Tests/Grand.Data.Tests/MongoDb/MongoDBRepositoryTest.cs
+++ b/src/Tests/Grand.Data.Tests/MongoDb/MongoDBRepositoryTest.cs
@@ -1,26 +1,25 @@
-using Grand.Domain;
-using Grand.Data.Mongo;
+using Grand.Data.Mongo;
+using Grand.Domain;
using MongoDB.Bson.Serialization.Conventions;
-namespace Grand.Data.Tests.MongoDb
+namespace Grand.Data.Tests.MongoDb;
+
+public class MongoDBRepositoryTest<T> : MongoRepository<T>, IRepository<T> where T : BaseEntity
{
- public class MongoDBRepositoryTest<T> : MongoRepository<T>, IRepository<T> where T : BaseEntity
+ public MongoDBRepositoryTest() : base(
+ DriverTestConfiguration.Client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName),
+ new AuditInfoProvider())
{
- public MongoDBRepositoryTest():base(DriverTestConfiguration.Client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName), new AuditInfoProvider())
- {
- var cp = new ConventionPack {
- new IgnoreExtraElementsConvention(true)
- };
- ConventionRegistry.Register("ApplicationConventions", cp, t => true);
+ var cp = new ConventionPack {
+ new IgnoreExtraElementsConvention(true)
+ };
+ ConventionRegistry.Register("ApplicationConventions", cp, t => true);
+
+ var client = DriverTestConfiguration.Client;
- var client = DriverTestConfiguration.Client;
-
- _database = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);
- _database.DropCollection(typeof(T).Name);
- _collection = _database.GetCollection<T>(typeof(T).Name);
- }
+ _database = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName);
+ _database.DropCollection(typeof(T).Name);
+ _collection = _database.GetCollection<T>(typeof(T).Name);
}
-
-
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Data.Tests/MongoDb/MongoRepositoryTests.cs b/src/Tests/Grand.Data.Tests/MongoDb/MongoRepositoryTests.cs
index ad5778314..ae3e1c713 100644
--- a/src/Tests/Grand.Data.Tests/MongoDb/MongoRepositoryTests.cs
+++ b/src/Tests/Grand.Data.Tests/MongoDb/MongoRepositoryTests.cs
@@ -1,514 +1,514 @@
-using Grand.SharedKernel.Extensions;
+using Grand.Domain.Common;
+using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Data.Tests.MongoDb
+namespace Grand.Data.Tests.MongoDb;
+
+[TestClass]
+public class MongoRepositoryTests
{
- [TestClass()]
- public class MongoRepositoryTests
+ private IRepository<SampleCollection> _myRepository;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _myRepository = new MongoDBRepositoryTest<SampleCollection>();
+
+ CommonPath.BaseDirectory = "";
+ }
+
+ [TestMethod]
+ public void Insert_MongoRepository_Success()
+ {
+ //Arrange
+ var product = new SampleCollection();
+ //Act
+ _myRepository.Insert(product);
+ //Assert
+ Assert.AreEqual(1, _myRepository.Table.Count());
+ Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedBy == "user");
+ Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedOnUtc.Month == DateTime.UtcNow.Month);
+ Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedOnUtc.Day == DateTime.UtcNow.Day);
+ }
+
+
+ [TestMethod]
+ public async Task GetById_MongoRepository_Success()
+ {
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ await _myRepository.InsertAsync(product);
+
+ //Act
+ var p = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsNotNull(p);
+ }
+
+ [TestMethod]
+ public async Task GetByIdAsync_MongoRepository_Success()
+ {
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ await _myRepository.InsertAsync(product);
+ //Act
+ var p = await _myRepository.GetByIdAsync("1");
+ //Assert
+ Assert.IsNotNull(p);
+ Assert.IsTrue(p!.CreatedBy == "user");
+ Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ }
+
+ [TestMethod]
+ public async Task GetOneAsync_MongoRepository_Success()
+ {
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ await _myRepository.InsertAsync(product);
+ //Act
+ var p = await _myRepository.GetOneAsync(x => x.Id == "1");
+ //Assert
+ Assert.IsNotNull(p);
+ Assert.IsTrue(p!.CreatedBy == "user");
+ Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ }
+
+ [TestMethod]
+ public async Task ClearAsync_MongoRepository_Success()
+ {
+ var product = new SampleCollection { Id = "1" };
+ await _myRepository.InsertAsync(product);
+
+ await _myRepository.ClearAsync();
+
+ Assert.IsTrue(_myRepository.Table.Count() == 0);
+ }
+
+ [TestMethod]
+ public async Task AddToSet_MongoRepository_Success()
+ {
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ await _myRepository.InsertAsync(product);
+
+ await _myRepository.AddToSet("1", x => x.UserFields,
+ new UserField { Key = "key", Value = "value", StoreId = "" });
+
+ //Act
+ await _myRepository.AddToSet("1", x => x.UserFields,
+ new UserField { Key = "key2", Value = "value2", StoreId = "" });
+
+ var p = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p.UserFields.Count == 2);
+ Assert.IsTrue(p!.CreatedBy == "user");
+ Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ Assert.IsTrue(p!.UpdatedBy == "user");
+ Assert.IsTrue(p!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task Delete_MongoRepository_Success()
+ {
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ await _myRepository.InsertAsync(product);
+
+ //Act
+ _myRepository.Delete(product);
+ var p = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsNull(p);
+ }
+
+ [TestMethod]
+ public async Task DeleteAsync_MongoRepository_Success()
+ {
+ //Arrange
+ var product = new SampleCollection { Id = "1" };
+ await _myRepository.InsertAsync(product);
+
+ //Act
+ await _myRepository.DeleteAsync(product);
+ var p = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsNull(p);
+ }
+
+ [TestMethod]
+ public async Task DeleteManyAsync_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() { Id = "1", Name = "Test" },
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test2" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.DeleteManyAsync(x => x.Name == "Test");
+
+ //Assert
+ Assert.IsTrue(_myRepository.Table.Count() == 1);
+ }
+
+ [TestMethod]
+ public async Task Pull_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() {
+ Id = "2", Name = "Test2",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.Pull("1", x => x.Phones, "Phone2");
+
+ var p = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p.Phones.Count == 2);
+ Assert.IsTrue(p!.CreatedBy == "user");
+ Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ Assert.IsTrue(p!.UpdatedBy == "user");
+ Assert.IsTrue(p!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task Pull_Many_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() {
+ Id = "2", Name = "Test2",
+ Phones = new[] { "Phone1", "Phone2", "Phone3" }
+ },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.Pull(string.Empty, x => x.Phones, "Phone2");
+
+ var p1 = _myRepository.GetById("1");
+ var p2 = _myRepository.GetById("2");
+ var p3 = _myRepository.GetById("3");
+
+ //Assert
+ Assert.IsTrue(p1.Phones.Count == 2 && p2.Phones.Count == 2 && p3.Phones.Count == 0);
+ Assert.IsTrue(p1!.CreatedBy == "user");
+ Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task PullFilter_1_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value == "value");
+
+ var p1 = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.UserFields.Count == 1);
+ Assert.IsTrue(p1!.CreatedBy == "user");
+ Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task PullFilter_2_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value, "value");
+
+ var p1 = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.UserFields.Count == 1);
+ Assert.IsTrue(p1!.CreatedBy == "user");
+ Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task PullFilter_2_Many_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() {
+ Id = "2", Name = "Test2",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value1", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.PullFilter(string.Empty, x => x.UserFields, x => x.Value, "value");
+
+ var p1 = _myRepository.GetById("1");
+ var p2 = _myRepository.GetById("2");
+
+ //Assert
+ Assert.IsTrue(p1.UserFields.Count == 1 && p2.UserFields.Count == 2);
+ Assert.IsTrue(p1!.CreatedBy == "user");
+ Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+
+ [TestMethod]
+ public void Update_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ var p1_update = products.FirstOrDefault();
+ p1_update.Name = "update";
+
+ //Act
+ _myRepository.Update(p1_update);
+ var p1 = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.Name == "update");
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task UpdateAsync_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ var p1_update = products.FirstOrDefault();
+ p1_update.Name = "update";
+ //Act
+ await _myRepository.UpdateAsync(p1_update);
+ var p1 = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.Name == "update");
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task UpdateField_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test2" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.UpdateField("1", x => x.Name, "update");
+ var p1 = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p1.Name == "update");
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task IncField_MongoRepository_Success()
+ {
+ var sample = new SampleCollection { Id = "1", Name = "Test" };
+ await _myRepository.InsertAsync(sample);
+
+ await _myRepository.IncField("1", x => x.Count, 1);
+ await _myRepository.IncField("1", x => x.Count, 1);
+ await _myRepository.IncField("1", x => x.Count, 1);
+
+ var p1 = _myRepository.GetById("1");
+
+ Assert.IsTrue(p1.Count == 3);
+ }
+
+ [TestMethod]
+ public async Task UpdateManyAsync_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+ //Act
+ await _myRepository.UpdateManyAsync(x => x.Name == "Test",
+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
+ var pUpdated = _myRepository.Table.Where(x => x.Name == "UpdateTest");
+ var p1 = pUpdated.FirstOrDefault();
+ //Assert
+ Assert.IsTrue(pUpdated.Count() == 2);
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task UpdateOneAsync_MongoRepository_Success()
+ {
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+
+ //Act
+ await _myRepository.UpdateOneAsync(x => x.Name == "Test",
+ UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
+
+ var pUpdated = _myRepository.Table.Where(x => x.Name == "UpdateTest");
+ var p1 = pUpdated.FirstOrDefault();
+ //Assert
+ Assert.IsTrue(pUpdated.Count() == 1);
+ Assert.IsTrue(p1!.UpdatedBy == "user");
+ Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
+ }
+
+ [TestMethod]
+ public async Task UpdateToSet_MongoRepository_Success()
{
- private IRepository<SampleCollection> _myRepository;
-
- [TestInitialize()]
- public void Init()
- {
- _myRepository = new MongoDBRepositoryTest<SampleCollection>();
-
- CommonPath.BaseDirectory = "";
- }
-
- [TestMethod()]
- public void Insert_MongoRepository_Success()
- {
- //Arrange
- var product = new SampleCollection();
- //Act
- _myRepository.Insert(product);
- //Assert
- Assert.AreEqual(1, _myRepository.Table.Count());
- Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedBy == "user");
- Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedOnUtc.Month == DateTime.UtcNow.Month);
- Assert.IsTrue(_myRepository.Table.FirstOrDefault()!.CreatedOnUtc.Day == DateTime.UtcNow.Day);
- }
-
-
- [TestMethod()]
- public async Task GetById_MongoRepository_Success()
- {
- //Arrange
- var product = new SampleCollection { Id = "1" };
- await _myRepository.InsertAsync(product);
-
- //Act
- var p = _myRepository.GetById("1");
-
- //Assert
- Assert.IsNotNull(p);
- }
-
- [TestMethod()]
- public async Task GetByIdAsync_MongoRepository_Success()
- {
- //Arrange
- var product = new SampleCollection { Id = "1" };
- await _myRepository.InsertAsync(product);
- //Act
- var p = await _myRepository.GetByIdAsync("1");
- //Assert
- Assert.IsNotNull(p);
- Assert.IsTrue(p!.CreatedBy == "user");
- Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- }
-
- [TestMethod()]
- public async Task GetOneAsync_MongoRepository_Success()
- {
- //Arrange
- var product = new SampleCollection { Id = "1" };
- await _myRepository.InsertAsync(product);
- //Act
- var p = await _myRepository.GetOneAsync(x => x.Id == "1");
- //Assert
- Assert.IsNotNull(p);
- Assert.IsTrue(p!.CreatedBy == "user");
- Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- }
-
- [TestMethod()]
- public async Task ClearAsync_MongoRepository_Success()
- {
- var product = new SampleCollection { Id = "1" };
- await _myRepository.InsertAsync(product);
-
- await _myRepository.ClearAsync();
-
- Assert.IsTrue(_myRepository.Table.Count() == 0);
- }
-
- [TestMethod()]
- public async Task AddToSet_MongoRepository_Success()
- {
- //Arrange
- var product = new SampleCollection { Id = "1" };
- await _myRepository.InsertAsync(product);
-
- await _myRepository.AddToSet("1", x => x.UserFields,
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" });
-
- //Act
- await _myRepository.AddToSet("1", x => x.UserFields,
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" });
-
- var p = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p.UserFields.Count == 2);
- Assert.IsTrue(p!.CreatedBy == "user");
- Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- Assert.IsTrue(p!.UpdatedBy == "user");
- Assert.IsTrue(p!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task Delete_MongoRepository_Success()
- {
- //Arrange
- var product = new SampleCollection { Id = "1" };
- await _myRepository.InsertAsync(product);
-
- //Act
- _myRepository.Delete(product);
- var p = _myRepository.GetById("1");
-
- //Assert
- Assert.IsNull(p);
- }
-
- [TestMethod()]
- public async Task DeleteAsync_MongoRepository_Success()
- {
- //Arrange
- var product = new SampleCollection { Id = "1" };
- await _myRepository.InsertAsync(product);
-
- //Act
- await _myRepository.DeleteAsync(product);
- var p = _myRepository.GetById("1");
-
- //Assert
- Assert.IsNull(p);
- }
-
- [TestMethod()]
- public async Task DeleteManyAsync_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection { Id = "1", Name = "Test" },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test2" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.DeleteManyAsync(x => x.Name == "Test");
-
- //Assert
- Assert.IsTrue(_myRepository.Table.Count() == 1);
- }
-
- [TestMethod()]
- public async Task Pull_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- Phones = new[] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection {
- Id = "2", Name = "Test2",
- Phones = new[] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.Pull("1", x => x.Phones, "Phone2");
-
- var p = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p.Phones.Count == 2);
- Assert.IsTrue(p!.CreatedBy == "user");
- Assert.IsTrue(p!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- Assert.IsTrue(p!.UpdatedBy == "user");
- Assert.IsTrue(p!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task Pull_Many_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- Phones = new[] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection {
- Id = "2", Name = "Test2",
- Phones = new[] { "Phone1", "Phone2", "Phone3" }
- },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.Pull(String.Empty, x => x.Phones, "Phone2");
-
- var p1 = _myRepository.GetById("1");
- var p2 = _myRepository.GetById("2");
- var p3 = _myRepository.GetById("3");
-
- //Assert
- Assert.IsTrue(p1.Phones.Count == 2 && p2.Phones.Count == 2 && p3.Phones.Count == 0);
- Assert.IsTrue(p1!.CreatedBy == "user");
- Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task PullFilter_1_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value == "value");
-
- var p1 = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.UserFields.Count == 1);
- Assert.IsTrue(p1!.CreatedBy == "user");
- Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task PullFilter_2_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.PullFilter("1", x => x.UserFields, x => x.Value, "value");
-
- var p1 = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.UserFields.Count == 1);
- Assert.IsTrue(p1!.CreatedBy == "user");
- Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task PullFilter_2_Many_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection {
- Id = "2", Name = "Test2",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value1", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.PullFilter(String.Empty, x => x.UserFields, x => x.Value, "value");
-
- var p1 = _myRepository.GetById("1");
- var p2 = _myRepository.GetById("2");
-
- //Assert
- Assert.IsTrue(p1.UserFields.Count == 1 && p2.UserFields.Count == 2);
- Assert.IsTrue(p1!.CreatedBy == "user");
- Assert.IsTrue(p1!.CreatedOnUtc.Year == DateTime.UtcNow.Year);
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
-
- [TestMethod()]
- public void Update_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- var p1_update = products.FirstOrDefault();
- p1_update.Name = "update";
-
- //Act
- _myRepository.Update(p1_update);
- var p1 = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.Name == "update");
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task UpdateAsync_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- var p1_update = products.FirstOrDefault();
- p1_update.Name = "update";
- //Act
- await _myRepository.UpdateAsync(p1_update);
- var p1 = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.Name == "update");
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task UpdateField_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test2" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.UpdateField("1", x => x.Name, "update");
- var p1 = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p1.Name == "update");
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task IncField_MongoRepository_Success()
- {
- var sample = new SampleCollection { Id = "1", Name = "Test" };
- await _myRepository.InsertAsync(sample);
-
- await _myRepository.IncField("1", x => x.Count, 1);
- await _myRepository.IncField("1", x => x.Count, 1);
- await _myRepository.IncField("1", x => x.Count, 1);
-
- var p1 = _myRepository.GetById("1");
-
- Assert.IsTrue(p1.Count == 3);
- }
-
- [TestMethod()]
- public async Task UpdateManyAsync_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
- //Act
- await _myRepository.UpdateManyAsync(x => x.Name == "Test",
- UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
- var pUpdated = _myRepository.Table.Where(x => x.Name == "UpdateTest");
- var p1 = pUpdated.FirstOrDefault();
- //Assert
- Assert.IsTrue(pUpdated.Count() == 2);
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task UpdateOneAsync_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
-
- //Act
- await _myRepository.UpdateOneAsync(x => x.Name == "Test",
- UpdateBuilder<SampleCollection>.Create().Set(x => x.Name, "UpdateTest"));
-
- var pUpdated = _myRepository.Table.Where(x => x.Name == "UpdateTest");
- var p1 = pUpdated.FirstOrDefault();
- //Assert
- Assert.IsTrue(pUpdated.Count() == 1);
- Assert.IsTrue(p1!.UpdatedBy == "user");
- Assert.IsTrue(p1!.UpdatedOnUtc.HasValue);
- }
-
- [TestMethod()]
- public async Task UpdateToSet_MongoRepository_Success()
- {
- //Arrange
- var products = new List<SampleCollection> {
- new SampleCollection {
- Id = "1", Name = "Test",
- UserFields = new List<Domain.Common.UserField> {
- new Domain.Common.UserField { Key = "key", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key1", Value = "value", StoreId = "" },
- new Domain.Common.UserField { Key = "key2", Value = "value2", StoreId = "" }
- }
- },
- new SampleCollection { Id = "2", Name = "Test" },
- new SampleCollection { Id = "3", Name = "Test3" }
- };
- products.ForEach(x => _myRepository.Insert(x));
- //Act
- await _myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key, "key",
- new Domain.Common.UserField { Key = "key", Value = "update", StoreId = "1" });
- var p = _myRepository.GetById("1");
-
- //Assert
- Assert.IsTrue(p.UserFields.FirstOrDefault(x => x.Key == "key")!.Value == "update");
- Assert.IsTrue(p!.UpdatedBy == "user");
- Assert.IsTrue(p!.UpdatedOnUtc.HasValue);
- }
+ //Arrange
+ var products = new List<SampleCollection> {
+ new() {
+ Id = "1", Name = "Test",
+ UserFields = new List<UserField> {
+ new() { Key = "key", Value = "value", StoreId = "" },
+ new() { Key = "key1", Value = "value", StoreId = "" },
+ new() { Key = "key2", Value = "value2", StoreId = "" }
+ }
+ },
+ new() { Id = "2", Name = "Test" },
+ new() { Id = "3", Name = "Test3" }
+ };
+ products.ForEach(x => _myRepository.Insert(x));
+ //Act
+ await _myRepository.UpdateToSet("1", x => x.UserFields, z => z.Key, "key",
+ new UserField { Key = "key", Value = "update", StoreId = "1" });
+ var p = _myRepository.GetById("1");
+
+ //Assert
+ Assert.IsTrue(p.UserFields.FirstOrDefault(x => x.Key == "key")!.Value == "update");
+ Assert.IsTrue(p!.UpdatedBy == "user");
+ Assert.IsTrue(p!.UpdatedOnUtc.HasValue);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Data.Tests/SampleCollection.cs b/src/Tests/Grand.Data.Tests/SampleCollection.cs
index e2bba1d24..907593fbc 100644
--- a/src/Tests/Grand.Data.Tests/SampleCollection.cs
+++ b/src/Tests/Grand.Data.Tests/SampleCollection.cs
@@ -1,21 +1,19 @@
using Grand.Domain;
-namespace Grand.Data.Tests
-{
- public class SampleCollection : BaseEntity
- {
- public string Name { get; set; }
+namespace Grand.Data.Tests;
- public int Count { get; set; }
- public IList<string> Phones { get; set; } = new List<string>();
+public class SampleCollection : BaseEntity
+{
+ public string Name { get; set; }
- public IList<SampleCategory> Category { get; set; } = new List<SampleCategory>();
+ public int Count { get; set; }
+ public IList<string> Phones { get; set; } = new List<string>();
- public class SampleCategory
- {
- public string Name { get; set; }
- public int DisplayOrder { get; set; }
- }
+ public IList<SampleCategory> Category { get; set; } = new List<SampleCategory>();
+ public class SampleCategory
+ {
+ public string Name { get; set; }
+ public int DisplayOrder { get; set; }
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Blogs/BlogExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Blogs/BlogExtensionsTests.cs
index ea4bbd963..d6be275c9 100644
--- a/src/Tests/Grand.Domain.Tests/Blogs/BlogExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Blogs/BlogExtensionsTests.cs
@@ -1,30 +1,29 @@
using Grand.Domain.Blogs;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Blogs
+namespace Grand.Domain.Tests.Blogs;
+
+[TestClass]
+public class BlogExtensionsTests
{
- [TestClass()]
- public class BlogExtensionsTests
+ [TestMethod]
+ public void ParseTagsTest()
{
- [TestMethod()]
- public void ParseTagsTest()
- {
- var blogPost = new BlogPost {
- Tags = "e-commerce, blog, moey"
- };
+ var blogPost = new BlogPost {
+ Tags = "e-commerce, blog, moey"
+ };
- Assert.AreEqual(3, blogPost.ParseTags().Length);
- }
+ Assert.AreEqual(3, blogPost.ParseTags().Length);
+ }
- [TestMethod()]
- public void GetPostsByDateTest()
- {
- var blogPosts = new List<BlogPost> {
- new BlogPost { StartDateUtc = new DateTime(2010,01,01) },
- new BlogPost { StartDateUtc = new DateTime(2010,02,01) },
- new BlogPost { StartDateUtc = new DateTime(2010,03,01) }
- };
- Assert.AreEqual(2, blogPosts.GetPostsByDate(new DateTime(2010, 01, 01), new DateTime(2010, 02, 28)).Count);
- }
+ [TestMethod]
+ public void GetPostsByDateTest()
+ {
+ var blogPosts = new List<BlogPost> {
+ new() { StartDateUtc = new DateTime(2010, 01, 01) },
+ new() { StartDateUtc = new DateTime(2010, 02, 01) },
+ new() { StartDateUtc = new DateTime(2010, 03, 01) }
+ };
+ Assert.AreEqual(2, blogPosts.GetPostsByDate(new DateTime(2010, 01, 01), new DateTime(2010, 02, 28)).Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Catalog/TierPriceExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Catalog/TierPriceExtensionsTests.cs
index 06ff38a8c..466a879f6 100644
--- a/src/Tests/Grand.Domain.Tests/Catalog/TierPriceExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Catalog/TierPriceExtensionsTests.cs
@@ -1,126 +1,124 @@
using Grand.Domain.Catalog;
+using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Catalog
-{
- [TestClass()]
- public class TierPriceExtensionsTests
- {
- private IList<TierPrice> _tierPrices;
+namespace Grand.Domain.Tests.Catalog;
- public TierPriceExtensionsTests()
- {
- _tierPrices = new List<TierPrice>();
- _tierPrices.Add(new TierPrice {
- CurrencyCode = "USD",
- CustomerGroupId = null,
- Price = 10,
- Quantity = 1,
- StoreId = "1"
- });
- _tierPrices.Add(new TierPrice {
- CurrencyCode = "USD",
- CustomerGroupId = "1",
- Price = 12,
- Quantity = 1,
- StoreId = "1"
- });
- _tierPrices.Add(new TierPrice {
- CurrencyCode = "USD",
- CustomerGroupId = "2",
- Price = 10,
- Quantity = 1,
- StoreId = "2",
- EndDateTimeUtc = DateTime.UtcNow.AddDays(1)
- });
- _tierPrices.Add(new TierPrice {
- CurrencyCode = "EUR",
- CustomerGroupId = "3",
- Price = 10,
- Quantity = 1,
- StoreId = "3",
- StartDateTimeUtc = DateTime.UtcNow
- });
-
- }
+[TestClass]
+public class TierPriceExtensionsTests
+{
+ private readonly IList<TierPrice> _tierPrices;
- [TestMethod()]
- public void FilterByDateTest()
- {
- Assert.AreEqual(3, _tierPrices.FilterByDate(new DateTime(2010, 01, 01)).Count());
+ public TierPriceExtensionsTests()
+ {
+ _tierPrices = new List<TierPrice>();
+ _tierPrices.Add(new TierPrice {
+ CurrencyCode = "USD",
+ CustomerGroupId = null,
+ Price = 10,
+ Quantity = 1,
+ StoreId = "1"
+ });
+ _tierPrices.Add(new TierPrice {
+ CurrencyCode = "USD",
+ CustomerGroupId = "1",
+ Price = 12,
+ Quantity = 1,
+ StoreId = "1"
+ });
+ _tierPrices.Add(new TierPrice {
+ CurrencyCode = "USD",
+ CustomerGroupId = "2",
+ Price = 10,
+ Quantity = 1,
+ StoreId = "2",
+ EndDateTimeUtc = DateTime.UtcNow.AddDays(1)
+ });
+ _tierPrices.Add(new TierPrice {
+ CurrencyCode = "EUR",
+ CustomerGroupId = "3",
+ Price = 10,
+ Quantity = 1,
+ StoreId = "3",
+ StartDateTimeUtc = DateTime.UtcNow
+ });
+ }
- }
+ [TestMethod]
+ public void FilterByDateTest()
+ {
+ Assert.AreEqual(3, _tierPrices.FilterByDate(new DateTime(2010, 01, 01)).Count());
+ }
- [TestMethod()]
- public void FilterByStoreTest()
- {
- Assert.AreEqual(2, _tierPrices.FilterByStore("1").Count());
- }
+ [TestMethod]
+ public void FilterByStoreTest()
+ {
+ Assert.AreEqual(2, _tierPrices.FilterByStore("1").Count());
+ }
- [TestMethod()]
- public void FilterForCustomerTest()
- {
- var customer = new Domain.Customers.Customer();
- customer.Groups.Add("1");
- customer.Groups.Add("2");
- Assert.AreEqual(3, _tierPrices.FilterForCustomer(customer).Count());
- }
+ [TestMethod]
+ public void FilterForCustomerTest()
+ {
+ var customer = new Customer();
+ customer.Groups.Add("1");
+ customer.Groups.Add("2");
+ Assert.AreEqual(3, _tierPrices.FilterForCustomer(customer).Count());
+ }
- [TestMethod()]
- public void FilterByCurrencyTest()
- {
- Assert.AreEqual(3, _tierPrices.FilterByCurrency("USD").Count());
- }
+ [TestMethod]
+ public void FilterByCurrencyTest()
+ {
+ Assert.AreEqual(3, _tierPrices.FilterByCurrency("USD").Count());
+ }
- [TestMethod()]
- public void RemoveDuplicatedQuantitiesTest()
- {
- var tierPrices = new List<TierPrice>();
- tierPrices.Add(new TierPrice {
- //will be removed
- Id = "1",
- Price = 150,
- Quantity = 1
- });
- tierPrices.Add(new TierPrice {
- //will stay
- Id = "2",
- Price = 100,
- Quantity = 1
- });
- tierPrices.Add(new TierPrice {
- //will stay
- Id = "3",
- Price = 200,
- Quantity = 3
- });
- tierPrices.Add(new TierPrice {
- //will stay
- Id = "4",
- Price = 250,
- Quantity = 4
- });
- tierPrices.Add(new TierPrice {
- //will be removed
- Id = "5",
- Price = 300,
- Quantity = 4
- });
- tierPrices.Add(new TierPrice {
- //will stay
- Id = "6",
- Price = 350,
- Quantity = 5
- });
+ [TestMethod]
+ public void RemoveDuplicatedQuantitiesTest()
+ {
+ var tierPrices = new List<TierPrice>();
+ tierPrices.Add(new TierPrice {
+ //will be removed
+ Id = "1",
+ Price = 150,
+ Quantity = 1
+ });
+ tierPrices.Add(new TierPrice {
+ //will stay
+ Id = "2",
+ Price = 100,
+ Quantity = 1
+ });
+ tierPrices.Add(new TierPrice {
+ //will stay
+ Id = "3",
+ Price = 200,
+ Quantity = 3
+ });
+ tierPrices.Add(new TierPrice {
+ //will stay
+ Id = "4",
+ Price = 250,
+ Quantity = 4
+ });
+ tierPrices.Add(new TierPrice {
+ //will be removed
+ Id = "5",
+ Price = 300,
+ Quantity = 4
+ });
+ tierPrices.Add(new TierPrice {
+ //will stay
+ Id = "6",
+ Price = 350,
+ Quantity = 5
+ });
- var tierPriceCollection = tierPrices.RemoveDuplicatedQuantities();
+ var tierPriceCollection = tierPrices.RemoveDuplicatedQuantities();
- Assert.IsNull(tierPriceCollection.FirstOrDefault(v => v.Id == "1"));
- Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "2")); //doubled 15 - saved
- Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "3")); //! doubled 15 - removed
- Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "4")); //doubled 23 - saved
- Assert.IsNull(tierPriceCollection.FirstOrDefault(v => v.Id == "5"));
- Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "6")); //! doubled 23 - removed }
- }
+ Assert.IsNull(tierPriceCollection.FirstOrDefault(v => v.Id == "1"));
+ Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "2")); //doubled 15 - saved
+ Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "3")); //! doubled 15 - removed
+ Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "4")); //doubled 23 - saved
+ Assert.IsNull(tierPriceCollection.FirstOrDefault(v => v.Id == "5"));
+ Assert.IsNotNull(tierPriceCollection.FirstOrDefault(v => v.Id == "6")); //! doubled 23 - removed }
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Common/AddressAttributeExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Common/AddressAttributeExtensionsTests.cs
index cd608d622..09abd51e4 100644
--- a/src/Tests/Grand.Domain.Tests/Common/AddressAttributeExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Common/AddressAttributeExtensionsTests.cs
@@ -2,43 +2,42 @@
using Grand.Domain.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Common
+namespace Grand.Domain.Tests.Common;
+
+[TestClass]
+public class AddressAttributeExtensionsTests
{
- [TestClass()]
- public class AddressAttributeExtensionsTests
+ [TestMethod]
+ public void ShouldHaveValues_NullAddressAtribute_ReturnFalse()
{
- [TestMethod()]
- public void ShouldHaveValues_NullAddressAtribute_ReturnFalse()
- {
- AddressAttribute addressAttribute = null;
- Assert.IsFalse(addressAttribute.ShouldHaveValues());
- }
+ AddressAttribute addressAttribute = null;
+ Assert.IsFalse(addressAttribute.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues__ReturnFalse()
- {
- AddressAttribute addressAttribute = new AddressAttribute { AttributeControlType = AttributeControlType.TextBox };
- AddressAttribute addressAttribute2 = new AddressAttribute { AttributeControlType = AttributeControlType.MultilineTextbox };
- AddressAttribute addressAttribute3 = new AddressAttribute { AttributeControlType = AttributeControlType.Datepicker };
- AddressAttribute addressAttribute4 = new AddressAttribute { AttributeControlType = AttributeControlType.FileUpload };
- Assert.IsFalse(addressAttribute.ShouldHaveValues());
- Assert.IsFalse(addressAttribute2.ShouldHaveValues());
- Assert.IsFalse(addressAttribute3.ShouldHaveValues());
- Assert.IsFalse(addressAttribute4.ShouldHaveValues());
- }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnFalse()
+ {
+ var addressAttribute = new AddressAttribute { AttributeControlType = AttributeControlType.TextBox };
+ var addressAttribute2 = new AddressAttribute { AttributeControlType = AttributeControlType.MultilineTextbox };
+ var addressAttribute3 = new AddressAttribute { AttributeControlType = AttributeControlType.Datepicker };
+ var addressAttribute4 = new AddressAttribute { AttributeControlType = AttributeControlType.FileUpload };
+ Assert.IsFalse(addressAttribute.ShouldHaveValues());
+ Assert.IsFalse(addressAttribute2.ShouldHaveValues());
+ Assert.IsFalse(addressAttribute3.ShouldHaveValues());
+ Assert.IsFalse(addressAttribute4.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues__ReturnTrue()
- {
- AddressAttribute addressAttribute = new AddressAttribute { AttributeControlType = AttributeControlType.DropdownList };
- AddressAttribute addressAttribute2 = new AddressAttribute { AttributeControlType = AttributeControlType.ImageSquares };
- AddressAttribute addressAttribute3 = new AddressAttribute { AttributeControlType = AttributeControlType.RadioList };
- AddressAttribute addressAttribute4 = new AddressAttribute { AttributeControlType = AttributeControlType.ReadonlyCheckboxes };
- Assert.IsTrue(addressAttribute.ShouldHaveValues());
- Assert.IsTrue(addressAttribute2.ShouldHaveValues());
- Assert.IsTrue(addressAttribute3.ShouldHaveValues());
- Assert.IsTrue(addressAttribute4.ShouldHaveValues());
- }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnTrue()
+ {
+ var addressAttribute = new AddressAttribute { AttributeControlType = AttributeControlType.DropdownList };
+ var addressAttribute2 = new AddressAttribute { AttributeControlType = AttributeControlType.ImageSquares };
+ var addressAttribute3 = new AddressAttribute { AttributeControlType = AttributeControlType.RadioList };
+ var addressAttribute4 = new AddressAttribute { AttributeControlType = AttributeControlType.ReadonlyCheckboxes };
+ Assert.IsTrue(addressAttribute.ShouldHaveValues());
+ Assert.IsTrue(addressAttribute2.ShouldHaveValues());
+ Assert.IsTrue(addressAttribute3.ShouldHaveValues());
+ Assert.IsTrue(addressAttribute4.ShouldHaveValues());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Common/AddressExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Common/AddressExtensionsTests.cs
index dc94c6d98..d17c68535 100644
--- a/src/Tests/Grand.Domain.Tests/Common/AddressExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Common/AddressExtensionsTests.cs
@@ -1,36 +1,36 @@
using Grand.Domain.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Common
+namespace Grand.Domain.Tests.Common;
+
+[TestClass]
+public class AddressExtensionsTests
{
- [TestClass()]
- public class AddressExtensionsTests
+ [TestMethod]
+ public void FindAddressTest_NotNull()
+ {
+ var addresses = new List<Address> {
+ new() { Address1 = "address1", Address2 = "address11", FirstName = "name1", LastName = "namelast1" },
+ new() { Address1 = "address2", Address2 = "address12", FirstName = "name2", LastName = "namelast2" },
+ new() { Address1 = "address3", Address2 = "address13", FirstName = "name3", LastName = "namelast3" },
+ new() { Address1 = "address4", Address2 = "address14", FirstName = "name4", LastName = "namelast4" }
+ };
+ var address = addresses.FindAddress("name1", "namelast1", string.Empty, string.Empty, string.Empty,
+ string.Empty, "address1", "address11", string.Empty, string.Empty, string.Empty, string.Empty);
+ Assert.IsNotNull(address);
+ }
+
+ [TestMethod]
+ public void FindAddressTest_IsNull()
{
- [TestMethod()]
- public void FindAddressTest_NotNull()
- {
- var addresses = new List<Address> {
- new Address { Address1 = "address1", Address2 = "address11", FirstName = "name1", LastName = "namelast1" },
- new Address { Address1 = "address2", Address2 = "address12", FirstName = "name2", LastName = "namelast2" },
- new Address { Address1 = "address3", Address2 = "address13", FirstName = "name3", LastName = "namelast3" },
- new Address { Address1 = "address4", Address2 = "address14", FirstName = "name4", LastName = "namelast4" }
- };
- var address = addresses.FindAddress("name1", "namelast1", string.Empty, string.Empty, string.Empty,
- string.Empty, "address1", "address11", string.Empty, string.Empty, string.Empty, string.Empty);
- Assert.IsNotNull(address);
- }
- [TestMethod()]
- public void FindAddressTest_IsNull()
- {
- var addresses = new List<Address> {
- new Address { Address1 = "address1", Address2 = "address11", FirstName = "name1", LastName = "namelast1" },
- new Address { Address1 = "address2", Address2 = "address12", FirstName = "name2", LastName = "namelast2" },
- new Address { Address1 = "address3", Address2 = "address13", FirstName = "name3", LastName = "namelast3" },
- new Address { Address1 = "address4", Address2 = "address14", FirstName = "name4", LastName = "namelast4" }
- };
- var address = addresses.FindAddress("name1", "namelast1", string.Empty, string.Empty, string.Empty,
- string.Empty, "address1", "address2", "city", string.Empty, string.Empty, string.Empty);
- Assert.IsNull(address);
- }
+ var addresses = new List<Address> {
+ new() { Address1 = "address1", Address2 = "address11", FirstName = "name1", LastName = "namelast1" },
+ new() { Address1 = "address2", Address2 = "address12", FirstName = "name2", LastName = "namelast2" },
+ new() { Address1 = "address3", Address2 = "address13", FirstName = "name3", LastName = "namelast3" },
+ new() { Address1 = "address4", Address2 = "address14", FirstName = "name4", LastName = "namelast4" }
+ };
+ var address = addresses.FindAddress("name1", "namelast1", string.Empty, string.Empty, string.Empty,
+ string.Empty, "address1", "address2", "city", string.Empty, string.Empty, string.Empty);
+ Assert.IsNull(address);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Common/UserFieldExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Common/UserFieldExtensionsTests.cs
index 37d796033..4f57f336e 100644
--- a/src/Tests/Grand.Domain.Tests/Common/UserFieldExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Common/UserFieldExtensionsTests.cs
@@ -1,46 +1,49 @@
using Grand.Domain.Common;
+using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Common
+namespace Grand.Domain.Tests.Common;
+
+[TestClass]
+public class UserFieldExtensionsTests
{
- [TestClass()]
- public class UserFieldExtensionsTests
+ private readonly Customer entity;
+
+ public UserFieldExtensionsTests()
+ {
+ entity = new Customer();
+ entity.UserFields.Add(new UserField { Key = "FirstName", Value = "Sara", StoreId = "" });
+ entity.UserFields.Add(new UserField { Key = "LastName", Value = "Name", StoreId = "" });
+ entity.UserFields.Add(new UserField { Key = "Registered", Value = "1", StoreId = "1" });
+ }
+
+ [TestMethod]
+ public void GetUserFieldFromEntityTest_FirstName_NotNull()
+ {
+ var userField = entity.GetUserFieldFromEntity<string>("FirstName");
+ Assert.IsNotNull(userField);
+ Assert.AreEqual(userField, "Sara");
+ }
+
+ [TestMethod]
+ public void GetUserFieldFromEntityTest_City_IsNull()
{
- private Domain.Customers.Customer entity;
+ var userField = entity.GetUserFieldFromEntity<string>("City");
+ Assert.IsNull(userField);
+ }
- public UserFieldExtensionsTests()
- {
- entity = new Domain.Customers.Customer();
- entity.UserFields.Add(new UserField { Key = "FirstName", Value = "Sara", StoreId = "" });
- entity.UserFields.Add(new UserField { Key = "LastName", Value = "Name", StoreId = "" });
- entity.UserFields.Add(new UserField { Key = "Registered", Value = "1", StoreId = "1" });
- }
+ [TestMethod]
+ public void GetUserFieldFromEntityTest_Registered_Store_NotNull()
+ {
+ var userField = entity.GetUserFieldFromEntity<string>("Registered", "1");
+ Assert.IsNotNull(userField);
+ Assert.AreEqual(userField, "1");
+ }
- [TestMethod()]
- public void GetUserFieldFromEntityTest_FirstName_NotNull()
- {
- var userField = entity.GetUserFieldFromEntity<string>("FirstName");
- Assert.IsNotNull(userField);
- Assert.AreEqual(userField, "Sara");
- }
- [TestMethod()]
- public void GetUserFieldFromEntityTest_City_IsNull()
- {
- var userField = entity.GetUserFieldFromEntity<string>("City");
- Assert.IsNull(userField);
- }
- [TestMethod()]
- public void GetUserFieldFromEntityTest_Registered_Store_NotNull()
- {
- var userField = entity.GetUserFieldFromEntity<string>("Registered", "1");
- Assert.IsNotNull(userField);
- Assert.AreEqual(userField, "1");
- }
- [TestMethod()]
- public void GetUserFieldFromEntityTest_Registered_Store_Null()
- {
- var userField = entity.GetUserFieldFromEntity<string>("Registered", "2");
- Assert.IsNull(userField);
- }
+ [TestMethod]
+ public void GetUserFieldFromEntityTest_Registered_Store_Null()
+ {
+ var userField = entity.GetUserFieldFromEntity<string>("Registered", "2");
+ Assert.IsNull(userField);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Customers/CustomerAttributeExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Customers/CustomerAttributeExtensionsTests.cs
index 7c1337b93..637afbe44 100644
--- a/src/Tests/Grand.Domain.Tests/Customers/CustomerAttributeExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Customers/CustomerAttributeExtensionsTests.cs
@@ -2,43 +2,44 @@
using Grand.Domain.Customers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Customers
+namespace Grand.Domain.Tests.Customers;
+
+[TestClass]
+public class CustomerAttributeExtensionsTests
{
- [TestClass()]
- public class CustomerAttributeExtensionsTests
+ [TestMethod]
+ public void ShouldHaveValues_NullCustomerAttribute_ReturnFalse()
{
- [TestMethod()]
- public void ShouldHaveValues_NullCustomerAttribute_ReturnFalse()
- {
- CustomerAttribute customerAttribute = null;
- Assert.IsFalse(customerAttribute.ShouldHaveValues());
- }
+ CustomerAttribute customerAttribute = null;
+ Assert.IsFalse(customerAttribute.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues__ReturnFalse()
- {
- var customerAttribute1 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.TextBox };
- var customerAttribute2 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
- var customerAttribute3 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.Datepicker };
- var customerAttribute4 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.FileUpload };
- Assert.IsFalse(customerAttribute1.ShouldHaveValues());
- Assert.IsFalse(customerAttribute2.ShouldHaveValues());
- Assert.IsFalse(customerAttribute3.ShouldHaveValues());
- Assert.IsFalse(customerAttribute4.ShouldHaveValues());
- }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnFalse()
+ {
+ var customerAttribute1 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.TextBox };
+ var customerAttribute2 = new CustomerAttribute
+ { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
+ var customerAttribute3 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.Datepicker };
+ var customerAttribute4 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.FileUpload };
+ Assert.IsFalse(customerAttribute1.ShouldHaveValues());
+ Assert.IsFalse(customerAttribute2.ShouldHaveValues());
+ Assert.IsFalse(customerAttribute3.ShouldHaveValues());
+ Assert.IsFalse(customerAttribute4.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues__ReturnTrue()
- {
- var addressAttribute1 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.DropdownList };
- var addressAttribute2 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.ImageSquares };
- var addressAttribute3 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.RadioList };
- var addressAttribute4 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.ReadonlyCheckboxes };
- Assert.IsTrue(addressAttribute1.ShouldHaveValues());
- Assert.IsTrue(addressAttribute2.ShouldHaveValues());
- Assert.IsTrue(addressAttribute3.ShouldHaveValues());
- Assert.IsTrue(addressAttribute4.ShouldHaveValues());
- }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnTrue()
+ {
+ var addressAttribute1 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.DropdownList };
+ var addressAttribute2 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.ImageSquares };
+ var addressAttribute3 = new CustomerAttribute { AttributeControlTypeId = AttributeControlType.RadioList };
+ var addressAttribute4 = new CustomerAttribute
+ { AttributeControlTypeId = AttributeControlType.ReadonlyCheckboxes };
+ Assert.IsTrue(addressAttribute1.ShouldHaveValues());
+ Assert.IsTrue(addressAttribute2.ShouldHaveValues());
+ Assert.IsTrue(addressAttribute3.ShouldHaveValues());
+ Assert.IsTrue(addressAttribute4.ShouldHaveValues());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Data/DataSettingsManagerTests.cs b/src/Tests/Grand.Domain.Tests/Data/DataSettingsManagerTests.cs
index 3a495a4f7..e29f5ea2e 100644
--- a/src/Tests/Grand.Domain.Tests/Data/DataSettingsManagerTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Data/DataSettingsManagerTests.cs
@@ -1,43 +1,44 @@
using Grand.Data;
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using TestContext = NUnit.Framework.TestContext;
-namespace Grand.Domain.Tests.Data
+namespace Grand.Domain.Tests.Data;
+
+[TestClass]
+public class DataSettingsManagerTests
{
- [TestClass()]
- public class DataSettingsManagerTests
+ public DataSettingsManagerTests()
{
- public DataSettingsManagerTests()
- {
- CommonPath.BaseDirectory = NUnit.Framework.TestContext.CurrentContext.TestDirectory;
- }
-
- [TestInitialize]
- public void Setup()
- {
- DataSettingsManager.LoadDataSettings(null);
+ CommonPath.BaseDirectory = TestContext.CurrentContext.TestDirectory;
+ }
- if (File.Exists(CommonPath.SettingsPath))
- File.Delete(CommonPath.SettingsPath);
- }
+ [TestInitialize]
+ public void Setup()
+ {
+ DataSettingsManager.LoadDataSettings(null);
- [TestMethod()]
- public async Task SaveSettings_LoadSettings_Test()
- {
- await DataSettingsManager.SaveSettings(new DataSettings { ConnectionString = "connectionstring", DbProvider = DbProvider.MongoDB });
- var settings = DataSettingsManager.LoadSettings();
- Assert.IsNotNull(settings);
- Assert.IsTrue(DataSettingsManager.DatabaseIsInstalled());
- Assert.AreEqual("connectionstring", settings.ConnectionString);
- }
+ if (File.Exists(CommonPath.SettingsPath))
+ File.Delete(CommonPath.SettingsPath);
+ }
+ [TestMethod]
+ public async Task SaveSettings_LoadSettings_Test()
+ {
+ await DataSettingsManager.SaveSettings(new DataSettings
+ { ConnectionString = "connectionstring", DbProvider = DbProvider.MongoDB });
+ var settings = DataSettingsManager.LoadSettings();
+ Assert.IsNotNull(settings);
+ Assert.IsTrue(DataSettingsManager.DatabaseIsInstalled());
+ Assert.AreEqual("connectionstring", settings.ConnectionString);
+ }
- [TestMethod()]
- public async Task DatabaseIsInstalledTest_True()
- {
- await DataSettingsManager.SaveSettings(new DataSettings { ConnectionString = "connectionstring", DbProvider = DbProvider.MongoDB });
- Assert.IsTrue(DataSettingsManager.DatabaseIsInstalled());
- }
+ [TestMethod]
+ public async Task DatabaseIsInstalledTest_True()
+ {
+ await DataSettingsManager.SaveSettings(new DataSettings
+ { ConnectionString = "connectionstring", DbProvider = DbProvider.MongoDB });
+ Assert.IsTrue(DataSettingsManager.DatabaseIsInstalled());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Messages/ContactAttributeExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Messages/ContactAttributeExtensionsTests.cs
index 7783600ff..c3eb06ebd 100644
--- a/src/Tests/Grand.Domain.Tests/Messages/ContactAttributeExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Messages/ContactAttributeExtensionsTests.cs
@@ -2,69 +2,75 @@
using Grand.Domain.Messages;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Messages
+namespace Grand.Domain.Tests.Messages;
+
+[TestClass]
+public class ContactAttributeExtensionsTests
{
- [TestClass()]
- public class ContactAttributeExtensionsTests
+ [TestMethod]
+ public void ShouldHaveValues_NullContactAttribute_ReturnFalse()
{
- [TestMethod()]
- public void ShouldHaveValues_NullContactAttribute_ReturnFalse()
- {
- ContactAttribute contactAttribute = null;
- Assert.IsFalse(contactAttribute.ShouldHaveValues());
- }
+ ContactAttribute contactAttribute = null;
+ Assert.IsFalse(contactAttribute.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues__ReturnFalse()
- {
- var contactAttribute1 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.TextBox };
- var contactAttribute2 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.MultilineTextbox };
- var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.Datepicker };
- var contactAttribute4 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.FileUpload };
- Assert.IsFalse(contactAttribute1.ShouldHaveValues());
- Assert.IsFalse(contactAttribute2.ShouldHaveValues());
- Assert.IsFalse(contactAttribute3.ShouldHaveValues());
- Assert.IsFalse(contactAttribute4.ShouldHaveValues());
- }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnFalse()
+ {
+ var contactAttribute1 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.TextBox };
+ var contactAttribute2 = new ContactAttribute
+ { AttributeControlTypeId = (int)AttributeControlType.MultilineTextbox };
+ var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.Datepicker };
+ var contactAttribute4 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.FileUpload };
+ Assert.IsFalse(contactAttribute1.ShouldHaveValues());
+ Assert.IsFalse(contactAttribute2.ShouldHaveValues());
+ Assert.IsFalse(contactAttribute3.ShouldHaveValues());
+ Assert.IsFalse(contactAttribute4.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues__ReturnTrue()
- {
- var contactAttribute1 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.DropdownList };
- var contactAttribute2 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.ImageSquares };
- var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.RadioList };
- var contactAttribute4 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.ReadonlyCheckboxes };
- Assert.IsTrue(contactAttribute1.ShouldHaveValues());
- Assert.IsTrue(contactAttribute2.ShouldHaveValues());
- Assert.IsTrue(contactAttribute3.ShouldHaveValues());
- Assert.IsTrue(contactAttribute4.ShouldHaveValues());
- }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnTrue()
+ {
+ var contactAttribute1 = new ContactAttribute
+ { AttributeControlTypeId = (int)AttributeControlType.DropdownList };
+ var contactAttribute2 = new ContactAttribute
+ { AttributeControlTypeId = (int)AttributeControlType.ImageSquares };
+ var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.RadioList };
+ var contactAttribute4 = new ContactAttribute
+ { AttributeControlTypeId = (int)AttributeControlType.ReadonlyCheckboxes };
+ Assert.IsTrue(contactAttribute1.ShouldHaveValues());
+ Assert.IsTrue(contactAttribute2.ShouldHaveValues());
+ Assert.IsTrue(contactAttribute3.ShouldHaveValues());
+ Assert.IsTrue(contactAttribute4.ShouldHaveValues());
+ }
- [TestMethod()]
- public void CanBeUsedAsConditionTest__ReturnFalse()
- {
- var contactAttribute1 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.TextBox };
- var contactAttribute2 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.MultilineTextbox };
- var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.Datepicker };
- var contactAttribute4 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.FileUpload };
- Assert.IsFalse(contactAttribute1.CanBeUsedAsCondition());
- Assert.IsFalse(contactAttribute2.CanBeUsedAsCondition());
- Assert.IsFalse(contactAttribute3.CanBeUsedAsCondition());
- Assert.IsFalse(contactAttribute4.CanBeUsedAsCondition());
- }
+ [TestMethod]
+ public void CanBeUsedAsConditionTest__ReturnFalse()
+ {
+ var contactAttribute1 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.TextBox };
+ var contactAttribute2 = new ContactAttribute
+ { AttributeControlTypeId = (int)AttributeControlType.MultilineTextbox };
+ var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.Datepicker };
+ var contactAttribute4 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.FileUpload };
+ Assert.IsFalse(contactAttribute1.CanBeUsedAsCondition());
+ Assert.IsFalse(contactAttribute2.CanBeUsedAsCondition());
+ Assert.IsFalse(contactAttribute3.CanBeUsedAsCondition());
+ Assert.IsFalse(contactAttribute4.CanBeUsedAsCondition());
+ }
- [TestMethod()]
- public void CanBeUsedAsConditionTest__ReturnTruee()
- {
- var contactAttribute1 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.DropdownList };
- var contactAttribute2 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.Checkboxes };
- var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.RadioList };
- var contactAttribute4 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.ColorSquares };
- Assert.IsTrue(contactAttribute1.CanBeUsedAsCondition());
- Assert.IsTrue(contactAttribute2.CanBeUsedAsCondition());
- Assert.IsTrue(contactAttribute3.CanBeUsedAsCondition());
- Assert.IsTrue(contactAttribute4.CanBeUsedAsCondition());
- }
+ [TestMethod]
+ public void CanBeUsedAsConditionTest__ReturnTruee()
+ {
+ var contactAttribute1 = new ContactAttribute
+ { AttributeControlTypeId = (int)AttributeControlType.DropdownList };
+ var contactAttribute2 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.Checkboxes };
+ var contactAttribute3 = new ContactAttribute { AttributeControlTypeId = (int)AttributeControlType.RadioList };
+ var contactAttribute4 = new ContactAttribute
+ { AttributeControlTypeId = (int)AttributeControlType.ColorSquares };
+ Assert.IsTrue(contactAttribute1.CanBeUsedAsCondition());
+ Assert.IsTrue(contactAttribute2.CanBeUsedAsCondition());
+ Assert.IsTrue(contactAttribute3.CanBeUsedAsCondition());
+ Assert.IsTrue(contactAttribute4.CanBeUsedAsCondition());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Orders/CheckoutAttributeExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Orders/CheckoutAttributeExtensionsTests.cs
index bfd128613..8231f76ec 100644
--- a/src/Tests/Grand.Domain.Tests/Orders/CheckoutAttributeExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Orders/CheckoutAttributeExtensionsTests.cs
@@ -2,70 +2,71 @@
using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Orders
+namespace Grand.Domain.Tests.Orders;
+
+[TestClass]
+public class CheckoutAttributeExtensionsTests
{
- [TestClass()]
- public class CheckoutAttributeExtensionsTests
+ [TestMethod]
+ public void ShouldHaveValues_NullCheckoutAttribute_ReturnFalse()
{
- [TestMethod()]
- public void ShouldHaveValues_NullCheckoutAttribute_ReturnFalse()
- {
- CheckoutAttribute checkoutAttribute = null;
- Assert.IsFalse(checkoutAttribute.ShouldHaveValues());
- }
-
- [TestMethod()]
- public void ShouldHaveValues__ReturnFalse()
- {
- var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.TextBox };
- var checkoutAttribute2 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
- var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.Datepicker };
- var checkoutAttribute4 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.FileUpload };
- Assert.IsFalse(checkoutAttribute1.ShouldHaveValues());
- Assert.IsFalse(checkoutAttribute2.ShouldHaveValues());
- Assert.IsFalse(checkoutAttribute3.ShouldHaveValues());
- Assert.IsFalse(checkoutAttribute4.ShouldHaveValues());
- }
+ CheckoutAttribute checkoutAttribute = null;
+ Assert.IsFalse(checkoutAttribute.ShouldHaveValues());
+ }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnFalse()
+ {
+ var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.TextBox };
+ var checkoutAttribute2 = new CheckoutAttribute
+ { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
+ var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.Datepicker };
+ var checkoutAttribute4 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.FileUpload };
+ Assert.IsFalse(checkoutAttribute1.ShouldHaveValues());
+ Assert.IsFalse(checkoutAttribute2.ShouldHaveValues());
+ Assert.IsFalse(checkoutAttribute3.ShouldHaveValues());
+ Assert.IsFalse(checkoutAttribute4.ShouldHaveValues());
+ }
- [TestMethod()]
- public void ShouldHaveValues__ReturnTrue()
- {
- var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.DropdownList };
- var checkoutAttribute2 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.ImageSquares };
- var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.RadioList };
- var checkoutAttribute4 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.ReadonlyCheckboxes };
- Assert.IsTrue(checkoutAttribute1.ShouldHaveValues());
- Assert.IsTrue(checkoutAttribute2.ShouldHaveValues());
- Assert.IsTrue(checkoutAttribute3.ShouldHaveValues());
- Assert.IsTrue(checkoutAttribute4.ShouldHaveValues());
- }
- [TestMethod()]
- public void CanBeUsedAsConditionTest__ReturnFalse()
- {
- var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.TextBox };
- var checkoutAttribute2 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
- var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.Datepicker };
- var checkoutAttribute4 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.FileUpload };
- Assert.IsFalse(checkoutAttribute1.CanBeUsedAsCondition());
- Assert.IsFalse(checkoutAttribute2.CanBeUsedAsCondition());
- Assert.IsFalse(checkoutAttribute3.CanBeUsedAsCondition());
- Assert.IsFalse(checkoutAttribute4.CanBeUsedAsCondition());
- }
+ [TestMethod]
+ public void ShouldHaveValues__ReturnTrue()
+ {
+ var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.DropdownList };
+ var checkoutAttribute2 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.ImageSquares };
+ var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.RadioList };
+ var checkoutAttribute4 = new CheckoutAttribute
+ { AttributeControlTypeId = AttributeControlType.ReadonlyCheckboxes };
+ Assert.IsTrue(checkoutAttribute1.ShouldHaveValues());
+ Assert.IsTrue(checkoutAttribute2.ShouldHaveValues());
+ Assert.IsTrue(checkoutAttribute3.ShouldHaveValues());
+ Assert.IsTrue(checkoutAttribute4.ShouldHaveValues());
+ }
- [TestMethod()]
- public void CanBeUsedAsConditionTest__ReturnTruee()
- {
- var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.DropdownList };
- var checkoutAttribute2 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.Checkboxes };
- var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.RadioList };
- var checkoutAttribute4 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.ColorSquares };
- Assert.IsTrue(checkoutAttribute1.CanBeUsedAsCondition());
- Assert.IsTrue(checkoutAttribute2.CanBeUsedAsCondition());
- Assert.IsTrue(checkoutAttribute3.CanBeUsedAsCondition());
- Assert.IsTrue(checkoutAttribute4.CanBeUsedAsCondition());
- }
+ [TestMethod]
+ public void CanBeUsedAsConditionTest__ReturnFalse()
+ {
+ var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.TextBox };
+ var checkoutAttribute2 = new CheckoutAttribute
+ { AttributeControlTypeId = AttributeControlType.MultilineTextbox };
+ var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.Datepicker };
+ var checkoutAttribute4 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.FileUpload };
+ Assert.IsFalse(checkoutAttribute1.CanBeUsedAsCondition());
+ Assert.IsFalse(checkoutAttribute2.CanBeUsedAsCondition());
+ Assert.IsFalse(checkoutAttribute3.CanBeUsedAsCondition());
+ Assert.IsFalse(checkoutAttribute4.CanBeUsedAsCondition());
+ }
+ [TestMethod]
+ public void CanBeUsedAsConditionTest__ReturnTruee()
+ {
+ var checkoutAttribute1 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.DropdownList };
+ var checkoutAttribute2 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.Checkboxes };
+ var checkoutAttribute3 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.RadioList };
+ var checkoutAttribute4 = new CheckoutAttribute { AttributeControlTypeId = AttributeControlType.ColorSquares };
+ Assert.IsTrue(checkoutAttribute1.CanBeUsedAsCondition());
+ Assert.IsTrue(checkoutAttribute2.CanBeUsedAsCondition());
+ Assert.IsTrue(checkoutAttribute3.CanBeUsedAsCondition());
+ Assert.IsTrue(checkoutAttribute4.CanBeUsedAsCondition());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Orders/GiftVoucherExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Orders/GiftVoucherExtensionsTests.cs
index b3f26a029..afec12bdc 100644
--- a/src/Tests/Grand.Domain.Tests/Orders/GiftVoucherExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Orders/GiftVoucherExtensionsTests.cs
@@ -1,77 +1,80 @@
using Grand.Domain.Common;
+using Grand.Domain.Directory;
using Grand.Domain.Orders;
+using Grand.Domain.Stores;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Orders
-{
- [TestClass()]
- public class GiftVoucherExtensionsTests
- {
- private GiftVoucher giftVoucher = new() {
- Amount = 10,
- Code = "123456",
- CurrencyCode = "USD",
- IsGiftVoucherActivated = true
- };
+namespace Grand.Domain.Tests.Orders;
- [TestMethod()]
- public void AddGiftVoucherAttributeTest()
- {
- IList<CustomAttribute> customAttributes = new List<CustomAttribute>();
- GiftVoucherExtensions.AddGiftVoucherAttribute(customAttributes, "Johny", "[email protected]", "My name", "[email protected]", "my sample message");
+[TestClass]
+public class GiftVoucherExtensionsTests
+{
+ private readonly GiftVoucher giftVoucher = new() {
+ Amount = 10,
+ Code = "123456",
+ CurrencyCode = "USD",
+ IsGiftVoucherActivated = true
+ };
- GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,
- out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var giftVoucherMessage);
+ [TestMethod]
+ public void AddGiftVoucherAttributeTest()
+ {
+ IList<CustomAttribute> customAttributes = new List<CustomAttribute>();
+ GiftVoucherExtensions.AddGiftVoucherAttribute(customAttributes, "Johny", "[email protected]", "My name",
+ "[email protected]", "my sample message");
- Assert.IsTrue(giftVoucherRecipientName == "Johny");
- Assert.IsTrue(giftVoucherRecipientEmail == "[email protected]");
- Assert.IsTrue(giftVoucherSenderName == "My name");
- Assert.IsTrue(giftVoucherSenderEmail == "[email protected]");
- Assert.IsTrue(giftVoucherMessage == "my sample message");
+ GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName,
+ out var giftVoucherRecipientEmail,
+ out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var giftVoucherMessage);
- }
+ Assert.IsTrue(giftVoucherRecipientName == "Johny");
+ Assert.IsTrue(giftVoucherRecipientEmail == "[email protected]");
+ Assert.IsTrue(giftVoucherSenderName == "My name");
+ Assert.IsTrue(giftVoucherSenderEmail == "[email protected]");
+ Assert.IsTrue(giftVoucherMessage == "my sample message");
+ }
- [TestMethod()]
- public void GetGiftVoucherAttributeTest()
- {
- IList<CustomAttribute> customAttributes = new List<CustomAttribute>();
- customAttributes.Add(new CustomAttribute { Key = "RecipientName", Value = "Johny" });
- customAttributes.Add(new CustomAttribute { Key = "RecipientEmail", Value = "[email protected]" });
- customAttributes.Add(new CustomAttribute { Key = "SenderName", Value = "My name" });
- customAttributes.Add(new CustomAttribute { Key = "SenderEmail", Value = "[email protected]" });
- customAttributes.Add(new CustomAttribute { Key = "Message", Value = "my sample message" });
- customAttributes.Add(new CustomAttribute { Key = "Test", Value = "my test" });
+ [TestMethod]
+ public void GetGiftVoucherAttributeTest()
+ {
+ IList<CustomAttribute> customAttributes = new List<CustomAttribute>();
+ customAttributes.Add(new CustomAttribute { Key = "RecipientName", Value = "Johny" });
+ customAttributes.Add(new CustomAttribute { Key = "RecipientEmail", Value = "[email protected]" });
+ customAttributes.Add(new CustomAttribute { Key = "SenderName", Value = "My name" });
+ customAttributes.Add(new CustomAttribute { Key = "SenderEmail", Value = "[email protected]" });
+ customAttributes.Add(new CustomAttribute { Key = "Message", Value = "my sample message" });
+ customAttributes.Add(new CustomAttribute { Key = "Test", Value = "my test" });
- GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName, out var giftVoucherRecipientEmail,
- out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var giftVoucherMessage);
+ GiftVoucherExtensions.GetGiftVoucherAttribute(customAttributes, out var giftVoucherRecipientName,
+ out var giftVoucherRecipientEmail,
+ out var giftVoucherSenderName, out var giftVoucherSenderEmail, out var giftVoucherMessage);
- Assert.IsTrue(giftVoucherRecipientName == "Johny");
- Assert.IsTrue(giftVoucherRecipientEmail == "[email protected]");
- Assert.IsTrue(giftVoucherSenderName == "My name");
- Assert.IsTrue(giftVoucherSenderEmail == "[email protected]");
- Assert.IsTrue(giftVoucherMessage == "my sample message");
- }
+ Assert.IsTrue(giftVoucherRecipientName == "Johny");
+ Assert.IsTrue(giftVoucherRecipientEmail == "[email protected]");
+ Assert.IsTrue(giftVoucherSenderName == "My name");
+ Assert.IsTrue(giftVoucherSenderEmail == "[email protected]");
+ Assert.IsTrue(giftVoucherMessage == "my sample message");
+ }
- [TestMethod()]
- public void GetGiftVoucherRemainingAmountTest()
- {
- giftVoucher.GiftVoucherUsageHistory.Add(new GiftVoucherUsageHistory { UsedValue = 3 });
- giftVoucher.GiftVoucherUsageHistory.Add(new GiftVoucherUsageHistory { UsedValue = 4 });
- Assert.IsTrue(giftVoucher.GetGiftVoucherRemainingAmount() == 3);
- }
+ [TestMethod]
+ public void GetGiftVoucherRemainingAmountTest()
+ {
+ giftVoucher.GiftVoucherUsageHistory.Add(new GiftVoucherUsageHistory { UsedValue = 3 });
+ giftVoucher.GiftVoucherUsageHistory.Add(new GiftVoucherUsageHistory { UsedValue = 4 });
+ Assert.IsTrue(giftVoucher.GetGiftVoucherRemainingAmount() == 3);
+ }
- [TestMethod()]
- public void IsGiftVoucherValidTest_ValidTo_True()
- {
- giftVoucher.ValidTo = DateTime.UtcNow.AddDays(1);
- Assert.IsTrue(giftVoucher.IsGiftVoucherValid(new Directory.Currency { CurrencyCode = "USD" }, new Domain.Stores.Store()));
- }
+ [TestMethod]
+ public void IsGiftVoucherValidTest_ValidTo_True()
+ {
+ giftVoucher.ValidTo = DateTime.UtcNow.AddDays(1);
+ Assert.IsTrue(giftVoucher.IsGiftVoucherValid(new Currency { CurrencyCode = "USD" }, new Store()));
+ }
- [TestMethod()]
- public void IsGiftVoucherValidTest_False()
- {
- giftVoucher.ValidTo = DateTime.UtcNow.AddDays(-1);
- Assert.IsFalse(giftVoucher.IsGiftVoucherValid(new Directory.Currency { CurrencyCode = "USD" }, new Domain.Stores.Store()));
- }
+ [TestMethod]
+ public void IsGiftVoucherValidTest_False()
+ {
+ giftVoucher.ValidTo = DateTime.UtcNow.AddDays(-1);
+ Assert.IsFalse(giftVoucher.IsGiftVoucherValid(new Currency { CurrencyCode = "USD" }, new Store()));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Orders/OrderExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Orders/OrderExtensionsTests.cs
index 7e65daa85..42a40fa8e 100644
--- a/src/Tests/Grand.Domain.Tests/Orders/OrderExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Orders/OrderExtensionsTests.cs
@@ -1,81 +1,83 @@
using Grand.Domain.Catalog;
using Grand.Domain.Orders;
+using Grand.Domain.Payments;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Orders
+namespace Grand.Domain.Tests.Orders;
+
+[TestClass]
+public class OrderExtensionsTests
{
- [TestClass]
- public class OrderExtensionsTests
+ [TestMethod]
+ public void IsDownloadAllowed_ReturnExpectedResult()
{
- [TestMethod]
- public void IsDownloadAllowed_ReturnExpectedResult()
- {
- var order1 = new Order { PaymentStatusId = Domain.Payments.PaymentStatus.Paid, PaidDateUtc = DateTime.UtcNow };
- Order order2 = null;
- var product1 = new Product { DownloadActivationTypeId = DownloadActivationType.WhenOrderIsPaid, IsDownload = true };
- var product2 = new Product { DownloadActivationTypeId = DownloadActivationType.Manually, IsDownload = true };
- var product3 = new Product { IsDownload = false };
- var orderItem = new OrderItem { IsDownloadActivated = true };
+ var order1 = new Order { PaymentStatusId = PaymentStatus.Paid, PaidDateUtc = DateTime.UtcNow };
+ Order order2 = null;
+ var product1 = new Product
+ { DownloadActivationTypeId = DownloadActivationType.WhenOrderIsPaid, IsDownload = true };
+ var product2 = new Product { DownloadActivationTypeId = DownloadActivationType.Manually, IsDownload = true };
+ var product3 = new Product { IsDownload = false };
+ var orderItem = new OrderItem { IsDownloadActivated = true };
- Assert.IsTrue(order1.IsDownloadAllowed(orderItem, product1));
- Assert.IsTrue(order1.IsDownloadAllowed(orderItem, product2));
- Assert.IsFalse(order1.IsDownloadAllowed(null, product1));
- Assert.IsFalse(order1.IsDownloadAllowed(orderItem, null));
- Assert.IsFalse(order1.IsDownloadAllowed(null, null));
- Assert.IsFalse(order1.IsDownloadAllowed(orderItem, product3));
- Assert.IsFalse(order2.IsDownloadAllowed(orderItem, product2));
- }
+ Assert.IsTrue(order1.IsDownloadAllowed(orderItem, product1));
+ Assert.IsTrue(order1.IsDownloadAllowed(orderItem, product2));
+ Assert.IsFalse(order1.IsDownloadAllowed(null, product1));
+ Assert.IsFalse(order1.IsDownloadAllowed(orderItem, null));
+ Assert.IsFalse(order1.IsDownloadAllowed(null, null));
+ Assert.IsFalse(order1.IsDownloadAllowed(orderItem, product3));
+ Assert.IsFalse(order2.IsDownloadAllowed(orderItem, product2));
+ }
- [TestMethod]
- public void IsLicenseDownloadAllowed_ReturnExpectedResults()
- {
- var order1 = new Order { PaymentStatusId = Domain.Payments.PaymentStatus.Paid, PaidDateUtc = DateTime.UtcNow };
- Order order2 = null;
- var product1 = new Product { DownloadActivationTypeId = DownloadActivationType.WhenOrderIsPaid, IsDownload = true };
- var product2 = new Product { DownloadActivationTypeId = DownloadActivationType.Manually, IsDownload = true };
- var product3 = new Product { IsDownload = false };
- var orderItem = new OrderItem { IsDownloadActivated = true, LicenseDownloadId = "idlicense" };
- var orderItem2 = new OrderItem { IsDownloadActivated = true, LicenseDownloadId = null };
- Assert.IsTrue(order1.IsLicenseDownloadAllowed(orderItem, product1));
- Assert.IsTrue(order1.IsLicenseDownloadAllowed(orderItem, product2));
- Assert.IsFalse(order1.IsLicenseDownloadAllowed(orderItem2, product1));
- Assert.IsFalse(order1.IsLicenseDownloadAllowed(orderItem2, product2));
- Assert.IsFalse(order2.IsLicenseDownloadAllowed(orderItem, product2));
- }
+ [TestMethod]
+ public void IsLicenseDownloadAllowed_ReturnExpectedResults()
+ {
+ var order1 = new Order { PaymentStatusId = PaymentStatus.Paid, PaidDateUtc = DateTime.UtcNow };
+ Order order2 = null;
+ var product1 = new Product
+ { DownloadActivationTypeId = DownloadActivationType.WhenOrderIsPaid, IsDownload = true };
+ var product2 = new Product { DownloadActivationTypeId = DownloadActivationType.Manually, IsDownload = true };
+ var product3 = new Product { IsDownload = false };
+ var orderItem = new OrderItem { IsDownloadActivated = true, LicenseDownloadId = "idlicense" };
+ var orderItem2 = new OrderItem { IsDownloadActivated = true, LicenseDownloadId = null };
+ Assert.IsTrue(order1.IsLicenseDownloadAllowed(orderItem, product1));
+ Assert.IsTrue(order1.IsLicenseDownloadAllowed(orderItem, product2));
+ Assert.IsFalse(order1.IsLicenseDownloadAllowed(orderItem2, product1));
+ Assert.IsFalse(order1.IsLicenseDownloadAllowed(orderItem2, product2));
+ Assert.IsFalse(order2.IsLicenseDownloadAllowed(orderItem, product2));
+ }
- [TestMethod]
- public void HasItemsToAddToShipment_ReturnExpectedResult()
- {
- var order = new Order();
- order.OrderItems.Add(new OrderItem { IsShipEnabled = false, OpenQty = 1 });
- Assert.IsFalse(order.HasItemsToAddToShipment());
- order.OrderItems.Add(new OrderItem { IsShipEnabled = true, OpenQty = 1 });
- Assert.IsTrue(order.HasItemsToAddToShipment());
- }
+ [TestMethod]
+ public void HasItemsToAddToShipment_ReturnExpectedResult()
+ {
+ var order = new Order();
+ order.OrderItems.Add(new OrderItem { IsShipEnabled = false, OpenQty = 1 });
+ Assert.IsFalse(order.HasItemsToAddToShipment());
+ order.OrderItems.Add(new OrderItem { IsShipEnabled = true, OpenQty = 1 });
+ Assert.IsTrue(order.HasItemsToAddToShipment());
+ }
- [TestMethod]
- public void HasItemsToAddToShipment_NullOrder_ThrowException()
- {
- Order order = null;
- Assert.ThrowsException<ArgumentNullException>(() => order.HasItemsToAddToShipment());
- }
+ [TestMethod]
+ public void HasItemsToAddToShipment_NullOrder_ThrowException()
+ {
+ Order order = null;
+ Assert.ThrowsException<ArgumentNullException>(() => order.HasItemsToAddToShipment());
+ }
- [TestMethod]
- public void OrderTagExists_ReturnExpectedResult()
- {
- var order = new Order();
- var tag = new OrderTag { Id = "id" };
- order.OrderTags.Add("1");
- Assert.IsFalse(order.OrderTagExists(tag));
- order.OrderTags.Add("id");
- Assert.IsTrue(order.OrderTagExists(tag));
- }
+ [TestMethod]
+ public void OrderTagExists_ReturnExpectedResult()
+ {
+ var order = new Order();
+ var tag = new OrderTag { Id = "id" };
+ order.OrderTags.Add("1");
+ Assert.IsFalse(order.OrderTagExists(tag));
+ order.OrderTags.Add("id");
+ Assert.IsTrue(order.OrderTagExists(tag));
+ }
- [TestMethod]
- public void OrderTagExists_NullOrder_ThrowException()
- {
- Order order = null;
- Assert.ThrowsException<ArgumentNullException>(() => order.HasItemsToAddToShipment());
- }
+ [TestMethod]
+ public void OrderTagExists_NullOrder_ThrowException()
+ {
+ Order order = null;
+ Assert.ThrowsException<ArgumentNullException>(() => order.HasItemsToAddToShipment());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Orders/ShoppingCartExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Orders/ShoppingCartExtensionsTests.cs
index c417ea7a7..44f41255a 100644
--- a/src/Tests/Grand.Domain.Tests/Orders/ShoppingCartExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Orders/ShoppingCartExtensionsTests.cs
@@ -1,36 +1,35 @@
using Grand.Domain.Orders;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Orders
+namespace Grand.Domain.Tests.Orders;
+
+[TestClass]
+public class ShoppingCartExtensionsTests
{
- [TestClass]
- public class ShoppingCartExtensionsTests
+ [TestMethod]
+ public void RequiresShipping_ReturnExpectedResults()
{
- [TestMethod]
- public void RequiresShipping_ReturnExpectedResults()
- {
- var shoppingCartItems = new List<ShoppingCartItem> {
- new ShoppingCartItem {IsShipEnabled=false },
- new ShoppingCartItem {IsShipEnabled=false }
- };
+ var shoppingCartItems = new List<ShoppingCartItem> {
+ new() { IsShipEnabled = false },
+ new() { IsShipEnabled = false }
+ };
- Assert.IsFalse(shoppingCartItems.RequiresShipping());
- shoppingCartItems.Add(new ShoppingCartItem { IsShipEnabled = true });
- Assert.IsTrue(shoppingCartItems.RequiresShipping());
- }
+ Assert.IsFalse(shoppingCartItems.RequiresShipping());
+ shoppingCartItems.Add(new ShoppingCartItem { IsShipEnabled = true });
+ Assert.IsTrue(shoppingCartItems.RequiresShipping());
+ }
- [TestMethod]
- public void LimitPerStore_ReturnExpectedResults()
- {
- var shoppingCartItems = new List<ShoppingCartItem> {
- new ShoppingCartItem {IsShipEnabled=false },
- new ShoppingCartItem {IsShipEnabled=false }
- };
- Assert.IsTrue(shoppingCartItems.LimitPerStore(false, "id").ToList().Count == 0);
- shoppingCartItems.Add(new ShoppingCartItem { StoreId = "id" });
- var result = shoppingCartItems.LimitPerStore(false, "id").ToList();
- Assert.IsTrue(result.Count == 1);
- Assert.IsTrue(result.First().StoreId.Equals("id"));
- }
+ [TestMethod]
+ public void LimitPerStore_ReturnExpectedResults()
+ {
+ var shoppingCartItems = new List<ShoppingCartItem> {
+ new() { IsShipEnabled = false },
+ new() { IsShipEnabled = false }
+ };
+ Assert.IsTrue(shoppingCartItems.LimitPerStore(false, "id").ToList().Count == 0);
+ shoppingCartItems.Add(new ShoppingCartItem { StoreId = "id" });
+ var result = shoppingCartItems.LimitPerStore(false, "id").ToList();
+ Assert.IsTrue(result.Count == 1);
+ Assert.IsTrue(result.First().StoreId.Equals("id"));
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Domain.Tests/Stores/StoreExtensionsTests.cs b/src/Tests/Grand.Domain.Tests/Stores/StoreExtensionsTests.cs
index fb1b4f343..fc609aedf 100644
--- a/src/Tests/Grand.Domain.Tests/Stores/StoreExtensionsTests.cs
+++ b/src/Tests/Grand.Domain.Tests/Stores/StoreExtensionsTests.cs
@@ -1,44 +1,42 @@
using Grand.Domain.Stores;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Domain.Tests.Stores
-{
- [TestClass()]
- public class StoreExtensionsTests
- {
- private Store store;
+namespace Grand.Domain.Tests.Stores;
- [TestInitialize]
- public void Setup()
- {
- store = new();
- store.Domains.Add(new DomainHost { HostName = "google.com", Url = "https:\\google.com" });
- store.Domains.Add(new DomainHost { HostName = "yahoo.com", Url = "https:\\yahoo.com" });
- }
+[TestClass]
+public class StoreExtensionsTests
+{
+ private Store store;
- [TestMethod()]
- public void ContainsHostValueTest_True()
- {
- Assert.IsTrue(store.ContainsHostValue("Google.com"));
- }
+ [TestInitialize]
+ public void Setup()
+ {
+ store = new Store();
+ store.Domains.Add(new DomainHost { HostName = "google.com", Url = "https:\\google.com" });
+ store.Domains.Add(new DomainHost { HostName = "yahoo.com", Url = "https:\\yahoo.com" });
+ }
- [TestMethod()]
- public void ContainsHostValueTest_False()
- {
- Assert.IsFalse(store.ContainsHostValue("google"));
- }
+ [TestMethod]
+ public void ContainsHostValueTest_True()
+ {
+ Assert.IsTrue(store.ContainsHostValue("Google.com"));
+ }
- [TestMethod()]
- public void HostValueTest_NotNull()
- {
- Assert.IsNotNull(store.HostValue("yAhoO.com"));
- }
+ [TestMethod]
+ public void ContainsHostValueTest_False()
+ {
+ Assert.IsFalse(store.ContainsHostValue("google"));
+ }
- [TestMethod()]
- public void HostValueTest_Null()
- {
- Assert.IsNull(store.HostValue("yahoo"));
- }
+ [TestMethod]
+ public void HostValueTest_NotNull()
+ {
+ Assert.IsNotNull(store.HostValue("yAhoO.com"));
+ }
+ [TestMethod]
+ public void HostValueTest_Null()
+ {
+ Assert.IsNull(store.HostValue("yahoo"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheBaseTests.cs b/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheBaseTests.cs
index 8492fbdd0..9ba5e0f86 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheBaseTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheBaseTests.cs
@@ -1,5 +1,4 @@
-using Grand.Business.Core.Commands.Checkout.Orders;
-using Grand.Infrastructure.Caching;
+using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Configuration;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
@@ -7,138 +6,138 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
-namespace Grand.Infrastructure.Tests.Caching
+namespace Grand.Infrastructure.Tests.Caching;
+
+[TestClass]
+public class MemoryCacheBaseTests
{
- [TestClass()]
- public class MemoryCacheBaseTests
+ private CacheConfig _config;
+ private Mock<IMediator> _mediatorMock;
+ private IMemoryCache _memoryCache;
+ private MemoryCacheBase _service;
+
+ [TestInitialize]
+ public void Init()
+ {
+ _config = new CacheConfig { DefaultCacheTimeMinutes = 1 };
+ var services = new ServiceCollection();
+ services.AddMemoryCache();
+ services.AddSingleton(_config);
+ var serviceProvider = services.BuildServiceProvider();
+
+ _memoryCache = serviceProvider.GetService<IMemoryCache>();
+ _mediatorMock = new Mock<IMediator>();
+ _service = new MemoryCacheBase(_memoryCache, _mediatorMock.Object, _config);
+ }
+
+ [TestMethod]
+ public async Task GetAsyncTest()
+ {
+ var result = await _service.GetAsync("key", () => { return Task.FromResult("test"); });
+ Assert.AreEqual(result, "test");
+ }
+
+ [TestMethod]
+ public async Task GetAsyncTest_CacheTimeMinutes()
+ {
+ var result = await _service.GetAsync("key", () => { return Task.FromResult("test"); }, 1);
+ Assert.AreEqual(result, "test");
+ }
+
+ [TestMethod]
+ public void GetTest()
+ {
+ var result = _service.Get("key", () => { return "test"; });
+ Assert.AreEqual(result, "test");
+ }
+
+ [TestMethod]
+ public void GetTest_CacheTimeMinutes()
+ {
+ var result = _service.Get("key", () => { return "test"; }, 1);
+ Assert.AreEqual(result, "test");
+ }
+
+ [TestMethod]
+ public async Task RemoveAsyncTest_IsNull()
+ {
+ _service.Get("key", () => { return "test"; }, 1);
+ await _service.RemoveAsync("key");
+ var result = _memoryCache.Get("key");
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task RemoveAsyncTest_NotNull()
+ {
+ _service.Get("key", () => { return "test"; }, 1);
+ await _service.RemoveAsync("key1");
+ var result = _memoryCache.Get("key");
+ Assert.IsNotNull(result);
+ }
+
+ [TestMethod]
+ public async Task RemoveByPrefixTest()
+ {
+ _service.Get("key1", () => { return "test"; }, 1);
+ _service.Get("key2", () => { return "test"; }, 1);
+ _service.Get("test", () => { return "test"; }, 1);
+ await _service.RemoveByPrefix("key");
+ var result = _memoryCache.Get("key1");
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task ClearTest()
+ {
+ _service.Get("key1", () => { return "test"; }, 1);
+ _service.Get("key2", () => { return "test"; }, 1);
+ _service.Get("test", () => { return "test"; }, 1);
+ await _service.Clear();
+ var result = _memoryCache.Get("key1");
+ Assert.IsNull(result);
+ }
+
+ [TestMethod]
+ public async Task SetAsync_Key_NotExist_ShouldSetCacheEntry()
+ {
+ // Arrange
+ var key = "testKey";
+ var cacheTime = 60;
+ var cacheEntry = "testValue";
+
+ var acquireMock = new Mock<Func<Task<string>>>();
+ acquireMock.Setup(a => a.Invoke()).ReturnsAsync(cacheEntry);
+
+ // Act
+ var result = await _service.SetAsync(key, acquireMock.Object, cacheTime);
+
+ // Assert
+ acquireMock.Verify(a => a.Invoke(), Times.Once);
+ var cacheResult = _memoryCache.Get(key);
+ Assert.IsNotNull(cacheResult);
+ Assert.AreEqual(cacheEntry, cacheResult);
+ }
+
+ [TestMethod]
+ public async Task SetAsync_Key_Exist_ShouldSetCacheEntry()
{
- private Mock<IMediator> _mediatorMock;
- private MemoryCacheBase _service;
- private IMemoryCache _memoryCache;
- private CacheConfig _config;
-
- [TestInitialize]
- public void Init()
- {
- _config = new CacheConfig { DefaultCacheTimeMinutes = 1 };
- var services = new ServiceCollection();
- services.AddMemoryCache();
- services.AddSingleton<CacheConfig>(_config);
- var serviceProvider = services.BuildServiceProvider();
-
- _memoryCache = serviceProvider.GetService<IMemoryCache>();
- _mediatorMock = new Mock<IMediator>();
- _service = new MemoryCacheBase(_memoryCache, _mediatorMock.Object, _config);
- }
-
- [TestMethod()]
- public async Task GetAsyncTest()
- {
- var result = await _service.GetAsync<string>("key", () => { return Task.FromResult("test"); });
- Assert.AreEqual(result, "test");
- }
-
- [TestMethod()]
- public async Task GetAsyncTest_CacheTimeMinutes()
- {
- var result = await _service.GetAsync<string>("key", () => { return Task.FromResult("test"); }, 1);
- Assert.AreEqual(result, "test");
- }
-
- [TestMethod()]
- public void GetTest()
- {
- var result = _service.Get<string>("key", () => { return "test"; });
- Assert.AreEqual(result, "test");
- }
-
- [TestMethod()]
- public void GetTest_CacheTimeMinutes()
- {
- var result = _service.Get<string>("key", () => { return "test"; }, 1);
- Assert.AreEqual(result, "test");
- }
-
- [TestMethod()]
- public async Task RemoveAsyncTest_IsNull()
- {
- _service.Get<string>("key", () => { return "test"; }, 1);
- await _service.RemoveAsync("key");
- var result = _memoryCache.Get("key");
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task RemoveAsyncTest_NotNull()
- {
- _service.Get<string>("key", () => { return "test"; }, 1);
- await _service.RemoveAsync("key1");
- var result = _memoryCache.Get("key");
- Assert.IsNotNull(result);
- }
-
- [TestMethod()]
- public async Task RemoveByPrefixTest()
- {
- _service.Get<string>("key1", () => { return "test"; }, 1);
- _service.Get<string>("key2", () => { return "test"; }, 1);
- _service.Get<string>("test", () => { return "test"; }, 1);
- await _service.RemoveByPrefix("key");
- var result = _memoryCache.Get("key1");
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task ClearTest()
- {
- _service.Get<string>("key1", () => { return "test"; }, 1);
- _service.Get<string>("key2", () => { return "test"; }, 1);
- _service.Get<string>("test", () => { return "test"; }, 1);
- await _service.Clear();
- var result = _memoryCache.Get("key1");
- Assert.IsNull(result);
- }
-
- [TestMethod()]
- public async Task SetAsync_Key_NotExist_ShouldSetCacheEntry()
- {
- // Arrange
- var key = "testKey";
- var cacheTime = 60;
- var cacheEntry = "testValue";
-
- var acquireMock = new Mock<Func<Task<string>>>();
- acquireMock.Setup(a => a.Invoke()).ReturnsAsync(cacheEntry);
-
- // Act
- var result = await _service.SetAsync(key, acquireMock.Object, cacheTime);
-
- // Assert
- acquireMock.Verify(a => a.Invoke(), Times.Once);
- var cacheResult = _memoryCache.Get(key);
- Assert.IsNotNull(cacheResult);
- Assert.AreEqual(cacheEntry, cacheResult);
- }
- [TestMethod()]
- public async Task SetAsync_Key_Exist_ShouldSetCacheEntry()
- {
- // Arrange
- var key = "testKey";
- var cacheTime = 60;
- var cacheEntry = "testValue";
-
- var acquireMock = new Mock<Func<Task<string>>>();
- acquireMock.Setup(a => a.Invoke()).ReturnsAsync(cacheEntry);
- _service.Get<string>(key, () => { return "fakeValue"; }, 1);
-
- // Act
- var result = await _service.SetAsync(key, acquireMock.Object, cacheTime);
-
- // Assert
- acquireMock.Verify(a => a.Invoke(), Times.Once);
- var cacheResult = _memoryCache.Get(key);
- Assert.IsNotNull(cacheResult);
- Assert.AreEqual(cacheEntry, cacheResult);
- }
+ // Arrange
+ var key = "testKey";
+ var cacheTime = 60;
+ var cacheEntry = "testValue";
+
+ var acquireMock = new Mock<Func<Task<string>>>();
+ acquireMock.Setup(a => a.Invoke()).ReturnsAsync(cacheEntry);
+ _service.Get(key, () => { return "fakeValue"; }, 1);
+
+ // Act
+ var result = await _service.SetAsync(key, acquireMock.Object, cacheTime);
+
+ // Assert
+ acquireMock.Verify(a => a.Invoke(), Times.Once);
+ var cacheResult = _memoryCache.Get(key);
+ Assert.IsNotNull(cacheResult);
+ Assert.AreEqual(cacheEntry, cacheResult);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheTest.cs b/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheTest.cs
index e600181cb..c90b1f3a2 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheTest.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Caching/MemoryCacheTest.cs
@@ -1,17 +1,16 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
-namespace Grand.Infrastructure.Tests.Caching
+namespace Grand.Infrastructure.Tests.Caching;
+
+public static class MemoryCacheTest
{
- public static class MemoryCacheTest
+ public static IMemoryCache Get()
{
- public static IMemoryCache Get()
- {
- var services = new ServiceCollection();
- services.AddMemoryCache();
- var serviceProvider = services.BuildServiceProvider();
+ var services = new ServiceCollection();
+ services.AddMemoryCache();
+ var serviceProvider = services.BuildServiceProvider();
- return serviceProvider.GetService<IMemoryCache>();
- }
+ return serviceProvider.GetService<IMemoryCache>();
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/DiscountProviderTest.cs b/src/Tests/Grand.Infrastructure.Tests/DiscountProviderTest.cs
index 39a4b594c..15263dc84 100644
--- a/src/Tests/Grand.Infrastructure.Tests/DiscountProviderTest.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/DiscountProviderTest.cs
@@ -1,32 +1,29 @@
using Grand.Business.Core.Interfaces.Catalog.Discounts;
-namespace Grand.Infrastructure.Tests
+namespace Grand.Infrastructure.Tests;
+
+public class DiscountProviderTest : IDiscountProvider
{
- public class DiscountProviderTest : IDiscountProvider
+ public DiscountProviderTest(List<string> stores, IList<string> groups)
{
- private IList<string> limitedToStores;
- private IList<string> limitedToGroups;
- public DiscountProviderTest(List<string> stores, IList<string> groups)
- {
- limitedToStores = stores;
- limitedToGroups = groups;
- }
+ LimitedToStores = stores;
+ LimitedToGroups = groups;
+ }
- public string ConfigurationUrl => throw new NotImplementedException();
+ public string ConfigurationUrl => throw new NotImplementedException();
- public string SystemName => throw new NotImplementedException();
+ public string SystemName => throw new NotImplementedException();
- public string FriendlyName => throw new NotImplementedException();
+ public string FriendlyName => throw new NotImplementedException();
- public int Priority => throw new NotImplementedException();
+ public int Priority => throw new NotImplementedException();
- public IList<string> LimitedToStores => limitedToStores;
+ public IList<string> LimitedToStores { get; }
- public IList<string> LimitedToGroups => limitedToGroups;
+ public IList<string> LimitedToGroups { get; }
- public IList<IDiscountRule> GetRequirementRules()
- {
- throw new NotImplementedException();
- }
+ public IList<IDiscountRule> GetRequirementRules()
+ {
+ throw new NotImplementedException();
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Extensions/CommonExtensionsTests.cs b/src/Tests/Grand.Infrastructure.Tests/Extensions/CommonExtensionsTests.cs
index 7881348eb..ec9f733c7 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Extensions/CommonExtensionsTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Extensions/CommonExtensionsTests.cs
@@ -1,47 +1,48 @@
using Grand.Infrastructure.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.Extensions
+namespace Grand.Infrastructure.Tests.Extensions;
+
+[TestClass]
+public class CommonExtensionsTests
{
- [TestClass()]
- public class CommonExtensionsTests
+ [TestMethod]
+ public void ModifyQueryStringTest_url_withoutparam()
{
- [TestMethod()]
- public void ModifyQueryStringTest_url_withoutparam()
- {
- var url = new Uri("http://google.com/computers");
- var param = "param";
- var value = "value";
- var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
- Assert.AreEqual(query, $"/computers?{param}={value}");
- }
- [TestMethod()]
- public void ModifyQueryStringTest_url_with1param()
- {
- var url = new Uri("http://google.com/computers?param=aaa");
- var param = "param";
- var value = "value";
- var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
- Assert.AreEqual(query, $"/computers?{param}={value}");
- }
- [TestMethod()]
- public void ModifyQueryStringTest_url_with2params()
- {
- var url = new Uri("http://google.com/computers?param=bbb&param2=cccc");
- var param = "param";
- var value = "value";
- var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
- Assert.AreEqual(query, $"/computers?param2=cccc&{param}={value}");
- }
- [TestMethod()]
- public void ModifyQueryStringTest_url_with3params()
- {
- var url = new Uri("http://google.com/computers?vvv=azaz&param=bbb&param2=cccc");
- var param = "param";
- var value = "value";
- var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
- Assert.AreEqual(query, $"/computers?vvv=azaz&param2=cccc&{param}={value}");
- }
+ var url = new Uri("http://google.com/computers");
+ var param = "param";
+ var value = "value";
+ var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
+ Assert.AreEqual(query, $"/computers?{param}={value}");
+ }
+
+ [TestMethod]
+ public void ModifyQueryStringTest_url_with1param()
+ {
+ var url = new Uri("http://google.com/computers?param=aaa");
+ var param = "param";
+ var value = "value";
+ var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
+ Assert.AreEqual(query, $"/computers?{param}={value}");
+ }
+ [TestMethod]
+ public void ModifyQueryStringTest_url_with2params()
+ {
+ var url = new Uri("http://google.com/computers?param=bbb&param2=cccc");
+ var param = "param";
+ var value = "value";
+ var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
+ Assert.AreEqual(query, $"/computers?param2=cccc&{param}={value}");
+ }
+
+ [TestMethod]
+ public void ModifyQueryStringTest_url_with3params()
+ {
+ var url = new Uri("http://google.com/computers?vvv=azaz&param=bbb&param2=cccc");
+ var param = "param";
+ var value = "value";
+ var query = CommonExtensions.ModifyQueryString(url.ToString(), param, value);
+ Assert.AreEqual(query, $"/computers?vvv=azaz&param2=cccc&{param}={value}");
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Extensions/ProviderExtensionsTests.cs b/src/Tests/Grand.Infrastructure.Tests/Extensions/ProviderExtensionsTests.cs
index 36fd7802a..348a16a9f 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Extensions/ProviderExtensionsTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Extensions/ProviderExtensionsTests.cs
@@ -1,66 +1,70 @@
-using Grand.Infrastructure.Extensions;
+using Grand.Domain.Customers;
+using Grand.Domain.Stores;
+using Grand.Infrastructure.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.Extensions
+namespace Grand.Infrastructure.Tests.Extensions;
+
+[TestClass]
+public class ProviderExtensionsTests
{
- [TestClass()]
- public class ProviderExtensionsTests
+ [TestMethod]
+ public void IsAuthenticateStoreTest_True()
+ {
+ var discountProvider = new DiscountProviderTest(["store1", "store2"], new List<string> { "group1" });
+ Assert.IsTrue(discountProvider.IsAuthenticateStore(new Store { Id = "store1" }));
+ }
+
+ [TestMethod]
+ public void IsAuthenticateStoreTest_True_NoStores()
+ {
+ var discountProvider = new DiscountProviderTest([], new List<string> { "group1" });
+ Assert.IsTrue(discountProvider.IsAuthenticateStore(new Store { Id = "store1" }));
+ }
+
+ [TestMethod]
+ public void IsAuthenticateStoreTest_False()
+ {
+ var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
+ Assert.IsFalse(discountProvider.IsAuthenticateStore(new Store { Id = "store1" }));
+ }
+
+ [TestMethod]
+ public void IsAuthenticateStoreTestId_True()
{
+ var discountProvider = new DiscountProviderTest(["store1", "store2"], new List<string> { "group1" });
+ Assert.IsTrue(discountProvider.IsAuthenticateStore("store1"));
+ }
- [TestMethod()]
- public void IsAuthenticateStoreTest_True()
- {
- var discountProvider = new DiscountProviderTest(["store1", "store2"], new List<string> { "group1" });
- Assert.IsTrue(discountProvider.IsAuthenticateStore(new Domain.Stores.Store { Id = "store1" }));
- }
- [TestMethod()]
- public void IsAuthenticateStoreTest_True_NoStores()
- {
- var discountProvider = new DiscountProviderTest([], new List<string> { "group1" });
- Assert.IsTrue(discountProvider.IsAuthenticateStore(new Domain.Stores.Store { Id = "store1" }));
- }
- [TestMethod()]
- public void IsAuthenticateStoreTest_False()
- {
- var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
- Assert.IsFalse(discountProvider.IsAuthenticateStore(new Domain.Stores.Store { Id = "store1" }));
- }
+ [TestMethod]
+ public void IsAuthenticateStoreTestId_True_NoStores()
+ {
+ var discountProvider = new DiscountProviderTest([], new List<string> { "group1" });
+ Assert.IsTrue(discountProvider.IsAuthenticateStore("store1"));
+ }
- [TestMethod()]
- public void IsAuthenticateStoreTestId_True()
- {
- var discountProvider = new DiscountProviderTest(["store1", "store2"], new List<string> { "group1" });
- Assert.IsTrue(discountProvider.IsAuthenticateStore("store1"));
- }
- [TestMethod()]
- public void IsAuthenticateStoreTestId_True_NoStores()
- {
- var discountProvider = new DiscountProviderTest([], new List<string> { "group1" });
- Assert.IsTrue(discountProvider.IsAuthenticateStore("store1"));
- }
- [TestMethod()]
- public void IsAuthenticateStoreTestId_False()
- {
- var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
- Assert.IsFalse(discountProvider.IsAuthenticateStore("store1"));
- }
+ [TestMethod]
+ public void IsAuthenticateStoreTestId_False()
+ {
+ var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
+ Assert.IsFalse(discountProvider.IsAuthenticateStore("store1"));
+ }
- [TestMethod()]
- public void IsAuthenticateGroupTest_True()
- {
- var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
- var customer = new Domain.Customers.Customer();
- customer.Groups.Add("group1");
- Assert.IsTrue(discountProvider.IsAuthenticateGroup(customer));
- }
+ [TestMethod]
+ public void IsAuthenticateGroupTest_True()
+ {
+ var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
+ var customer = new Customer();
+ customer.Groups.Add("group1");
+ Assert.IsTrue(discountProvider.IsAuthenticateGroup(customer));
+ }
- [TestMethod()]
- public void IsAuthenticateGroupTest_False()
- {
- var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
- var customer = new Domain.Customers.Customer();
- customer.Groups.Add("group2");
- Assert.IsFalse(discountProvider.IsAuthenticateGroup(customer));
- }
+ [TestMethod]
+ public void IsAuthenticateGroupTest_False()
+ {
+ var discountProvider = new DiscountProviderTest(["store2"], new List<string> { "group1" });
+ var customer = new Customer();
+ customer.Groups.Add("group2");
+ Assert.IsFalse(discountProvider.IsAuthenticateGroup(customer));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/MigrationTest.cs b/src/Tests/Grand.Infrastructure.Tests/MigrationTest.cs
index 2bd42af32..c4b5f4339 100644
--- a/src/Tests/Grand.Infrastructure.Tests/MigrationTest.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/MigrationTest.cs
@@ -1,37 +1,36 @@
using Grand.Data;
using Grand.Infrastructure.Migrations;
-namespace Grand.Infrastructure.Tests
+namespace Grand.Infrastructure.Tests;
+
+public class MigrationTest1 : IMigration
{
- public class MigrationTest1 : IMigration
- {
- public int Priority => 0;
+ public int Priority => 0;
- public DbVersion Version => new DbVersion(int.Parse(GrandVersion.MajorVersion), int.Parse(GrandVersion.MinorVersion));
+ public DbVersion Version => new(int.Parse(GrandVersion.MajorVersion), int.Parse(GrandVersion.MinorVersion));
- public Guid Identity => Guid.NewGuid();
+ public Guid Identity => Guid.NewGuid();
- public string Name => "SampleMigration";
+ public string Name => "SampleMigration";
- public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
- {
- return true;
- }
- }
- public class MigrationTest2 : IMigration
+ public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
{
- public int Priority => 0;
+ return true;
+ }
+}
- public DbVersion Version => new DbVersion(int.Parse(GrandVersion.MajorVersion)+1, int.Parse(GrandVersion.MinorVersion));
+public class MigrationTest2 : IMigration
+{
+ public int Priority => 0;
- public Guid Identity => Guid.NewGuid();
+ public DbVersion Version => new(int.Parse(GrandVersion.MajorVersion) + 1, int.Parse(GrandVersion.MinorVersion));
- public string Name => "SampleMigration";
+ public Guid Identity => Guid.NewGuid();
- public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
- {
- return true;
- }
- }
+ public string Name => "SampleMigration";
-}
+ public bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider)
+ {
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Migrations/DbVersionTests.cs b/src/Tests/Grand.Infrastructure.Tests/Migrations/DbVersionTests.cs
index bf4b7b82c..1e4d5e907 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Migrations/DbVersionTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Migrations/DbVersionTests.cs
@@ -1,54 +1,53 @@
using Grand.Infrastructure.Migrations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.Migrations
+namespace Grand.Infrastructure.Tests.Migrations;
+
+[TestClass]
+public class DbVersionTests
{
- [TestClass()]
- public class DbVersionTests
+ [TestMethod]
+ public void CompareToTest_Greater_Major()
{
- [TestMethod()]
- public void CompareToTest_Greater_Major()
- {
- var dbVersion1 = new DbVersion(1, 0);
- var dbVersion2 = new DbVersion(2, 0);
- var result = dbVersion2.CompareTo(dbVersion1);
- Assert.AreEqual(result, 1);
- }
+ var dbVersion1 = new DbVersion(1, 0);
+ var dbVersion2 = new DbVersion(2, 0);
+ var result = dbVersion2.CompareTo(dbVersion1);
+ Assert.AreEqual(result, 1);
+ }
- [TestMethod()]
- public void CompareToTest_Lower_Major()
- {
- var dbVersion1 = new DbVersion(1, 0);
- var dbVersion2 = new DbVersion(2, 0);
- var result = dbVersion1.CompareTo(dbVersion2);
- Assert.AreEqual(result, -1);
- }
+ [TestMethod]
+ public void CompareToTest_Lower_Major()
+ {
+ var dbVersion1 = new DbVersion(1, 0);
+ var dbVersion2 = new DbVersion(2, 0);
+ var result = dbVersion1.CompareTo(dbVersion2);
+ Assert.AreEqual(result, -1);
+ }
- [TestMethod()]
- public void CompareToTest_Greater_Minor()
- {
- var dbVersion1 = new DbVersion(2, 0);
- var dbVersion2 = new DbVersion(2, 1);
- var result = dbVersion2.CompareTo(dbVersion1);
- Assert.AreEqual(result, 1);
- }
+ [TestMethod]
+ public void CompareToTest_Greater_Minor()
+ {
+ var dbVersion1 = new DbVersion(2, 0);
+ var dbVersion2 = new DbVersion(2, 1);
+ var result = dbVersion2.CompareTo(dbVersion1);
+ Assert.AreEqual(result, 1);
+ }
- [TestMethod()]
- public void CompareToTest_Lower_Minor()
- {
- var dbVersion1 = new DbVersion(2, 0);
- var dbVersion2 = new DbVersion(2, 1);
- var result = dbVersion1.CompareTo(dbVersion2);
- Assert.AreEqual(result, -1);
- }
- [TestMethod()]
- public void CompareToTest_Eq()
- {
- var dbVersion1 = new DbVersion(2, 0);
- var dbVersion2 = new DbVersion(2, 0);
- var result = dbVersion1.CompareTo(dbVersion2);
- Assert.AreEqual(result, 0);
- }
+ [TestMethod]
+ public void CompareToTest_Lower_Minor()
+ {
+ var dbVersion1 = new DbVersion(2, 0);
+ var dbVersion2 = new DbVersion(2, 1);
+ var result = dbVersion1.CompareTo(dbVersion2);
+ Assert.AreEqual(result, -1);
+ }
+ [TestMethod]
+ public void CompareToTest_Eq()
+ {
+ var dbVersion1 = new DbVersion(2, 0);
+ var dbVersion2 = new DbVersion(2, 0);
+ var result = dbVersion1.CompareTo(dbVersion2);
+ Assert.AreEqual(result, 0);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Migrations/MigrationManagerTests.cs b/src/Tests/Grand.Infrastructure.Tests/Migrations/MigrationManagerTests.cs
index f348d67d0..1239d0541 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Migrations/MigrationManagerTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Migrations/MigrationManagerTests.cs
@@ -1,25 +1,24 @@
using Grand.Infrastructure.Migrations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.Migrations
+namespace Grand.Infrastructure.Tests.Migrations;
+
+[TestClass]
+public class MigrationManagerTests
{
- [TestClass()]
- public class MigrationManagerTests
- {
- MigrationManager migrationManager = new();
+ private readonly MigrationManager migrationManager = new();
- [TestMethod()]
- public void GetAllMigrationsTest()
- {
- var result = migrationManager.GetAllMigrations();
- Assert.IsTrue(result.Count() == 2);
- }
+ [TestMethod]
+ public void GetAllMigrationsTest()
+ {
+ var result = migrationManager.GetAllMigrations();
+ Assert.IsTrue(result.Count() == 2);
+ }
- [TestMethod()]
- public void GetCurrentMigrationsTest()
- {
- var result = migrationManager.GetCurrentMigrations();
- Assert.IsTrue(result.Count() == 1);
- }
+ [TestMethod]
+ public void GetCurrentMigrationsTest()
+ {
+ var result = migrationManager.GetCurrentMigrations();
+ Assert.IsTrue(result.Count() == 1);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Plugins/BasePluginTests.cs b/src/Tests/Grand.Infrastructure.Tests/Plugins/BasePluginTests.cs
index 75273a440..3017f0686 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Plugins/BasePluginTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Plugins/BasePluginTests.cs
@@ -1,54 +1,54 @@
using Grand.Infrastructure.Plugins;
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using TestContext = NUnit.Framework.TestContext;
-namespace Grand.Infrastructure.Tests.Plugins
+namespace Grand.Infrastructure.Tests.Plugins;
+
+[TestClass]
+public class BasePluginTests
{
- [TestClass()]
- public class BasePluginTests
+ private SampleBasePlugin sampleBasePlugin;
+
+ [TestInitialize]
+ public void Init()
+ {
+ CommonPath.BaseDirectory = TestContext.CurrentContext.TestDirectory;
+ if (File.Exists(CommonPath.InstalledPluginsFilePath))
+ File.Delete(CommonPath.InstalledPluginsFilePath);
+
+ sampleBasePlugin = new SampleBasePlugin();
+ }
+
+ [TestMethod]
+ public void ConfigurationUrlTest()
+ {
+ Assert.IsNotNull(sampleBasePlugin.ConfigurationUrl());
+ }
+
+ [TestMethod]
+ public async Task InstallTest()
+ {
+ await sampleBasePlugin.Install();
+ var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
+ Assert.IsNotNull(plugins);
+ Assert.AreEqual("SamplePlugin", plugins.FirstOrDefault());
+ }
+
+ [TestMethod]
+ public async Task UninstallTest_WithInstall()
+ {
+ await sampleBasePlugin.Install();
+ await sampleBasePlugin.Uninstall();
+ var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
+ Assert.AreEqual(0, plugins.Count);
+ }
+
+ [TestMethod]
+ public async Task UninstallTest()
{
- SampleBasePlugin sampleBasePlugin;
-
- [TestInitialize()]
- public void Init()
- {
- CommonPath.BaseDirectory = NUnit.Framework.TestContext.CurrentContext.TestDirectory;
- if (File.Exists(CommonPath.InstalledPluginsFilePath))
- File.Delete(CommonPath.InstalledPluginsFilePath);
-
- sampleBasePlugin = new SampleBasePlugin();
-
- }
- [TestMethod()]
- public void ConfigurationUrlTest()
- {
- Assert.IsNotNull(sampleBasePlugin.ConfigurationUrl());
- }
-
- [TestMethod()]
- public async Task InstallTest()
- {
- await sampleBasePlugin.Install();
- var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
- Assert.IsNotNull(plugins);
- Assert.AreEqual("SamplePlugin", plugins.FirstOrDefault());
- }
-
- [TestMethod()]
- public async Task UninstallTest_WithInstall()
- {
- await sampleBasePlugin.Install();
- await sampleBasePlugin.Uninstall();
- var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
- Assert.AreEqual(0, plugins.Count);
- }
-
- [TestMethod()]
- public async Task UninstallTest()
- {
- await sampleBasePlugin.Uninstall();
- var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
- Assert.AreEqual(0, plugins.Count);
- }
+ await sampleBasePlugin.Uninstall();
+ var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
+ Assert.AreEqual(0, plugins.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Plugins/PluginExtensionsTests.cs b/src/Tests/Grand.Infrastructure.Tests/Plugins/PluginExtensionsTests.cs
index 7544d6869..be5981772 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Plugins/PluginExtensionsTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Plugins/PluginExtensionsTests.cs
@@ -1,33 +1,35 @@
using Grand.Infrastructure.Plugins;
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
+using TestContext = NUnit.Framework.TestContext;
-namespace Grand.Infrastructure.Tests.Plugins
+namespace Grand.Infrastructure.Tests.Plugins;
+
+[TestClass]
+public class PluginExtensionsTests
{
- [TestClass()]
- public class PluginExtensionsTests
+ private readonly SampleBasePlugin sampleBasePlugin;
+
+ public PluginExtensionsTests()
{
- SampleBasePlugin sampleBasePlugin;
- public PluginExtensionsTests()
- {
- CommonPath.BaseDirectory = NUnit.Framework.TestContext.CurrentContext.TestDirectory;
- sampleBasePlugin = new SampleBasePlugin();
- }
+ CommonPath.BaseDirectory = TestContext.CurrentContext.TestDirectory;
+ sampleBasePlugin = new SampleBasePlugin();
+ }
- [TestMethod()]
- public async Task ParseInstalledPluginsFileTest()
- {
- await sampleBasePlugin.Install();
- var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
- Assert.IsNotNull(plugins);
- }
+ [TestMethod]
+ public async Task ParseInstalledPluginsFileTest()
+ {
+ await sampleBasePlugin.Install();
+ var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
+ Assert.IsNotNull(plugins);
+ }
- [TestMethod()]
- public async Task SaveInstalledPluginsFileTest()
- {
- await PluginExtensions.SaveInstalledPluginsFile(new List<string> { "plugin1", "plugin2" }, CommonPath.InstalledPluginsFilePath);
- var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
- Assert.AreEqual(2, plugins.Count);
- }
+ [TestMethod]
+ public async Task SaveInstalledPluginsFileTest()
+ {
+ await PluginExtensions.SaveInstalledPluginsFile(new List<string> { "plugin1", "plugin2" },
+ CommonPath.InstalledPluginsFilePath);
+ var plugins = PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);
+ Assert.AreEqual(2, plugins.Count);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Plugins/SampleBasePlugin.cs b/src/Tests/Grand.Infrastructure.Tests/Plugins/SampleBasePlugin.cs
index b6f97f379..7c552d518 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Plugins/SampleBasePlugin.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Plugins/SampleBasePlugin.cs
@@ -1,23 +1,18 @@
using Grand.Infrastructure.Plugins;
-namespace Grand.Infrastructure.Tests.Plugins
+namespace Grand.Infrastructure.Tests.Plugins;
+
+public class SampleBasePlugin : BasePlugin, IPlugin
{
- public class SampleBasePlugin : BasePlugin, IPlugin
- {
- private PluginInfo _pluginInfo = new() {
- Author = "grandnode",
- DisplayOrder = 0,
- FriendlyName = "sample plugin",
- SystemName = "SamplePlugin"
- };
+ public override PluginInfo PluginInfo { get; set; } = new() {
+ Author = "grandnode",
+ DisplayOrder = 0,
+ FriendlyName = "sample plugin",
+ SystemName = "SamplePlugin"
+ };
- public override PluginInfo PluginInfo {
- get => _pluginInfo;
- set => _pluginInfo = value;
- }
- public override string ConfigurationUrl()
- {
- return "sample";
- }
+ public override string ConfigurationUrl()
+ {
+ return "sample";
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/BoolTypeConverterTests.cs b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/BoolTypeConverterTests.cs
index 1e525b220..d06ac1364 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/BoolTypeConverterTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/BoolTypeConverterTests.cs
@@ -1,37 +1,38 @@
using Grand.Infrastructure.TypeConverters.Converter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.TypeConverters.Converter
+namespace Grand.Infrastructure.Tests.TypeConverters.Converter;
+
+[TestClass]
+public class BoolTypeConverterTests
{
- [TestClass()]
- public class BoolTypeConverterTests
+ private readonly BoolTypeConverter boolTypeConverter = new();
+
+ [TestMethod]
+ public void ConvertFromTest_Null_False()
{
- BoolTypeConverter boolTypeConverter = new();
+ var result = (bool)boolTypeConverter.ConvertFrom(null);
+ Assert.IsFalse(result);
+ }
- [TestMethod()]
- public void ConvertFromTest_Null_False()
- {
- var result = (bool)boolTypeConverter.ConvertFrom(null);
- Assert.IsFalse(result);
- }
+ [TestMethod]
+ public void ConvertFromTest_string_True()
+ {
+ var result = (bool)boolTypeConverter.ConvertFrom("true");
+ Assert.IsTrue(result);
+ }
- [TestMethod()]
- public void ConvertFromTest_string_True()
- {
- var result = (bool)boolTypeConverter.ConvertFrom("true");
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public void ConvertFromTest_String_True()
- {
- var result = (bool)boolTypeConverter.ConvertFrom("True");
- Assert.IsTrue(result);
- }
- [TestMethod()]
- public void ConvertFromTest_int_False()
- {
- var result = (bool)boolTypeConverter.ConvertFrom(0);
- Assert.IsFalse(result);
- }
+ [TestMethod]
+ public void ConvertFromTest_String_True()
+ {
+ var result = (bool)boolTypeConverter.ConvertFrom("True");
+ Assert.IsTrue(result);
+ }
+
+ [TestMethod]
+ public void ConvertFromTest_int_False()
+ {
+ var result = (bool)boolTypeConverter.ConvertFrom(0);
+ Assert.IsFalse(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CaptchaInterfaceConverter.cs b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CaptchaInterfaceConverter.cs
index 52a80f703..a63ed0964 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CaptchaInterfaceConverter.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CaptchaInterfaceConverter.cs
@@ -4,10 +4,10 @@ using System.Text.Json;
namespace Grand.Infrastructure.Tests.TypeConverters.Converter;
-[TestClass()]
+[TestClass]
public class CaptchaInterfaceConverter
{
- [TestMethod()]
+ [TestMethod]
public void ConvertFrom_CaptchaObject_To_Json()
{
//Arrange
@@ -22,11 +22,13 @@ public class CaptchaInterfaceConverter
//Act
var jsonString = JsonSerializer.Serialize(sample);
//Assert
- var expJson = "{\"CaptchaValidModel\":{\"ReCaptchaChallengeField\":\"zzz\",\"ReCaptchaResponseField\":\"yyy\",\"ReCaptchaResponseValue\":\"uuu\",\"ReCaptchaResponse\":\"xxx\"}}";
-
+ var expJson =
+ "{\"CaptchaValidModel\":{\"ReCaptchaChallengeField\":\"zzz\",\"ReCaptchaResponseField\":\"yyy\",\"ReCaptchaResponseValue\":\"uuu\",\"ReCaptchaResponse\":\"xxx\"}}";
+
Assert.AreEqual(expJson, jsonString);
}
- [TestMethod()]
+
+ [TestMethod]
public void ConvertFrom_CaptchaNullObject_To_Json()
{
//Arrange
@@ -34,27 +36,29 @@ public class CaptchaInterfaceConverter
//Act
var jsonString = JsonSerializer.Serialize(sample);
//Assert
- var expJson = "{\"CaptchaValidModel\":{\"ReCaptchaChallengeField\":null,\"ReCaptchaResponseField\":null,\"ReCaptchaResponseValue\":null,\"ReCaptchaResponse\":null}}";
+ var expJson =
+ "{\"CaptchaValidModel\":{\"ReCaptchaChallengeField\":null,\"ReCaptchaResponseField\":null,\"ReCaptchaResponseValue\":null,\"ReCaptchaResponse\":null}}";
Assert.AreEqual(expJson, jsonString);
-
}
- [TestMethod()]
+ [TestMethod]
public void ConvertFrom_Json_To_CaptchaObject()
{
//Arrange
- var json = "{\"CaptchaValidModel\":{\"ReCaptchaChallengeField\":\"zzz\",\"ReCaptchaResponseField\":\"yyy\",\"ReCaptchaResponseValue\":\"uuu\",\"ReCaptchaResponse\":\"xxx\"}}";
+ var json =
+ "{\"CaptchaValidModel\":{\"ReCaptchaChallengeField\":\"zzz\",\"ReCaptchaResponseField\":\"yyy\",\"ReCaptchaResponseValue\":\"uuu\",\"ReCaptchaResponse\":\"xxx\"}}";
//Act
var sample = JsonSerializer.Deserialize<SampleClass>(json);
//Assert
Assert.IsNotNull(sample);
- Assert.AreEqual("zzz",sample.CaptchaValidModel.ReCaptchaChallengeField);
- Assert.AreEqual("yyy",sample.CaptchaValidModel.ReCaptchaResponseField);
- Assert.AreEqual("uuu",sample.CaptchaValidModel.ReCaptchaResponseValue);
- Assert.AreEqual("xxx",sample.CaptchaValidModel.ReCaptchaResponse);
+ Assert.AreEqual("zzz", sample.CaptchaValidModel.ReCaptchaChallengeField);
+ Assert.AreEqual("yyy", sample.CaptchaValidModel.ReCaptchaResponseField);
+ Assert.AreEqual("uuu", sample.CaptchaValidModel.ReCaptchaResponseValue);
+ Assert.AreEqual("xxx", sample.CaptchaValidModel.ReCaptchaResponse);
}
- [TestMethod()]
+
+ [TestMethod]
public void ConvertFrom_JsonEmptyCaptcha_To_CaptchaObject()
{
//Arrange
@@ -69,7 +73,7 @@ public class CaptchaInterfaceConverter
Assert.IsNull(sample.CaptchaValidModel.ReCaptchaResponseValue);
Assert.IsNull(sample.CaptchaValidModel.ReCaptchaResponse);
}
-
+
public class SampleClass
{
public ICaptchaValidModel CaptchaValidModel { get; set; } = new CaptchaModel();
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CustomAttributeListTypeConverterTests.cs b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CustomAttributeListTypeConverterTests.cs
index 267f0c00e..83eb116e5 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CustomAttributeListTypeConverterTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/CustomAttributeListTypeConverterTests.cs
@@ -2,48 +2,48 @@
using Grand.Infrastructure.TypeConverters.Converter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.TypeConverters.Converter
+namespace Grand.Infrastructure.Tests.TypeConverters.Converter;
+
+[TestClass]
+public class CustomAttributeListTypeConverterTests
{
- [TestClass()]
- public class CustomAttributeListTypeConverterTests
+ private readonly CustomAttributeListTypeConverter _converter = new();
+
+ [TestMethod]
+ public void CanConvertFromTest_True()
{
- CustomAttributeListTypeConverter _converter = new();
+ Assert.IsTrue(_converter.CanConvertFrom(typeof(string)));
+ }
- [TestMethod()]
- public void CanConvertFromTest_True()
- {
- Assert.IsTrue(_converter.CanConvertFrom(typeof(string)));
- }
+ [TestMethod]
+ public void CanConvertFromTest_False()
+ {
+ Assert.IsFalse(_converter.CanConvertFrom(typeof(decimal)));
+ }
- [TestMethod()]
- public void CanConvertFromTest_False()
- {
- Assert.IsFalse(_converter.CanConvertFrom(typeof(decimal)));
- }
+ [TestMethod]
+ public void ConvertFromTest_NotNull()
+ {
+ var str = "[{\"Key\":\"FirstName\",\"Value\":\"Lucas\"},{\"Key\":\"LastName\",\"Value\":\"Scott\"}]";
+ var converted = _converter.ConvertFrom(str);
+ Assert.IsNotNull(converted);
+ }
- [TestMethod()]
- public void ConvertFromTest_NotNull()
- {
- var str = "[{\"Key\":\"FirstName\",\"Value\":\"Lucas\"},{\"Key\":\"LastName\",\"Value\":\"Scott\"}]";
- var converted = _converter.ConvertFrom(str);
- Assert.IsNotNull(converted);
- }
- [TestMethod()]
- public void ConvertFromTest_Null()
- {
- var converted = _converter.ConvertFrom("test");
- Assert.IsNull(converted);
- }
+ [TestMethod]
+ public void ConvertFromTest_Null()
+ {
+ var converted = _converter.ConvertFrom("test");
+ Assert.IsNull(converted);
+ }
- [TestMethod()]
- public void ConvertToTest()
- {
- List<CustomAttribute> customAttributes = [
- new CustomAttribute { Key = "FirstName", Value = "Lucas" },
- new CustomAttribute { Key = "LastName", Value = "Scott" }
- ];
- var result = _converter.ConvertTo(customAttributes, typeof(string));
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public void ConvertToTest()
+ {
+ List<CustomAttribute> customAttributes = [
+ new CustomAttribute { Key = "FirstName", Value = "Lucas" },
+ new CustomAttribute { Key = "LastName", Value = "Scott" }
+ ];
+ var result = _converter.ConvertTo(customAttributes, typeof(string));
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/GenericListTypeConverterTests.cs b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/GenericListTypeConverterTests.cs
index 5d8c80f37..1db01a53d 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/GenericListTypeConverterTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/GenericListTypeConverterTests.cs
@@ -1,61 +1,63 @@
using Grand.Infrastructure.TypeConverters.Converter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.TypeConverters.Converter
+namespace Grand.Infrastructure.Tests.TypeConverters.Converter;
+
+[TestClass]
+public class GenericListTypeConverterTests
{
- [TestClass()]
- public class GenericListTypeConverterTests
+ private readonly GenericListTypeConverter<double> _doubleconverter = new();
+ private readonly GenericListTypeConverter<int> _intconverter = new();
+ private readonly GenericListTypeConverter<string> _stringconverter = new();
+
+ [TestMethod]
+ public void CanConvertFromTest_string_true()
+ {
+ Assert.IsTrue(_intconverter.CanConvertFrom(typeof(string)));
+ Assert.IsTrue(_stringconverter.CanConvertFrom(typeof(string)));
+ Assert.IsTrue(_doubleconverter.CanConvertFrom(typeof(string)));
+ }
+
+ [TestMethod]
+ public void CanConvertFromTest_int_false()
+ {
+ Assert.IsFalse(_intconverter.CanConvertFrom(typeof(int)));
+ Assert.IsFalse(_stringconverter.CanConvertFrom(typeof(int)));
+ Assert.IsFalse(_doubleconverter.CanConvertFrom(typeof(int)));
+ }
+
+ [TestMethod]
+ public void ConvertFromTest_List_string()
+ {
+ var mylist = (List<string>)_stringconverter.ConvertFrom("str1, str2");
+ Assert.IsNotNull(mylist);
+ Assert.IsTrue(mylist.Count > 0);
+ }
+
+ [TestMethod]
+ public void ConvertFromTest_List_int()
+ {
+ var mylist = (List<int>)_intconverter.ConvertFrom("1, 2");
+ Assert.IsNotNull(mylist);
+ Assert.IsTrue(mylist.Count > 0);
+ }
+
+ [TestMethod]
+ public void ConvertFromTest_list_double()
+ {
+ var mylist = (List<double>)_doubleconverter.ConvertFrom("1.1, 2");
+ Assert.IsNotNull(mylist);
+ Assert.IsTrue(mylist.Count == 2);
+ }
+
+ [TestMethod]
+ public void ConvertToTest()
{
- GenericListTypeConverter<int> _intconverter = new();
- GenericListTypeConverter<double> _doubleconverter = new();
- GenericListTypeConverter<string> _stringconverter = new();
-
- [TestMethod()]
- public void CanConvertFromTest_string_true()
- {
- Assert.IsTrue(_intconverter.CanConvertFrom(typeof(string)));
- Assert.IsTrue(_stringconverter.CanConvertFrom(typeof(string)));
- Assert.IsTrue(_doubleconverter.CanConvertFrom(typeof(string)));
- }
-
- [TestMethod()]
- public void CanConvertFromTest_int_false()
- {
- Assert.IsFalse(_intconverter.CanConvertFrom(typeof(int)));
- Assert.IsFalse(_stringconverter.CanConvertFrom(typeof(int)));
- Assert.IsFalse(_doubleconverter.CanConvertFrom(typeof(int)));
- }
-
- [TestMethod()]
- public void ConvertFromTest_List_string()
- {
- var mylist = (List<string>)_stringconverter.ConvertFrom("str1, str2");
- Assert.IsNotNull(mylist);
- Assert.IsTrue(mylist.Count > 0);
- }
- [TestMethod()]
- public void ConvertFromTest_List_int()
- {
- var mylist = (List<int>)_intconverter.ConvertFrom("1, 2");
- Assert.IsNotNull(mylist);
- Assert.IsTrue(mylist.Count > 0);
- }
- [TestMethod()]
- public void ConvertFromTest_list_double()
- {
- var mylist = (List<double>)_doubleconverter.ConvertFrom("1.1, 2");
- Assert.IsNotNull(mylist);
- Assert.IsTrue(mylist.Count == 2);
- }
- [TestMethod()]
- public void ConvertToTest()
- {
- var str1 = _intconverter.ConvertTo(new List<int> { 1, 2 }, typeof(string));
- Assert.IsNotNull(str1);
- var str2 = _stringconverter.ConvertTo(new List<string> { "1", "2" }, typeof(string));
- Assert.IsNotNull(str2);
- var str3 = _doubleconverter.ConvertTo(new List<double> { 1, 2 }, typeof(string));
- Assert.IsNotNull(str3);
- }
+ var str1 = _intconverter.ConvertTo(new List<int> { 1, 2 }, typeof(string));
+ Assert.IsNotNull(str1);
+ var str2 = _stringconverter.ConvertTo(new List<string> { "1", "2" }, typeof(string));
+ Assert.IsNotNull(str2);
+ var str3 = _doubleconverter.ConvertTo(new List<double> { 1, 2 }, typeof(string));
+ Assert.IsNotNull(str3);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/RefreshTokenTypeConverterTests.cs b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/RefreshTokenTypeConverterTests.cs
index 91bd57ead..9e17d3456 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/RefreshTokenTypeConverterTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/RefreshTokenTypeConverterTests.cs
@@ -2,62 +2,65 @@
using Grand.Infrastructure.TypeConverters.Converter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.TypeConverters.Converter
+namespace Grand.Infrastructure.Tests.TypeConverters.Converter;
+
+[TestClass]
+public class RefreshTokenTypeConverterTests
{
- [TestClass()]
- public class RefreshTokenTypeConverterTests
+ private readonly RefreshTokenTypeConverter refreshTokenTypeConverter = new();
+
+ [TestMethod]
+ public void CanConvertFromTest_string()
+ {
+ Assert.IsTrue(refreshTokenTypeConverter.CanConvertFrom(typeof(string)));
+ }
+
+ [TestMethod]
+ public void CanConvertFromTest_decimal()
+ {
+ Assert.IsFalse(refreshTokenTypeConverter.CanConvertFrom(typeof(decimal)));
+ }
+
+ [TestMethod]
+ public void ConvertFromTest_NotNull()
+ {
+ var refreshToken = refreshTokenTypeConverter.ConvertFrom(
+ "{\"RefreshId\":\"eed7fe9a-a920-4212-be3a-043e31737615\",\"Token\":\"aa7c8eda-9d79-4a70-8936-ee03bcc97daf\",\"ValidTo\":\"2022-09-22T15:42:52.8392185Z\",\"IsActive\":true}");
+ Assert.IsNotNull(refreshToken);
+ }
+
+ [TestMethod]
+ public void ConvertFromTest_Null()
+ {
+ var refreshToken = refreshTokenTypeConverter.ConvertFrom("sdf");
+ Assert.IsNull(refreshToken);
+ }
+
+ [TestMethod]
+ public void ConvertToTest_NotNull()
{
- RefreshTokenTypeConverter refreshTokenTypeConverter = new();
-
- [TestMethod()]
- public void CanConvertFromTest_string()
- {
- Assert.IsTrue(refreshTokenTypeConverter.CanConvertFrom(typeof(string)));
- }
- [TestMethod()]
- public void CanConvertFromTest_decimal()
- {
- Assert.IsFalse(refreshTokenTypeConverter.CanConvertFrom(typeof(decimal)));
- }
-
- [TestMethod()]
- public void ConvertFromTest_NotNull()
- {
- var refreshToken = refreshTokenTypeConverter.ConvertFrom("{\"RefreshId\":\"eed7fe9a-a920-4212-be3a-043e31737615\",\"Token\":\"aa7c8eda-9d79-4a70-8936-ee03bcc97daf\",\"ValidTo\":\"2022-09-22T15:42:52.8392185Z\",\"IsActive\":true}");
- Assert.IsNotNull(refreshToken);
- }
-
- [TestMethod()]
- public void ConvertFromTest_Null()
- {
- var refreshToken = refreshTokenTypeConverter.ConvertFrom("sdf");
- Assert.IsNull(refreshToken);
- }
-
- [TestMethod()]
- public void ConvertToTest_NotNull()
- {
- var refreshToken = new RefreshToken {
- RefreshId = Guid.NewGuid().ToString(),
- Token = Guid.NewGuid().ToString(),
- IsActive = true,
- ValidTo = DateTime.UtcNow.AddDays(1)
- };
- var str = refreshTokenTypeConverter.ConvertTo(refreshToken, typeof(string));
- Assert.IsNotNull(str);
- Assert.IsInstanceOfType(str, typeof(string));
- }
- [TestMethod()]
- public void ConvertToTest_decimal_Exception()
- {
- var refreshToken = new RefreshToken {
- RefreshId = Guid.NewGuid().ToString(),
- Token = Guid.NewGuid().ToString(),
- IsActive = true,
- ValidTo = DateTime.UtcNow.AddDays(1)
- };
-
- Assert.ThrowsException<NotSupportedException>(() => _ = refreshTokenTypeConverter.ConvertTo(refreshToken, typeof(decimal)));
- }
+ var refreshToken = new RefreshToken {
+ RefreshId = Guid.NewGuid().ToString(),
+ Token = Guid.NewGuid().ToString(),
+ IsActive = true,
+ ValidTo = DateTime.UtcNow.AddDays(1)
+ };
+ var str = refreshTokenTypeConverter.ConvertTo(refreshToken, typeof(string));
+ Assert.IsNotNull(str);
+ Assert.IsInstanceOfType(str, typeof(string));
+ }
+
+ [TestMethod]
+ public void ConvertToTest_decimal_Exception()
+ {
+ var refreshToken = new RefreshToken {
+ RefreshId = Guid.NewGuid().ToString(),
+ Token = Guid.NewGuid().ToString(),
+ IsActive = true,
+ ValidTo = DateTime.UtcNow.AddDays(1)
+ };
+
+ Assert.ThrowsException<NotSupportedException>(() =>
+ _ = refreshTokenTypeConverter.ConvertTo(refreshToken, typeof(decimal)));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/ShippingOptionTypeConverterTests.cs b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/ShippingOptionTypeConverterTests.cs
index 0e3571c98..c329c3c43 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/ShippingOptionTypeConverterTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeConverters/Converter/ShippingOptionTypeConverterTests.cs
@@ -2,37 +2,37 @@
using Grand.Infrastructure.TypeConverters.Converter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.TypeConverters.Converter
+namespace Grand.Infrastructure.Tests.TypeConverters.Converter;
+
+[TestClass]
+public class ShippingOptionTypeConverterTests
{
- [TestClass()]
- public class ShippingOptionTypeConverterTests
- {
- ShippingOptionTypeConverter _converter = new();
+ private readonly ShippingOptionTypeConverter _converter = new();
- [TestMethod()]
- public void CanConvertFromTest()
- {
- Assert.IsTrue(_converter.CanConvertFrom(typeof(string)));
- }
+ [TestMethod]
+ public void CanConvertFromTest()
+ {
+ Assert.IsTrue(_converter.CanConvertFrom(typeof(string)));
+ }
- [TestMethod()]
- public void ConvertFromTest()
- {
- var str = "{\"ShippingRateProviderSystemName\":\"Ground\",\"Rate\":10,\"Name\":\"sample\",\"Description\":null}";
- var result = _converter.ConvertFrom(str);
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public void ConvertFromTest()
+ {
+ var str =
+ "{\"ShippingRateProviderSystemName\":\"Ground\",\"Rate\":10,\"Name\":\"sample\",\"Description\":null}";
+ var result = _converter.ConvertFrom(str);
+ Assert.IsNotNull(result);
+ }
- [TestMethod()]
- public void ConvertToTest_NotNull()
- {
- ShippingOption shippingOption = new ShippingOption {
- ShippingRateProviderSystemName = "Ground",
- Name = "sample",
- Rate = 10
- };
- var result = _converter.ConvertTo(shippingOption, typeof(string));
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ public void ConvertToTest_NotNull()
+ {
+ var shippingOption = new ShippingOption {
+ ShippingRateProviderSystemName = "Ground",
+ Name = "sample",
+ Rate = 10
+ };
+ var result = _converter.ConvertTo(shippingOption, typeof(string));
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs b/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs
index 9166559ed..19bbe0292 100644
--- a/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/TypeSearcher/TypeSearcherTests.cs
@@ -1,28 +1,28 @@
using Grand.Infrastructure.Caching;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.TypeSearcher
+namespace Grand.Infrastructure.Tests.TypeSearcher;
+
+[TestClass]
+public class TypeSearcherTests
{
- [TestClass()]
- public class TypeSearcherTests
+ private readonly TypeSearch.TypeSearcher _typeSearcher = new();
+
+ [TestMethod]
+ public void GetAssembliesTest()
{
- private TypeSearch.TypeSearcher _typeSearcher = new();
+ Assert.IsTrue(_typeSearcher.GetAssemblies().Any());
+ }
- [TestMethod()]
- public void GetAssembliesTest()
- {
- Assert.IsTrue(_typeSearcher.GetAssemblies().Any());
- }
+ [TestMethod]
+ public void ClassesOfTypeTest_onlyConcreteClasses_false()
+ {
+ Assert.IsTrue(_typeSearcher.ClassesOfType<ICacheBase>(false).Any());
+ }
- [TestMethod()]
- public void ClassesOfTypeTest_onlyConcreteClasses_false()
- {
- Assert.IsTrue(_typeSearcher.ClassesOfType<ICacheBase>(false).Any());
- }
- [TestMethod()]
- public void ClassesOfTypeTest_onlyConcreteClasses_true()
- {
- Assert.IsFalse(_typeSearcher.ClassesOfType<IWorkContext>(true).Any());
- }
+ [TestMethod]
+ public void ClassesOfTypeTest_onlyConcreteClasses_true()
+ {
+ Assert.IsFalse(_typeSearcher.ClassesOfType<IWorkContext>().Any());
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Validators/FluentValidationFilterTests.cs b/src/Tests/Grand.Infrastructure.Tests/Validators/FluentValidationFilterTests.cs
index 1a1398dce..d9fecf3f8 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Validators/FluentValidationFilterTests.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Validators/FluentValidationFilterTests.cs
@@ -9,108 +9,105 @@ using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.Infrastructure.Tests.Validators
+namespace Grand.Infrastructure.Tests.Validators;
+
+[TestClass]
+public class ValidationFilterTests
{
- [TestClass()]
- public class ValidationFilterTests
+ [TestMethod]
+ public async Task OnActionExecutionAsyncTest_ValidModel()
+ {
+ //arrange
+ var services = new ServiceCollection();
+ services.AddScoped<IValidator<SourceTest>, SourceTestValidator>();
+ var serviceProvider = services.BuildServiceProvider();
+
+ var actionFilter = new ValidationFilter(serviceProvider);
+
+ var httpContext = new DefaultHttpContext {
+ Request = {
+ Method = "POST"
+ }
+ };
+
+ var actionContext = new ActionContext(httpContext,
+ new RouteData(),
+ new ActionDescriptor(),
+ new ModelStateDictionary());
+
+ var actionExecutedContext = new ActionExecutedContext(actionContext,
+ new List<IFilterMetadata>(),
+ null);
+
+ var actionExecutingContext = new ActionExecutingContext(actionContext,
+ new List<IFilterMetadata>(),
+ new Dictionary<string, object>(),
+ null);
+
+ var source = new SourceTest {
+ FirstName = "ABCD",
+ LastName = "ABCD"
+ };
+ actionExecutingContext.ActionArguments["model"] = source;
+
+ //act
+ var next = new ActionExecutionDelegate(() =>
+ Task.FromResult(CreateActionExecutedContext(actionExecutingContext)));
+ await actionFilter.OnActionExecutionAsync(actionExecutingContext, next);
+
+ //assert
+ Assert.IsTrue(actionExecutingContext.ModelState.IsValid);
+ }
+
+ [TestMethod]
+ public async Task OnActionExecutionAsyncTest_NotValidModel()
+ {
+ //arrange
+ var services = new ServiceCollection();
+ services.AddScoped<IValidator<SourceTest>, SourceTestValidator>();
+ var serviceProvider = services.BuildServiceProvider();
+
+ var actionFilter = new ValidationFilter(serviceProvider);
+
+ var httpContext = new DefaultHttpContext {
+ Request = {
+ Method = "POST"
+ }
+ };
+
+ var actionContext = new ActionContext(httpContext,
+ new RouteData(),
+ new ActionDescriptor(),
+ new ModelStateDictionary());
+
+ var actionExecutedContext = new ActionExecutedContext(actionContext,
+ new List<IFilterMetadata>(),
+ null);
+
+ var actionExecutingContext = new ActionExecutingContext(actionContext,
+ new List<IFilterMetadata>(),
+ new Dictionary<string, object>(),
+ null);
+
+ var source = new SourceTest {
+ FirstName = "ABCD"
+ };
+ actionExecutingContext.ActionArguments["model"] = source;
+
+ //act
+ var next = new ActionExecutionDelegate(() =>
+ Task.FromResult(CreateActionExecutedContext(actionExecutingContext)));
+ await actionFilter.OnActionExecutionAsync(actionExecutingContext, next);
+
+ //assert
+ Assert.IsFalse(actionExecutingContext.ModelState.IsValid);
+ }
+
+
+ private static ActionExecutedContext CreateActionExecutedContext(ActionExecutingContext context)
{
- [TestMethod()]
- public async Task OnActionExecutionAsyncTest_ValidModel()
- {
-
- //arrange
- var services = new ServiceCollection();
- services.AddScoped<IValidator<SourceTest>, SourceTestValidator>();
- var serviceProvider = services.BuildServiceProvider();
-
- var actionFilter = new ValidationFilter(serviceProvider);
-
- var httpContext = new DefaultHttpContext {
- Request = {
- Method = "POST"
- }
- };
-
- var actionContext = new ActionContext(httpContext,
- new RouteData(),
- new ActionDescriptor(),
- new ModelStateDictionary());
-
- var actionExecutedContext = new ActionExecutedContext(actionContext,
- new List<IFilterMetadata>(),
- controller: null);
-
- var actionExecutingContext = new ActionExecutingContext(actionContext,
- new List<IFilterMetadata>(),
- new Dictionary<string, object>(),
- controller: null);
-
- var source = new SourceTest {
- FirstName = "ABCD",
- LastName = "ABCD"
-
- };
- actionExecutingContext.ActionArguments["model"] = source;
-
- //act
- var next = new ActionExecutionDelegate(() => Task.FromResult(CreateActionExecutedContext(actionExecutingContext)));
- await actionFilter.OnActionExecutionAsync(actionExecutingContext, next);
-
- //assert
- Assert.IsTrue(actionExecutingContext.ModelState.IsValid);
-
- }
- [TestMethod()]
- public async Task OnActionExecutionAsyncTest_NotValidModel()
- {
-
- //arrange
- var services = new ServiceCollection();
- services.AddScoped<IValidator<SourceTest>, SourceTestValidator>();
- var serviceProvider = services.BuildServiceProvider();
-
- var actionFilter = new ValidationFilter(serviceProvider);
-
- var httpContext = new DefaultHttpContext {
- Request = {
- Method = "POST"
- }
- };
-
- var actionContext = new ActionContext(httpContext,
- new RouteData(),
- new ActionDescriptor(),
- new ModelStateDictionary());
-
- var actionExecutedContext = new ActionExecutedContext(actionContext,
- new List<IFilterMetadata>(),
- controller: null);
-
- var actionExecutingContext = new ActionExecutingContext(actionContext,
- new List<IFilterMetadata>(),
- new Dictionary<string, object>(),
- controller: null);
-
- var source = new SourceTest {
- FirstName = "ABCD"
- };
- actionExecutingContext.ActionArguments["model"] = source;
-
- //act
- var next = new ActionExecutionDelegate(() => Task.FromResult(CreateActionExecutedContext(actionExecutingContext)));
- await actionFilter.OnActionExecutionAsync(actionExecutingContext, next);
-
- //assert
- Assert.IsFalse(actionExecutingContext.ModelState.IsValid);
- }
-
-
-
- private static ActionExecutedContext CreateActionExecutedContext(ActionExecutingContext context)
- {
- return new ActionExecutedContext(context, context.Filters, context.Controller) {
- Result = context.Result
- };
- }
+ return new ActionExecutedContext(context, context.Filters, context.Controller) {
+ Result = context.Result
+ };
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTest.cs b/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTest.cs
index 5f6d5b69b..a96377f33 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTest.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTest.cs
@@ -1,8 +1,7 @@
-namespace Grand.Infrastructure.Tests.Validators
+namespace Grand.Infrastructure.Tests.Validators;
+
+public class SourceTest
{
- public class SourceTest
- {
- public string FirstName { get; set; }
- public string LastName { get; set; }
- }
-}
+ public string FirstName { get; set; }
+ public string LastName { get; set; }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTestValidator.cs b/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTestValidator.cs
index 1f0e38411..28f198a01 100644
--- a/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTestValidator.cs
+++ b/src/Tests/Grand.Infrastructure.Tests/Validators/SourceTestValidator.cs
@@ -1,12 +1,11 @@
using FluentValidation;
-namespace Grand.Infrastructure.Tests.Validators
+namespace Grand.Infrastructure.Tests.Validators;
+
+public class SourceTestValidator : AbstractValidator<SourceTest>
{
- public class SourceTestValidator : AbstractValidator<SourceTest>
+ public SourceTestValidator()
{
- public SourceTestValidator()
- {
- RuleFor(person => person.LastName).NotNull();
- }
+ RuleFor(person => person.LastName).NotNull();
}
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonHelperTests.cs b/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonHelperTests.cs
index 887d5d046..1fe43fd43 100644
--- a/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonHelperTests.cs
+++ b/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonHelperTests.cs
@@ -2,164 +2,169 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Globalization;
-namespace Grand.SharedKernel.Tests.Extensions
+namespace Grand.SharedKernel.Tests.Extensions;
+
+[TestClass]
+public class CommonHelperTests
{
- [TestClass()]
- public class CommonHelperTests
- {
- [TestMethod()]
- [DataRow("email")]
- [DataRow("email@email")]
- [DataRow("email@[email protected]")]
- public void EnsureSubscriberEmailOrThrowTest_ThrowException(string email)
- {
- Assert.ThrowsException<GrandException>(() => CommonHelper.EnsureSubscriberEmailOrThrow(email));
- }
-
- [TestMethod()]
- [DataRow("[email protected]")]
- [DataRow("[email protected]")]
- public void EnsureSubscriberEmailOrThrowTest_Success(string email)
- {
- Assert.IsTrue(CommonHelper.EnsureSubscriberEmailOrThrow(email) == email);
- }
-
- [TestMethod()]
- [DataRow("email")]
- [DataRow("email@email")]
- [DataRow("email@[email protected]")]
- public void IsValidEmailTest_False(string email)
- {
- Assert.IsFalse(CommonHelper.IsValidEmail(email));
- }
-
- [TestMethod()]
- [DataRow("[email protected]")]
- [DataRow("[email protected]")]
- public void IsValidEmailTest_True(string email)
- {
- Assert.IsTrue(CommonHelper.IsValidEmail(email));
- }
-
- [TestMethod()]
- [DataRow(5)]
- [DataRow(7)]
- public void GenerateRandomDigitCodeTest(int length)
- {
- var result = CommonHelper.GenerateRandomDigitCode(length);
-
- Assert.IsNotNull(result);
- Assert.IsTrue(result.Length == length);
- }
-
- [TestMethod()]
- [DataRow(5, 7)]
- [DataRow(6, 10)]
- public void GenerateRandomIntegerTest_True(int min, int max)
- {
- var result = CommonHelper.GenerateRandomInteger(min, max);
-
- Assert.IsTrue(result >= min);
- Assert.IsTrue(result <= max);
- }
-
- [TestMethod()]
- [DataRow(10, 1)]
- public void GenerateRandomIntegerTest_ThrowException(int min, int max)
- {
- Assert.ThrowsException<ArgumentOutOfRangeException>(() => CommonHelper.GenerateRandomInteger(min, max));
- }
-
- [TestMethod()]
- public void EnsureMaximumLengthTest_Value_3_True()
- {
- var str = "value"; var max = 3; string post = null;
- Assert.IsTrue(CommonHelper.EnsureMaximumLength(str, max, post) == "val");
- }
-
- [TestMethod()]
- public void EnsureMaximumLengthTest_Value_10_True()
- {
- var str = "value"; var max = 10; string post = null;
- Assert.IsTrue(CommonHelper.EnsureMaximumLength(str, max, post) == "value");
- }
-
- [TestMethod()]
- public void EnsureMaximumLengthTest_Value_2_Post_True()
- {
- var str = "0123456789000"; var max = 10; var post = "...";
- Assert.IsTrue(CommonHelper.EnsureMaximumLength(str, max, post) == "0123456...");
- }
-
- [TestMethod()]
- [DataRow("value", 1, "...")]
- public void EnsureMaximumLengthTest_ThrowException(string str, int max, string post)
- {
- Assert.ThrowsException<ArgumentOutOfRangeException>(() => CommonHelper.EnsureMaximumLength(str, max, post));
- }
-
- [TestMethod()]
- public void ArraysEqualTest_True()
- {
- Assert.IsTrue(CommonHelper.ArraysEqual(["a1", "a2"], ["a1", "a2"]));
- }
-
- [TestMethod()]
- public void ArraysEqualTest_False()
- {
- Assert.IsFalse(CommonHelper.ArraysEqual(["a1", "a2"], ["a2", "a3"]));
- }
-
- [TestMethod()]
- public void ToTest_True()
- {
- object obj = "sample";
- Assert.IsTrue(obj == CommonHelper.To(obj, typeof(string)));
- }
-
- [TestMethod()]
- public void ToTest_ThrowException()
- {
- object obj = "sample";
- Assert.ThrowsException<ArgumentException>(() => CommonHelper.To(obj, typeof(decimal)));
- }
-
- [TestMethod()]
- public void ConvertEnumTest()
- {
- var value = SampleEnum.Test0;
- Assert.IsTrue(CommonHelper.ConvertEnum(value) == "Test0");
- }
-
- [TestMethod()]
- public void GetDifferenceInYearsTest()
- {
- Assert.IsTrue(CommonHelper.GetDifferenceInYears(new DateTime(2010, 01, 01), new DateTime(2020, 01, 01)) == 10);
- Assert.IsTrue(CommonHelper.GetDifferenceInYears(new DateTime(2010, 02, 01), new DateTime(2020, 01, 01)) == 9);
- Assert.IsTrue(CommonHelper.GetDifferenceInYears(new DateTime(2011, 01, 02), new DateTime(2020, 01, 01)) == 8);
- }
-
- [TestMethod()]
- public void ToTest_T()
- {
- object obj = "sample";
- Assert.IsTrue(obj.ToString() == CommonHelper.To<string>(obj));
- }
-
- [TestMethod()]
- public void ToCultureInfoTest()
- {
- object obj = "sample";
- Assert.IsTrue(obj == CommonHelper.To(obj, typeof(string), CultureInfo.InvariantCulture));
- }
-
- [TestMethod()]
- [DataRow("test")]
- [DataRow(null)]
- public void EnsureNotNullTest(string text)
- {
- var result = CommonHelper.EnsureNotNull(text);
- Assert.IsNotNull(result);
- }
+ [TestMethod]
+ [DataRow("email")]
+ [DataRow("email@email")]
+ [DataRow("email@[email protected]")]
+ public void EnsureSubscriberEmailOrThrowTest_ThrowException(string email)
+ {
+ Assert.ThrowsException<GrandException>(() => CommonHelper.EnsureSubscriberEmailOrThrow(email));
+ }
+
+ [TestMethod]
+ [DataRow("[email protected]")]
+ [DataRow("[email protected]")]
+ public void EnsureSubscriberEmailOrThrowTest_Success(string email)
+ {
+ Assert.IsTrue(CommonHelper.EnsureSubscriberEmailOrThrow(email) == email);
+ }
+
+ [TestMethod]
+ [DataRow("email")]
+ [DataRow("email@email")]
+ [DataRow("email@[email protected]")]
+ public void IsValidEmailTest_False(string email)
+ {
+ Assert.IsFalse(CommonHelper.IsValidEmail(email));
+ }
+
+ [TestMethod]
+ [DataRow("[email protected]")]
+ [DataRow("[email protected]")]
+ public void IsValidEmailTest_True(string email)
+ {
+ Assert.IsTrue(CommonHelper.IsValidEmail(email));
+ }
+
+ [TestMethod]
+ [DataRow(5)]
+ [DataRow(7)]
+ public void GenerateRandomDigitCodeTest(int length)
+ {
+ var result = CommonHelper.GenerateRandomDigitCode(length);
+
+ Assert.IsNotNull(result);
+ Assert.IsTrue(result.Length == length);
+ }
+
+ [TestMethod]
+ [DataRow(5, 7)]
+ [DataRow(6, 10)]
+ public void GenerateRandomIntegerTest_True(int min, int max)
+ {
+ var result = CommonHelper.GenerateRandomInteger(min, max);
+
+ Assert.IsTrue(result >= min);
+ Assert.IsTrue(result <= max);
+ }
+
+ [TestMethod]
+ [DataRow(10, 1)]
+ public void GenerateRandomIntegerTest_ThrowException(int min, int max)
+ {
+ Assert.ThrowsException<ArgumentOutOfRangeException>(() => CommonHelper.GenerateRandomInteger(min, max));
+ }
+
+ [TestMethod]
+ public void EnsureMaximumLengthTest_Value_3_True()
+ {
+ var str = "value";
+ var max = 3;
+ string post = null;
+ Assert.IsTrue(CommonHelper.EnsureMaximumLength(str, max, post) == "val");
+ }
+
+ [TestMethod]
+ public void EnsureMaximumLengthTest_Value_10_True()
+ {
+ var str = "value";
+ var max = 10;
+ string post = null;
+ Assert.IsTrue(CommonHelper.EnsureMaximumLength(str, max, post) == "value");
+ }
+
+ [TestMethod]
+ public void EnsureMaximumLengthTest_Value_2_Post_True()
+ {
+ var str = "0123456789000";
+ var max = 10;
+ var post = "...";
+ Assert.IsTrue(CommonHelper.EnsureMaximumLength(str, max, post) == "0123456...");
+ }
+
+ [TestMethod]
+ [DataRow("value", 1, "...")]
+ public void EnsureMaximumLengthTest_ThrowException(string str, int max, string post)
+ {
+ Assert.ThrowsException<ArgumentOutOfRangeException>(() => CommonHelper.EnsureMaximumLength(str, max, post));
+ }
+
+ [TestMethod]
+ public void ArraysEqualTest_True()
+ {
+ Assert.IsTrue(CommonHelper.ArraysEqual(["a1", "a2"], ["a1", "a2"]));
+ }
+
+ [TestMethod]
+ public void ArraysEqualTest_False()
+ {
+ Assert.IsFalse(CommonHelper.ArraysEqual(["a1", "a2"], ["a2", "a3"]));
+ }
+
+ [TestMethod]
+ public void ToTest_True()
+ {
+ object obj = "sample";
+ Assert.IsTrue(obj == CommonHelper.To(obj, typeof(string)));
+ }
+
+ [TestMethod]
+ public void ToTest_ThrowException()
+ {
+ object obj = "sample";
+ Assert.ThrowsException<ArgumentException>(() => CommonHelper.To(obj, typeof(decimal)));
+ }
+
+ [TestMethod]
+ public void ConvertEnumTest()
+ {
+ var value = SampleEnum.Test0;
+ Assert.IsTrue(CommonHelper.ConvertEnum(value) == "Test0");
+ }
+
+ [TestMethod]
+ public void GetDifferenceInYearsTest()
+ {
+ Assert.IsTrue(CommonHelper.GetDifferenceInYears(new DateTime(2010, 01, 01), new DateTime(2020, 01, 01)) == 10);
+ Assert.IsTrue(CommonHelper.GetDifferenceInYears(new DateTime(2010, 02, 01), new DateTime(2020, 01, 01)) == 9);
+ Assert.IsTrue(CommonHelper.GetDifferenceInYears(new DateTime(2011, 01, 02), new DateTime(2020, 01, 01)) == 8);
+ }
+
+ [TestMethod]
+ public void ToTest_T()
+ {
+ object obj = "sample";
+ Assert.IsTrue(obj.ToString() == CommonHelper.To<string>(obj));
+ }
+
+ [TestMethod]
+ public void ToCultureInfoTest()
+ {
+ object obj = "sample";
+ Assert.IsTrue(obj == CommonHelper.To(obj, typeof(string), CultureInfo.InvariantCulture));
+ }
+
+ [TestMethod]
+ [DataRow("test")]
+ [DataRow(null)]
+ public void EnsureNotNullTest(string text)
+ {
+ var result = CommonHelper.EnsureNotNull(text);
+ Assert.IsNotNull(result);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonPathTests.cs b/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonPathTests.cs
index 106fc1788..11461a6c7 100644
--- a/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonPathTests.cs
+++ b/src/Tests/Grand.SharedKernel.Tests/Extensions/CommonPathTests.cs
@@ -1,37 +1,36 @@
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.SharedKernel.Tests.Extensions
+namespace Grand.SharedKernel.Tests.Extensions;
+
+[TestClass]
+public class CommonPathTests
{
- [TestClass()]
- public class CommonPathTests
+ public CommonPathTests()
{
- public CommonPathTests()
- {
- CommonPath.BaseDirectory = "base";
- CommonPath.WebHostEnvironment = "www";
- }
+ CommonPath.BaseDirectory = "base";
+ CommonPath.WebHostEnvironment = "www";
+ }
- [TestMethod()]
- public void MapPathTest()
- {
- var path = CommonPath.MapPath("path");
- Assert.AreEqual(Path.Combine("base", "path"), path);
- }
+ [TestMethod]
+ public void MapPathTest()
+ {
+ var path = CommonPath.MapPath("path");
+ Assert.AreEqual(Path.Combine("base", "path"), path);
+ }
- [TestMethod()]
- public void WebMapPathTest()
- {
- var path = CommonPath.WebMapPath("path");
- Assert.AreEqual(Path.Combine("www","path"), path);
- }
+ [TestMethod]
+ public void WebMapPathTest()
+ {
+ var path = CommonPath.WebMapPath("path");
+ Assert.AreEqual(Path.Combine("www", "path"), path);
+ }
- [TestMethod()]
- public void WebHostMapPathTest()
- {
- var path = CommonPath.WebHostMapPath("path");
- Assert.AreEqual(Path.Combine("www", "path"), path);
- }
+ [TestMethod]
+ public void WebHostMapPathTest()
+ {
+ var path = CommonPath.WebHostMapPath("path");
+ Assert.AreEqual(Path.Combine("www", "path"), path);
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.SharedKernel.Tests/Extensions/ExtendedLinqTests.cs b/src/Tests/Grand.SharedKernel.Tests/Extensions/ExtendedLinqTests.cs
index b2ce0bedc..f62d9d3f4 100644
--- a/src/Tests/Grand.SharedKernel.Tests/Extensions/ExtendedLinqTests.cs
+++ b/src/Tests/Grand.SharedKernel.Tests/Extensions/ExtendedLinqTests.cs
@@ -1,43 +1,42 @@
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.SharedKernel.Tests.Extensions
+namespace Grand.SharedKernel.Tests.Extensions;
+
+[TestClass]
+public class ExtendedLinqTests
{
- [TestClass()]
- public class ExtendedLinqTests
+ [TestMethod]
+ public void CartesianProductTest()
{
- [TestMethod()]
- public void CartesianProductTest()
- {
- var sampleList = new List<SampleObject> {
- new SampleObject { Id = "1", Name = "name1" },
- new SampleObject { Id = "1", Name = "name2" },
- new SampleObject { Id = "3", Name = "name3" }
- };
+ var sampleList = new List<SampleObject> {
+ new() { Id = "1", Name = "name1" },
+ new() { Id = "1", Name = "name2" },
+ new() { Id = "3", Name = "name3" }
+ };
- var cartesianProduct = sampleList.GroupBy(x => x.Id).CartesianProduct().ToList();
- Assert.AreEqual(2, cartesianProduct.Count);
- }
+ var cartesianProduct = sampleList.GroupBy(x => x.Id).CartesianProduct().ToList();
+ Assert.AreEqual(2, cartesianProduct.Count);
+ }
- [TestMethod()]
- public void ContainsAnyTest_True()
- {
- var sampleList = new List<int> { 1, 2, 3, 4 };
- Assert.IsTrue(sampleList.ContainsAny(new List<int> { 2, 3 }));
- }
+ [TestMethod]
+ public void ContainsAnyTest_True()
+ {
+ var sampleList = new List<int> { 1, 2, 3, 4 };
+ Assert.IsTrue(sampleList.ContainsAny(new List<int> { 2, 3 }));
+ }
- [TestMethod()]
- public void ContainsAnyTest2_True()
- {
- var sampleList = new List<int> { 1, 2, 3, 4 };
- Assert.IsTrue(sampleList.ContainsAny(new List<int> { 2, 5 }));
- }
- [TestMethod()]
- public void ContainsAnyTest_False()
- {
- var sampleList = new List<int> { 1, 2, 3, 4 };
- Assert.IsFalse(sampleList.ContainsAny(new List<int> { 5, 6 }));
- }
+ [TestMethod]
+ public void ContainsAnyTest2_True()
+ {
+ var sampleList = new List<int> { 1, 2, 3, 4 };
+ Assert.IsTrue(sampleList.ContainsAny(new List<int> { 2, 5 }));
+ }
+ [TestMethod]
+ public void ContainsAnyTest_False()
+ {
+ var sampleList = new List<int> { 1, 2, 3, 4 };
+ Assert.IsFalse(sampleList.ContainsAny(new List<int> { 5, 6 }));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.SharedKernel.Tests/Extensions/FormatTextTests.cs b/src/Tests/Grand.SharedKernel.Tests/Extensions/FormatTextTests.cs
index 5ad51776b..2884348ec 100644
--- a/src/Tests/Grand.SharedKernel.Tests/Extensions/FormatTextTests.cs
+++ b/src/Tests/Grand.SharedKernel.Tests/Extensions/FormatTextTests.cs
@@ -1,20 +1,17 @@
using Grand.SharedKernel.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
-namespace Grand.SharedKernel.Tests.Extensions
+namespace Grand.SharedKernel.Tests.Extensions;
+
+[TestClass]
+public class FormatTextTests
{
- [TestClass()]
- public class FormatTextTests
+ [TestMethod]
+ [DataRow("sample <br /> sample ")]
+ [DataRow("&nbsp;&nbsp; sample <br /> sample &nbsp;&nbsp;")]
+ public void ConvertTextTest(string text)
{
-
- [TestMethod()]
- [DataRow("sample <br /> sample ")]
- [DataRow("&nbsp;&nbsp; sample <br /> sample &nbsp;&nbsp;")]
- public void ConvertTextTest(string text)
- {
- Assert.IsFalse(FormatText.ConvertText(text).Contains("<br"));
- Assert.IsFalse(FormatText.ConvertText(text).Contains("&nbsp;&nbsp;"));
- }
-
+ Assert.IsFalse(FormatText.ConvertText(text).Contains("<br"));
+ Assert.IsFalse(FormatText.ConvertText(text).Contains("&nbsp;&nbsp;"));
}
}
\ No newline at end of file
diff --git a/src/Tests/Grand.SharedKernel.Tests/SampleEnum.cs b/src/Tests/Grand.SharedKernel.Tests/SampleEnum.cs
index 1d1afac7b..71a193c76 100644
--- a/src/Tests/Grand.SharedKernel.Tests/SampleEnum.cs
+++ b/src/Tests/Grand.SharedKernel.Tests/SampleEnum.cs
@@ -1,7 +1,8 @@
namespace Grand.SharedKernel.Tests;
+
public enum SampleEnum
{
Test0 = 0,
Test1 = 1,
Test2 = 2
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.SharedKernel.Tests/SampleObject.cs b/src/Tests/Grand.SharedKernel.Tests/SampleObject.cs
index a323abe3e..0daf83680 100644
--- a/src/Tests/Grand.SharedKernel.Tests/SampleObject.cs
+++ b/src/Tests/Grand.SharedKernel.Tests/SampleObject.cs
@@ -4,5 +4,4 @@ public class SampleObject
{
public string Id { get; set; }
public string Name { get; set; }
-
-}
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Web.Admin.Tests/MenuViewModelServiceTests.cs b/src/Tests/Grand.Web.Admin.Tests/MenuViewModelServiceTests.cs
index b492bb3bd..c2aeeaa66 100644
--- a/src/Tests/Grand.Web.Admin.Tests/MenuViewModelServiceTests.cs
+++ b/src/Tests/Grand.Web.Admin.Tests/MenuViewModelServiceTests.cs
@@ -11,169 +11,172 @@ using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace Grand.Web.Admin.Tests;
- [TestClass]
- public class MenuViewModelServiceTests
+[TestClass]
+public class MenuViewModelServiceTests
+{
+ private Mock<IAdminSiteMapService> _adminSiteMapServiceMock;
+ private IMapper _mapper;
+ private MenuViewModelService _menuViewModelService;
+
+ [TestInitialize]
+ public void SetUp()
{
- private MenuViewModelService _menuViewModelService;
- private Mock<IAdminSiteMapService> _adminSiteMapServiceMock;
- private IMapper _mapper;
-
- [TestInitialize]
- public void SetUp()
+ _adminSiteMapServiceMock = new Mock<IAdminSiteMapService>();
+ _menuViewModelService = new MenuViewModelService(_adminSiteMapServiceMock.Object);
+ var mapperConfig = new MapperConfiguration(cfg =>
{
- _adminSiteMapServiceMock = new Mock<IAdminSiteMapService>();
- _menuViewModelService = new MenuViewModelService(_adminSiteMapServiceMock.Object);
- var mapperConfig = new MapperConfiguration(cfg =>
- {
- cfg.AddProfile(new MenuProfile());
- });
- _mapper = mapperConfig.CreateMapper();
- AutoMapperConfig.Init(mapperConfig);
- }
-
- [TestMethod]
- public async Task MenuItems_ReturnsMenuItems()
- {
- // Arrange
- var siteMap = new List<AdminSiteMap>
- {
- new AdminSiteMap { Id = "1", SystemName = "Item 1", DisplayOrder = 1 },
- new AdminSiteMap { Id = "2", SystemName = "Item 2", DisplayOrder = 2 }
- };
-
- _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
-
- // Act
- var result = await _menuViewModelService.MenuItems();
-
- // Assert
- Assert.AreEqual(2, result.Count);
- Assert.AreEqual("1", result[0].Id);
- Assert.AreEqual("Item 1", result[0].SystemName);
- Assert.AreEqual(1, result[0].DisplayOrder);
- Assert.AreEqual("2", result[1].Id);
- Assert.AreEqual("Item 2", result[1].SystemName);
- Assert.AreEqual(2, result[1].DisplayOrder);
- }
-
- [TestMethod]
- public async Task GetMenuById_ReturnsMenuById()
- {
- // Arrange
- var siteMap = new List<AdminSiteMap>
- {
- new AdminSiteMap { Id = "1", SystemName = "Item 1" },
- new AdminSiteMap { Id = "2", SystemName = "Item 2" }
- };
-
- _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
-
- // Act
- var result = await _menuViewModelService.GetMenuById("2");
-
- // Assert
- Assert.AreEqual("2", result.Id);
- Assert.AreEqual("Item 2", result.SystemName);
- }
- [TestMethod]
- public async Task InsertMenuModel_AddsNewMenuModel()
- {
- // Arrange
- var model = new MenuModel { Id = "3", SystemName = "Item 3" };
- var parentEntity = new AdminSiteMap { Id = "1", SystemName = "Item 1", ChildNodes = new List<AdminSiteMap>() };
- var sitemap = new List<AdminSiteMap> { parentEntity };
-
- _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(sitemap);
- _adminSiteMapServiceMock.Setup(x => x.InsertSiteMap(It.IsAny<AdminSiteMap>())).Callback<AdminSiteMap>(node => parentEntity.ChildNodes.Add(node));
-
- // Act
- var result = await _menuViewModelService.InsertMenuModel(model, "1");
-
- // Assert
- Assert.AreEqual("3", result.Id);
- Assert.AreEqual("Item 3", result.SystemName);
- Assert.AreEqual(1, parentEntity.ChildNodes.Count);
- }
-
- [TestMethod]
- public async Task UpdateMenuModel_UpdatesMenuModel()
- {
- // Arrange
- var model = new MenuModel { Id = "2", SystemName = "Updated Item 2" };
- var siteMap = new List<AdminSiteMap>
- {
- new AdminSiteMap { Id = "1", SystemName = "Item 1" },
- new AdminSiteMap { Id = "2", SystemName = "Item 2" }
- };
-
- _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
- _adminSiteMapServiceMock.Setup(x => x.UpdateSiteMap(It.IsAny<AdminSiteMap>()));
-
- // Act
- var result = await _menuViewModelService.UpdateMenuModel(model);
-
- // Assert
- Assert.AreEqual("2", result.Id);
- Assert.AreEqual("Updated Item 2", result.SystemName);
- }
- [TestMethod]
- public async Task UpdateMenuModel_UpdatesSubMenuModel()
- {
- // Arrange
- var model = new MenuModel { Id = "3", SystemName = "Updated Item 3" };
- var siteMap = new List<AdminSiteMap>
- {
- new AdminSiteMap { Id = "1", SystemName = "Item 1" },
- new AdminSiteMap { Id = "2", SystemName = "Item 2",
- ChildNodes = new List<AdminSiteMap> {new (){Id = "3", SystemName = "Item 3"} }}
- };
-
- _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
- _adminSiteMapServiceMock.Setup(x => x.UpdateSiteMap(It.IsAny<AdminSiteMap>()));
-
- // Act
- var result = await _menuViewModelService.UpdateMenuModel(model);
-
- // Assert
- Assert.AreEqual("3", result.Id);
- Assert.AreEqual("Updated Item 3", result.SystemName);
- }
- [TestMethod]
- public async Task DeleteMenu_CallsDeleteSiteMap()
- {
- // Arrange
- var idToDelete = "2";
- var siteMap = new List<AdminSiteMap>
- {
- new AdminSiteMap { Id = "1", SystemName = "Item 1", ChildNodes = new List<AdminSiteMap>() },
- new AdminSiteMap { Id = "2", SystemName = "Item 2" }
- };
-
- _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
-
- // Act
- await _menuViewModelService.DeleteMenu(idToDelete);
-
- // Assert
- _adminSiteMapServiceMock.Verify(x => x.DeleteSiteMap(It.IsAny<AdminSiteMap>()), Times.Once);
- }
- [TestMethod]
- public async Task DeleteMenu_CallsUpdate()
- {
- // Arrange
- var idToDelete = "3";
- var siteMap = new List<AdminSiteMap>
- {
- new AdminSiteMap { Id = "1", SystemName = "Item 1", ChildNodes = new List<AdminSiteMap> { new AdminSiteMap { Id = idToDelete } } },
- new AdminSiteMap { Id = "2", SystemName = "Item 2" }
- };
-
- _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
-
- // Act
- await _menuViewModelService.DeleteMenu(idToDelete);
-
- // Assert
- _adminSiteMapServiceMock.Verify(x => x.UpdateSiteMap(It.IsAny<AdminSiteMap>()), Times.Once);
- }
- }
\ No newline at end of file
+ cfg.AddProfile(new MenuProfile());
+ });
+ _mapper = mapperConfig.CreateMapper();
+ AutoMapperConfig.Init(mapperConfig);
+ }
+
+ [TestMethod]
+ public async Task MenuItems_ReturnsMenuItems()
+ {
+ // Arrange
+ var siteMap = new List<AdminSiteMap> {
+ new() { Id = "1", SystemName = "Item 1", DisplayOrder = 1 },
+ new() { Id = "2", SystemName = "Item 2", DisplayOrder = 2 }
+ };
+
+ _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
+
+ // Act
+ var result = await _menuViewModelService.MenuItems();
+
+ // Assert
+ Assert.AreEqual(2, result.Count);
+ Assert.AreEqual("1", result[0].Id);
+ Assert.AreEqual("Item 1", result[0].SystemName);
+ Assert.AreEqual(1, result[0].DisplayOrder);
+ Assert.AreEqual("2", result[1].Id);
+ Assert.AreEqual("Item 2", result[1].SystemName);
+ Assert.AreEqual(2, result[1].DisplayOrder);
+ }
+
+ [TestMethod]
+ public async Task GetMenuById_ReturnsMenuById()
+ {
+ // Arrange
+ var siteMap = new List<AdminSiteMap> {
+ new() { Id = "1", SystemName = "Item 1" },
+ new() { Id = "2", SystemName = "Item 2" }
+ };
+
+ _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
+
+ // Act
+ var result = await _menuViewModelService.GetMenuById("2");
+
+ // Assert
+ Assert.AreEqual("2", result.Id);
+ Assert.AreEqual("Item 2", result.SystemName);
+ }
+
+ [TestMethod]
+ public async Task InsertMenuModel_AddsNewMenuModel()
+ {
+ // Arrange
+ var model = new MenuModel { Id = "3", SystemName = "Item 3" };
+ var parentEntity = new AdminSiteMap { Id = "1", SystemName = "Item 1", ChildNodes = new List<AdminSiteMap>() };
+ var sitemap = new List<AdminSiteMap> { parentEntity };
+
+ _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(sitemap);
+ _adminSiteMapServiceMock.Setup(x => x.InsertSiteMap(It.IsAny<AdminSiteMap>()))
+ .Callback<AdminSiteMap>(node => parentEntity.ChildNodes.Add(node));
+
+ // Act
+ var result = await _menuViewModelService.InsertMenuModel(model, "1");
+
+ // Assert
+ Assert.AreEqual("3", result.Id);
+ Assert.AreEqual("Item 3", result.SystemName);
+ Assert.AreEqual(1, parentEntity.ChildNodes.Count);
+ }
+
+ [TestMethod]
+ public async Task UpdateMenuModel_UpdatesMenuModel()
+ {
+ // Arrange
+ var model = new MenuModel { Id = "2", SystemName = "Updated Item 2" };
+ var siteMap = new List<AdminSiteMap> {
+ new() { Id = "1", SystemName = "Item 1" },
+ new() { Id = "2", SystemName = "Item 2" }
+ };
+
+ _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
+ _adminSiteMapServiceMock.Setup(x => x.UpdateSiteMap(It.IsAny<AdminSiteMap>()));
+
+ // Act
+ var result = await _menuViewModelService.UpdateMenuModel(model);
+
+ // Assert
+ Assert.AreEqual("2", result.Id);
+ Assert.AreEqual("Updated Item 2", result.SystemName);
+ }
+
+ [TestMethod]
+ public async Task UpdateMenuModel_UpdatesSubMenuModel()
+ {
+ // Arrange
+ var model = new MenuModel { Id = "3", SystemName = "Updated Item 3" };
+ var siteMap = new List<AdminSiteMap> {
+ new() { Id = "1", SystemName = "Item 1" },
+ new() {
+ Id = "2", SystemName = "Item 2",
+ ChildNodes = new List<AdminSiteMap> { new() { Id = "3", SystemName = "Item 3" } }
+ }
+ };
+
+ _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
+ _adminSiteMapServiceMock.Setup(x => x.UpdateSiteMap(It.IsAny<AdminSiteMap>()));
+
+ // Act
+ var result = await _menuViewModelService.UpdateMenuModel(model);
+
+ // Assert
+ Assert.AreEqual("3", result.Id);
+ Assert.AreEqual("Updated Item 3", result.SystemName);
+ }
+
+ [TestMethod]
+ public async Task DeleteMenu_CallsDeleteSiteMap()
+ {
+ // Arrange
+ var idToDelete = "2";
+ var siteMap = new List<AdminSiteMap> {
+ new() { Id = "1", SystemName = "Item 1", ChildNodes = new List<AdminSiteMap>() },
+ new() { Id = "2", SystemName = "Item 2" }
+ };
+
+ _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
+
+ // Act
+ await _menuViewModelService.DeleteMenu(idToDelete);
+
+ // Assert
+ _adminSiteMapServiceMock.Verify(x => x.DeleteSiteMap(It.IsAny<AdminSiteMap>()), Times.Once);
+ }
+
+ [TestMethod]
+ public async Task DeleteMenu_CallsUpdate()
+ {
+ // Arrange
+ var idToDelete = "3";
+ var siteMap = new List<AdminSiteMap> {
+ new() {
+ Id = "1", SystemName = "Item 1", ChildNodes = new List<AdminSiteMap> { new() { Id = idToDelete } }
+ },
+ new() { Id = "2", SystemName = "Item 2" }
+ };
+
+ _adminSiteMapServiceMock.Setup(x => x.GetSiteMap()).ReturnsAsync(siteMap);
+
+ // Act
+ await _menuViewModelService.DeleteMenu(idToDelete);
+
+ // Assert
+ _adminSiteMapServiceMock.Verify(x => x.UpdateSiteMap(It.IsAny<AdminSiteMap>()), Times.Once);
+ }
+}
\ No newline at end of file
diff --git a/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs b/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs
index e8440d299..df1af2ee0 100644
--- a/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs
+++ b/src/Tests/Grand.Web.Common.Tests/AuthorizeMenuAttributeTests.cs
@@ -1,8 +1,8 @@
using Grand.Business.Core.Interfaces.Common.Security;
using Grand.Business.Core.Interfaces.System.Admin;
+using Grand.Data;
using Grand.Domain.Admin;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure;
using Grand.Infrastructure.Configuration;
using Grand.SharedKernel.Extensions;
@@ -12,20 +12,20 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
-using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Grand.Web.Common.Tests;
[TestClass]
public class AuthorizeMenuAttributeTests
{
- private Mock<IPermissionService> _mockPermissionService;
private Mock<IAdminSiteMapService> _mockAdminSiteMapService;
+ private AuthorizationFilterContext _mockFilterContext;
+ private Mock<IPermissionService> _mockPermissionService;
private Mock<IWorkContext> _mockWorkContext;
private SecurityConfig _securityConfig;
- private AuthorizationFilterContext _mockFilterContext;
[TestInitialize]
public void Setup()
@@ -36,15 +36,14 @@ public class AuthorizeMenuAttributeTests
_mockAdminSiteMapService = new Mock<IAdminSiteMapService>();
_mockWorkContext = new Mock<IWorkContext>();
_securityConfig = new SecurityConfig();
- var filters = new List<IFilterMetadata>
- {
- new AuthorizeMenuAttribute(false)
+ var filters = new List<IFilterMetadata> {
+ new AuthorizeMenuAttribute()
};
_mockFilterContext = new AuthorizationFilterContext(GetMockedAuthorizationFilterContext(), filters);
}
+
private AuthorizationFilterContext GetMockedAuthorizationFilterContext()
{
-
// Mocking HttpContext
var httpContextMock = new Mock<HttpContext>();
@@ -59,26 +58,26 @@ public class AuthorizeMenuAttributeTests
var actionContext = new ActionContext(
- httpContextMock.Object,
- routeData,
+ httpContextMock.Object,
+ routeData,
actionDescriptorMock.Object
);
// Mocking filters for the context (can be empty if not needed for testing)
- var filters = new List<IFilterMetadata>
- {
- new AuthorizeMenuAttribute(false)
+ var filters = new List<IFilterMetadata> {
+ new AuthorizeMenuAttribute()
};
-
+
var authorizationFilterContext = new AuthorizationFilterContext(actionContext, filters);
return authorizationFilterContext;
}
+
[TestMethod]
public async Task TestAuthorizeMenuAttribute_WithoutIgnoreFilter_DatabaseNotInstalled()
{
// Arrange
- var attribute = new AuthorizeMenuAttribute(false);
+ var attribute = new AuthorizeMenuAttribute();
var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(
false,
_mockPermissionService.Object,
@@ -100,7 +99,7 @@ public class AuthorizeMenuAttributeTests
{
// Arrange
_securityConfig.AuthorizeAdminMenu = false;
- var attribute = new AuthorizeMenuAttribute(false);
+ var attribute = new AuthorizeMenuAttribute();
var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(
false,
_mockPermissionService.Object,
@@ -121,11 +120,14 @@ public class AuthorizeMenuAttributeTests
public async Task TestAuthorizeMenuAttribute_WithValidSiteMap_AllPermissions()
{
// Arrange
- var menuSiteMap = new AdminSiteMap { AllPermissions = true, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction", ControllerName = "SampleController" };
+ var menuSiteMap = new AdminSiteMap {
+ AllPermissions = true, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction",
+ ControllerName = "SampleController"
+ };
_mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });
_mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(false);
_securityConfig.AuthorizeAdminMenu = true;
- var attribute = new AuthorizeMenuAttribute(false);
+ var attribute = new AuthorizeMenuAttribute();
var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(
false,
_mockPermissionService.Object,
@@ -140,17 +142,20 @@ public class AuthorizeMenuAttributeTests
// Assert
Assert.IsInstanceOfType(_mockFilterContext.Result, typeof(ForbidResult));
}
-
+
[TestMethod]
public async Task TestAuthorizeMenuAttribute_NoPermissionsInSiteMap()
{
// Arrange
- var menuSiteMap = new AdminSiteMap { AllPermissions = true, PermissionNames = new List<string> { }, ActionName = "SampleAction", ControllerName = "SampleController" };
+ var menuSiteMap = new AdminSiteMap {
+ AllPermissions = true, PermissionNames = new List<string>(), ActionName = "SampleAction",
+ ControllerName = "SampleController"
+ };
_mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });
_mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(false);
_securityConfig.AuthorizeAdminMenu = true;
- var attribute = new AuthorizeMenuAttribute(false);
+ var attribute = new AuthorizeMenuAttribute();
var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(
false,
_mockPermissionService.Object,
@@ -166,17 +171,20 @@ public class AuthorizeMenuAttributeTests
// No permissions in the sitemap, so no redirect should occur
Assert.IsNull(_mockFilterContext.Result);
}
-
+
[TestMethod]
public async Task TestAuthorizeMenuAttribute_WithoutAllPermissions_Authorized()
{
// Arrange
- var menuSiteMap = new AdminSiteMap { AllPermissions = false, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction", ControllerName = "SampleController" };
+ var menuSiteMap = new AdminSiteMap {
+ AllPermissions = false, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction",
+ ControllerName = "SampleController"
+ };
_mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });
_mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(true);
_securityConfig.AuthorizeAdminMenu = true;
- var attribute = new AuthorizeMenuAttribute(false);
+ var attribute = new AuthorizeMenuAttribute();
var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(
false,
_mockPermissionService.Object,
@@ -197,12 +205,15 @@ public class AuthorizeMenuAttributeTests
public async Task TestAuthorizeMenuAttribute_WithoutAllPermissions_NotAuthorized()
{
// Arrange
- var menuSiteMap = new AdminSiteMap { AllPermissions = false, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction", ControllerName = "SampleController" };
+ var menuSiteMap = new AdminSiteMap {
+ AllPermissions = false, PermissionNames = new List<string> { "Permission1" }, ActionName = "SampleAction",
+ ControllerName = "SampleController"
+ };
_mockAdminSiteMapService.Setup(s => s.GetSiteMap()).ReturnsAsync(new List<AdminSiteMap> { menuSiteMap });
_mockPermissionService.Setup(s => s.Authorize(It.IsAny<string>(), It.IsAny<Customer>())).ReturnsAsync(false);
_securityConfig.AuthorizeAdminMenu = true;
- var attribute = new AuthorizeMenuAttribute(false);
+ var attribute = new AuthorizeMenuAttribute();
var filter = new AuthorizeMenuAttribute.AuthorizeMenuFilter(
false,
_mockPermissionService.Object,