Moq无法在单元测试中引发特定异常

时间:2019-09-11 12:32:57

标签: c# .net unit-testing moq

我有一个Azure功能,可将应用程序设置存储在Azure Blob存储中。为了对获取和添加设置的类进行单元测试,我使用moq使blob存储抽象类(blobStorageRepository)抛出异常。它主要工作。但是,我有两个测试失败。

我还有其他模拟_blobStorageRepository的单元测试。我有两个不同的单元测试,它们使用moc引发特定的异常(StorageException),并且已将moq设置为引发该异常,但是moq始终会引发正常的“异常”。

我正在测试的方法在基类中,测试正在调用使用基类的类。

这里是测试:

        [Fact(DisplayName = "SystemSettingsRepository - Add StorageException")]
        [Trait("Category", "Unit Test")]
        public async Task AddSettingsAsyncTestBaseClassWithStorageException()
        {
            string id = Guid.NewGuid().ToString();
            string correlationId = Guid.NewGuid().ToString();

            string body = File.ReadAllText("TestData/systemSettings.json");
            SystemSettingsObject systemSettingsObject = JsonConvert.DeserializeObject<SystemSettingsObject>(body);

            var iFunctionEnvironment = TestHelpers.GetEnvironmentVariable("Test");

            var iblobStorageRepositoryMoq = new Mock<IBlobStorageRepository>();
            iblobStorageRepositoryMoq
                .Setup(mock => mock.Add(It.IsAny<ILogger>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
                .ThrowsAsync(new StorageException("Function Add threw an exception"));
            var iblobStorageRepository = iblobStorageRepositoryMoq.Object;

            SystemSettingsRepository systemSettingsRepository = new SystemSettingsRepository(iFunctionEnvironment, iblobStorageRepository);

            Exception exception = await Assert.ThrowsAsync<StorageException>(async () => await systemSettingsRepository.Add(logger, correlationId, id, systemSettingsObject));
            Assert.Equal($"Function Add threw an exception", exception.Message);
            Assert.Null(exception.InnerException);

这是基类的接口:

    {
        Task<bool> Add(ILogger logger, string correlationId, string id, TEntity entity);
    } 

这是该类的实现:

    {        
        private readonly BlobStorageConfiguration _blobStorageConfiguration;

        private readonly IFunctionEnvironment _functionEnvironment;
        private readonly IBlobStorageRepository _blobStorageRepository;

        public Repository(IFunctionEnvironment functionEnvironment,
                          IBlobStorageRepository blobStorageRepository)
        {
            _functionEnvironment = functionEnvironment;
            _blobStorageRepository = blobStorageRepository;

            ConfigReader configurationReader = new ConfigReader(_functionEnvironment);

            // blobStorageConfiguration = configurationReader.BlobStorageConfiguration;
        }

        public async Task<bool> Add(ILogger logger, string correlationId, string id, TEntity entity)
        {
            if (String.IsNullOrEmpty(correlationId))
            {
                correlationId = Guid.NewGuid().ToString();
            }
            if (string.IsNullOrEmpty(id))
            {

                throw new ArgumentException("Argument id is missing or empty");
            }

            if (entity == null)
            {

                throw new ArgumentNullException(nameof(entity));
            }

            try
            {
                string settingsObjectString = JsonConvert.SerializeObject(entity);

                bool response = await _blobStorageRepository.Add(logger, correlationId, settingsObjectString, id);
                return response;
            }
            catch (StorageException storageException)
            {

                throw new StorageException(storageException.Message, storageException.InnerException);
            }
            catch (Exception exception)
            {

                throw new InvalidOperationException($"settingsObject upload {id} failed", exception.InnerException);
            }
        }
    }

以下是使用上述基类的类的接口:

public interface ISystemSettingsRepository : IRepository<SystemSettingsObject>
    {
    }

这是该类的实现:

public class SystemSettingsRepository : Repository<SystemSettingsObject>, ISystemSettingsRepository
    {        
        private readonly BlobStorageConfiguration _blobStorageConfiguration;

        private readonly IFunctionEnvironment _functionEnvironment;
        private readonly IBlobStorageRepository _blobStorageRepository;

        public SystemSettingsRepository(IFunctionEnvironment functionEnvironment,
                                        IBlobStorageRepository blobStorageRepository) : base(functionEnvironment,
                                                                                             blobStorageRepository)
        {            
            _functionEnvironment = functionEnvironment;
            _blobStorageRepository = blobStorageRepository;
        }
    }

我试图获取模拟来抛出其他异常类型,例如InvalidOperationException,但最小起订量仅引发“普通”异常。我确实有其他单元测试,在这里我不使用接口/基类设置,而最低订量引发了异常,这是我已经设置的。

非常欢迎您提出想法和建议!

0 个答案:

没有答案