Check out this code:
internal static readonly Dictionary<Type, Func<IModel>> typeToCreator = new Dictionary<Type, Func<IModel>>();
protected static object _lock;
public virtual void Register<T>(Func<IModel> creator)
{
lock (_lock)
{
if (typeToCreator.ContainsKey(typeof(T)))
typeToCreator[typeof(T)] = creator;
else
typeToCreator.Add(typeof(T), creator);
}
}
When I use run the code in this test (testframework is MSTest):
[TestMethod]
public void Must_Be_BasePresenterType()
{
var sut = new ListTilbudPresenter(_tilbudView);
Assert.IsInstanceOfType(sut, typeof(BasePresenter));
}
...MSTest passes it and TestDriven.NET fails it because _lock is null.
Why does MSTest NOT fail the test???
Related
I am new vertx wanted to know which is the best junit framework and references that we should went through.
I tried using couple of things with mockito but services are not getting injected.
Please help in this.
UPDATE:
My TestClass looks something like this
public class GroupModeTest {
private static final Logger logger = LoggerFactory.getLogger(GroupMode.class);
public static GroupModeService service;
public static GroupModeDao dao;
private GroupMode groupMode;
private static GroupModeDao daoMock;
#BeforeAll
static void setup() {
logger.info("Starting Unit Tests for GroupMode");
daoMock = mock(GroupModeDao.class);
dao = new GroupModeDao();
service = new GroupModeService(daoMock);
}
#BeforeEach
void init() {
logger.info("Mocking new GroupMode Entity");
this.groupMode = new GroupMode();
}
#Test
public void testFakeWithMockito() throws IOException {
IGroupModeDao iGroupModeDao = mock(IGroupModeDao.class);
GroupMode groupMode = new GroupMode();
groupMode.setId(1L);
groupMode.setModeType("unique");
groupMode.setCreatedBy(1);
groupMode.setCreatedOn(LocalDateTime.now());
groupMode.setUpdatedBy(1);
groupMode.setUpdatedOn(LocalDateTime.now());
Single<Long> expected=Single.just(1L);
when(iGroupModeDao.create(groupMode)).thenReturn(expected);
GroupModeService groupModeService = new GroupModeService(iGroupModeDao);
Single<Long> actual= groupModeService.rxCreate("unique",1);
assertEquals(expected, actual);
}
}
I have a service class with some injected services. It's dealing with my Azure storage requests. I need to write NUnit tests for that class.
I'm new to NUnit and I'm struggling with making the object of that my AzureService.cs
Below AzureService.cs. I have used some injected services
using System;
using System.Linq;
using System.Threading.Tasks;
using JohnMorris.Plugin.Image.Upload.Azure.Interfaces;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Domain.Media;
using Nop.Services.Logging;
namespace JohnMorris.Plugin.Image.Upload.Azure.Services
{
public class AzureService : IAzureService
{
#region Constants
private const string THUMB_EXISTS_KEY = "Nop.azure.thumb.exists-{0}";
private const string THUMBS_PATTERN_KEY = "Nop.azure.thumb";
#endregion
#region Fields
private readonly ILogger _logger;
private static CloudBlobContainer _container;
private readonly IStaticCacheManager _cacheManager;
private readonly MediaSettings _mediaSettings;
private readonly NopConfig _config;
#endregion
#region
public AzureService(IStaticCacheManager cacheManager, MediaSettings mediaSettings, NopConfig config, ILogger logger)
{
this._cacheManager = cacheManager;
this._mediaSettings = mediaSettings;
this._config = config;
this._logger = logger;
}
#endregion
#region Utilities
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
public virtual async Task DeleteFileAsync(string prefix)
{
try
{
BlobContinuationToken continuationToken = null;
do
{
var resultSegment = await _container.ListBlobsSegmentedAsync(prefix, true, BlobListingDetails.All, null, continuationToken, null, null);
await Task.WhenAll(resultSegment.Results.Select(blobItem => ((CloudBlockBlob)blobItem).DeleteAsync()));
//get the continuation token.
continuationToken = resultSegment.ContinuationToken;
}
while (continuationToken != null);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file delete error", e);
}
}
public virtual async Task<bool> CheckFileExistsAsync(string filePath)
{
try
{
var key = string.Format(THUMB_EXISTS_KEY, filePath);
return await _cacheManager.Get(key, async () =>
{
//GetBlockBlobReference doesn't need to be async since it doesn't contact the server yet
var blockBlob = _container.GetBlockBlobReference(filePath);
return await blockBlob.ExistsAsync();
});
}
catch { return false; }
}
public virtual async Task SaveFileAsync(string filePath, string mimeType, byte[] binary)
{
try
{
var blockBlob = _container.GetBlockBlobReference(filePath);
if (!string.IsNullOrEmpty(mimeType))
blockBlob.Properties.ContentType = mimeType;
if (!string.IsNullOrEmpty(_mediaSettings.AzureCacheControlHeader))
blockBlob.Properties.CacheControl = _mediaSettings.AzureCacheControlHeader;
await blockBlob.UploadFromByteArrayAsync(binary, 0, binary.Length);
_cacheManager.RemoveByPrefix(THUMBS_PATTERN_KEY);
}
catch (Exception e)
{
_logger.Error($"Azure file upload error", e);
}
}
public virtual byte[] LoadFileFromAzure(string filePath)
{
try
{
var blob = _container.GetBlockBlobReference(filePath);
if (blob.ExistsAsync().GetAwaiter().GetResult())
{
blob.FetchAttributesAsync().GetAwaiter().GetResult();
var bytes = new byte[blob.Properties.Length];
blob.DownloadToByteArrayAsync(bytes, 0).GetAwaiter().GetResult();
return bytes;
}
}
catch (Exception)
{
}
return new byte[0];
}
#endregion
}
}
This is my test class below, I need to create new AzureService(); from my service class. But in my AzureService constructor, I'm injecting some service
using JohnMorris.Plugin.Image.Upload.Azure.Services;
using Nop.Core.Caching;
using Nop.Core.Domain.Media;
using Nop.Services.Tests;
using NUnit.Framework;
namespace JohnMorris.Plugin.Image.Upload.Azure.Test
{
public class AzureServiceTest
{
private AzureService _azureService;
[SetUp]
public void Setup()
{
_azureService = new AzureService( cacheManager, mediaSettings, config, logger);
}
[Test]
public void App_settings_has_azure_connection_details()
{
var url= _azureService.GetAzureStorageUrl();
Assert.IsNotNull(url);
Assert.IsNotEmpty(url);
}
[Test]
public void Check_File_Exists_Async_test(){
//To Do
}
[Test]
public void Save_File_Async_Test()(){
//To Do
}
[Test]
public void Load_File_From_Azure_Test(){
//To Do
}
}
}
Question is, what exactly do you want to test? If you want to test if NopConfig is properly reading values from AppSettings, then you do not have to test AzureService at all.
If you want to test that GetAzureStorageUrl method is working correctly, then you should mock your NopConfig dependency and focus on testing only AzureService methods like this:
using Moq;
using Nop.Core.Configuration;
using NUnit.Framework;
namespace NopTest
{
public class AzureService
{
private readonly NopConfig _config;
public AzureService(NopConfig config)
{
_config = config;
}
public string GetAzureStorageUrl()
{
return $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}";
}
}
[TestFixture]
public class NopTest
{
[Test]
public void GetStorageUrlTest()
{
Mock<NopConfig> nopConfigMock = new Mock<NopConfig>();
nopConfigMock.Setup(x => x.AzureBlobStorageEndPoint).Returns("https://www.example.com/");
nopConfigMock.Setup(x => x.AzureBlobStorageContainerName).Returns("containername");
AzureService azureService = new AzureService(nopConfigMock.Object);
string azureStorageUrl = azureService.GetAzureStorageUrl();
Assert.AreEqual("https://www.example.com/containername", azureStorageUrl);
}
}
}
I have added an application in scriptcs and added some references to assemblies which have the version v2.0.50727. So while running the scriptcs file it returns as Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime.Setting attribute useLegacyV2RuntimeActivationPolicy="true" in app.config may resolve the issue in asp.net web application. but in scriptcs its not working. further searching reveals that above attribbute useLegacyV2RuntimeActivationPolicy="true" should be added as scriptcs.exe.config. I have an application file named FMUpgrade.csx and how can we reference this scriptcs.exe.config in the FMUpgrade.csx file.scriptcs docs doesn't say much about scriptcs.exe.config.Also added program.exe.config with app.config but still not success.
After much research I got a workaround solution to the above problem.
By make use of class ExeConfigurationFileMap we could able to get the key values from app.config, its not able to bypass the supported runtime error caused by mixed mode assembly error.
Server server = new Server(new ServerConnection(con)); server.ConnectionContext.ExecuteNonQuery(script);
The error is caused while executing the statement ExecuteNonQuery.
So before executing the statement
if( RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully )
server.ConnectionContext.ExecuteNonQuery(script);
Solution is below
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully
{ get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
} using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }
static RuntimePolicyHelper()
{
ICLRRuntimeInfo clrRuntimeInfo =
(ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
Guid.Empty,
typeof(ICLRRuntimeInfo).GUID);
try
{
clrRuntimeInfo.BindAsLegacyV2Runtime();
LegacyV2RuntimeEnabledSuccessfully = true;
}
catch (COMException)
{
// This occurs with an HRESULT meaning
// "A different runtime was already bound to the legacy CLR version 2 activation policy."
LegacyV2RuntimeEnabledSuccessfully = false;
}
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
void xGetVersionString();
void xGetRuntimeDirectory();
void xIsLoaded();
void xIsLoadable();
void xLoadErrorString();
void xLoadLibrary();
void xGetProcAddress();
void xGetInterface();
void xSetDefaultStartupFlags();
void xGetDefaultStartupFlags();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void BindAsLegacyV2Runtime();
}
}
I am converting ado.net code to use EF. In my ado.net code i set dataReader.FetchSize = command.RowSize * 1000 and that dramatically improves performance over the default fetch size .
When I convert my code to EF, the performance is on par to ado.net code where I didn't specify fetch size, i.e. it's very slow over large records.
Any way I could specify fetch size for retrieving records in EF?
You can set ODP.NET FetchSize in the Registry or the .NET config files when using Entity Framework. That will standardize the FetchSize across all your ODP.NET instances (in the case of the Registry) or across your application (in the case of app/web.config).
http://docs.oracle.com/cd/E48297_01/doc/win.121/e41125/featConfig.htm
Christian Shay
Oracle
I was running into a similar problem, but don't want to change the overall FetchSize, instead I want to change the FetchSize per query.
Here is the solution I came up with, maybe this helps someone.
It basically uses the CallContext to pass arguments to a DbInterceptor. The interceptor will override the needed properties on the query commands.
Thread safe with support for nesting scopes.
This can be as well used to modify other properties of commands executed through Entity Framework queries for a defined scope.
Usage:
using (var context = new MyDbContext())
{
using (new OracleCommandContext(fetchSize: 1024 * 128))
{
// your query here
}
}
Properties to override:
public class OracleCommandProperties
{
public long FetchSize { get; set; } = 524288; // oracle default value
}
The call context:
public class OracleCommandContext : IDisposable
{
private static readonly object sync = new object();
private readonly OracleCommandProperties previousCommandProperties;
private bool isDisposed;
static OracleCommandContext()
{
DbInterception.Add(new OracleCommandInterceptor());
}
public OracleCommandContext(long fetchSize)
{
lock (sync)
{
var commandProperties = new OracleCommandProperties();
if (TryGetProperties(out var previousProperties))
{
// when using nested OracleCommandContext, escalate the properties
previousCommandProperties = previousProperties;
commandProperties.FetchSize = Math.Max(previousProperties.FetchSize, fetchSize);
}
else
{
commandProperties.FetchSize = fetchSize;
}
CallContext.LogicalSetData(nameof(OracleCommandProperties), commandProperties);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~OracleCommandContext()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (!isDisposed)
{
lock (sync)
{
CallContext.LogicalSetData(nameof(OracleCommandProperties), previousCommandProperties);
}
isDisposed = true;
}
}
}
public static bool TryGetProperties(out OracleCommandProperties properties)
{
lock(sync)
{
if (CallContext.LogicalGetData(nameof(OracleCommandProperties)) is OracleCommandProperties oracleReaderProperties)
{
properties = oracleReaderProperties;
return true;
}
properties = null;
return false;
}
}
}
The interceptor doing the actual work:
public class OracleCommandInterceptor : IDbCommandInterceptor
{
public void NonQueryExecuted(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
}
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
AdjustCommand(command);
}
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
}
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
AdjustCommand(command);
}
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
}
public void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
AdjustCommand(command);
}
private static void AdjustCommand(DbCommand command)
{
if (command is OracleCommand oracleCommand)
{
if (OracleCommandContext.TryGetProperties(out var properties))
{
oracleCommand.FetchSize = properties.FetchSize;
}
}
}
}
namespace MoqSample.Test
{
[TestFixture]
public class GivenCustomerServiceTest
{
private ICustomerService customerService;
private CustomerModel customer;
// Defining the mock object.
private Mock<ICustomerRepository> mockCustomerRepository;
[SetUp]
public void SetUp()
{
//Creating the mock object.
mockCustomerRepository = new Mock<ICustomerRepository>();
customerService = new CustomerService(mockCustomerRepository.Object);
}
[Test]
public void GetCustomerByIdTest()
{
customer = new CustomerModel { Id = 1, Name = "TEST-CUSTOMER", Address = "abc" };
mockCustomerRepository.Setup(customerRepository => customerRepository.GetCustomerById(1)).Returns(customer);
var customerReturned = customerService.GetCustomerById(1);
//Verifying values.
Assert.AreEqual(customer.Id, customerReturned.Id);
Assert.AreEqual(customer.Name, customerReturned.Name);
Assert.AreEqual(customer.Address, customerReturned.Address);
}
}
}
When I am trying to debug the code in aforementioned class , it's not hitting the break point.
I.e I am unable to debug the code.
Any suggestions are welcome.
Using the Resharper or TestDriven test runners should allow you to debug through your unit tests.