I use the System.IO.Abstractions.TestingHelpers to mock FileSystem. In my class, I inject IFileSystem and use the instance to call _fileSystem.File.Exists and _fileSystem.File.Delete. In my test class, I would like to verify that the "Delete" method was called. It's easy by mocking only the IFile, but since I already mocked the FileSystem, I don't want to have to mock the Directory, Path and File on top of it. Is it possible to call something like _fileRepository.FileMock.Verify(x => x.Delete(It.IsAny<string>()))...?
public class Downloader : IDownloader
{
public Downloader(HttpClient httpClient, IFileSystem fileSystem)
{
HttpClient = httpClient;
FileSystem = fileSystem;
}
public async Task DownloadConfigFileAsync(string updatedConfigBaseFolderPath, string configurationFileUrl, string personalAccessToken)
{
var newFilePath = FileSystem.Path.Combine(updatedConfigBaseFolderPath, "subfolder1", "myNewFile.txt");
if (FileSystem.File.Exists(newFilePath))
{
FileSystem.File.Delete(newFilePath);
}
// rest of implementation ommited for demo purpose
}
}
And my test is like :
[Fact]
public async void Given_MissingPathParts_ShouldThrow()
{
var handlerMock = GetMessageHandlerMock();
var mockFileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ #"c:\Test\", new MockDirectoryData() },
{ #"c:\Test\subfolder1\myNewFile.txt", new MockFileData(string.Empty) }
});
var httpClient = new HttpClient(handlerMock.Object);
var sut = new Downloader(httpClient, mockFileSystem);
await sut.DownloadConfigFileAsync(BasePath, "http://fakeurl.com?path=%2Fconfiguration%2Flocal%2FTestFile.txt", _fixture.Create<string>());
handlerMock.Protected().Verify(
"SendAsync",
Times.Exactly(1),
ItExpr.Is<HttpRequestMessage>(req => req.Method == HttpMethod.Get),
ItExpr.IsAny<CancellationToken>());
mockFileSystem.File.Exists(FilePath).Should().BeTrue();
// Add assertion that the File.Delete has been called
}
The test freamwork has extensive unit tests itself.
Looking into ...tests\TestableIO.System.IO.Abstractions.TestingHelpers.Tests\MockFileDeleteTests.cs, it just counts the files, which I don't find overly satisying. If there would be a direct way, the creator would have used it.
var fileCount1 = fileSystem.Directory.GetFiles(directory, "*").Length;
fileSystem.File.Delete(path);
var fileCount2 = fileSystem.Directory.GetFiles(directory, "*").Length;
Assert.AreEqual(1, fileCount1, "File should have existed");
Assert.AreEqual(0, fileCount2, "File should have been deleted");
Related
I am new at implementing unit tests and integration tests. I am trying to write some integration tests for my application.
Following are the code snippets from my application to give you all the idea of my code.
It would be great help if you could provide me some guidance for it.
namespace MyApplication.ApiControllers
{
[Authorize]
[RoutePrefix("api/customers")]
[AppExceptionFilter]
public class CustomersController : ApiController
{
private readonly IMediator _mediator;
public CustomersController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
[Route("GetCustomer")]
public async Task<IHttpActionResult> GetCustomer(string customerNumber, string customerType = null)
{
var result = await _mediator.RequestAsync(new GetCustomerRequest(customerNumber, customerType));
return Ok(result);
}
}
}
Following is the implementation for GetCustomerRequest handler
public async Task<List<Customer>> HandleAsync(GetCustomerRequest request)
{
var result = await customerService.GetCustomer(request.CustomerNumber, request.CustomerType);
// some business logic
return result;
}
Following is the implementation for customerService
public async Task<List<Customer>> GetCustomer(string customerNumber, string customerType = null)
{
using (var dataContext = _dataContextFactory.Invoke())
{
result = await dataContext.Customers
.Where(b => b.CustomerNumber == customerNumber)
.Where(b => b.CustomerType == customerType)
.Select(b => new Customer
{
// Properties assignment...
})
.ToListAsync();
}
return result;
}
Below is the integration unit test what I have tried.
namespace MyApplication.Tests.Integrations
{
[TestFixture]
public class CustomersControllerTests
{
private string _baseAddress;
private string _username;
private string _password;
private IApiClient _apiClient;
[SetUp]
public void Setup()
{
_baseAddress = "https://mywebaaplication.com"; // TODO get this from a config
_username = "";
_password = "";
_apiClient = new ApiClient(new ApiClientAuthenticationHandler(), _baseAddress); // REPLACE with AzureADApiClientAuthenticationHandler
}
[Test]
public async Task CustomersController_GetCustomer()
{
var customerNumber = string.Empty;
var customerType = 500;
var result = await _apiClient.GetAsync<Customer[]>($"/api/customers/GetCustomer?customerNumber={customerNumber}&customerType={customerType}");
Assert.IsNotNull(result);
Assert.IsTrue(result?.Length > 0);
}
}
}
You can do a few things:
Create a webhost within your unit test, then do http requests against it
Not test your controller in a unit test, but in a liveness/readiness check (because it's just glue code anyway). Just do integration testing for your service.
Just test against "new CustomersController"
There isn't a right/wrong answer here. You just look at the risks, and test accordingly. Also depends on the type of code-changes you expect. Sometimes its fine to create the test only within the context of a new change, no need to anticipate everything.
I am planning to write an ActionFilter for business validation and in which some services will be resolved via Service Locator(I know this is not good practice and as far as possible i avoid Service Locator pattern, but for this case i want to use it).
OnActionExecuting method of the filter is something like this:
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
// get validator for input;
var validator = actionContext.HttpContext.RequestServices.GetService<IValidator<TypeOfInput>>();// i will ask another question for this line
if(!validator.IsValid(input))
{
//send errors
}
}
Is it possible to write unit test for above ActionFilterand how?
Here is an sample on how to create a mock (using XUnit and Moq framework) to verify that the IsValid method is called and where the mock returns an false.
using Dealz.Common.Web.Tests.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using System;
using Xunit;
namespace Dealz.Common.Web.Tests.ActionFilters
{
public class TestActionFilter
{
[Fact]
public void ActionFilterTest()
{
/****************
* Setup
****************/
// Create the userValidatorMock
var userValidatorMock = new Mock<IValidator<User>>();
userValidatorMock.Setup(validator => validator
// For any parameter passed to IsValid
.IsValid(It.IsAny<User>())
)
// return false when IsValid is called
.Returns(false)
// Make sure that `IsValid` is being called at least once or throw error
.Verifiable();
// If provider.GetService(typeof(IValidator<User>)) gets called,
// IValidator<User> mock will be returned
var serviceProviderMock = new Mock<IServiceProvider>();
serviceProviderMock.Setup(provider => provider.GetService(typeof(IValidator<User>)))
.Returns(userValidatorMock.Object);
// Mock the HttpContext to return a mockable
var httpContextMock = new Mock<HttpContext>();
httpContextMock.SetupGet(context => context.RequestServices)
.Returns(serviceProviderMock.Object);
var actionExecutingContext = HttpContextUtils.MockedActionExecutingContext(httpContextMock.Object, null);
/****************
* Act
****************/
var userValidator = new ValidationActionFilter<User>();
userValidator.OnActionExecuting(actionExecutingContext);
/****************
* Verify
****************/
// Make sure that IsValid is being called at least once, otherwise this throws an exception. This is a behavior test
userValidatorMock.Verify();
// TODO: Also Mock HttpContext.Response and return in it's Body proeprty a memory stream where
// your ActionFilter writes to and validate the input is what you desire.
}
}
class User
{
public string Username { get; set; }
}
class ValidationActionFilter<T> : IActionFilter where T : class, new()
{
public void OnActionExecuted(ActionExecutedContext context)
{
throw new NotImplementedException();
}
public void OnActionExecuting(ActionExecutingContext actionContext)
{
var type = typeof(IValidator<>).MakeGenericType(typeof(T));
var validator = (IValidator<T>)actionContext.HttpContext
.RequestServices.GetService<IValidator<T>>();
// Get your input somehow
T input = new T();
if (!validator.IsValid(input))
{
//send errors
actionContext.HttpContext.Response.WriteAsync("Error");
}
}
}
internal interface IValidator<T>
{
bool IsValid(T input);
}
}
HttpContextUtils.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Collections.Generic;
namespace Dealz.Common.Web.Tests.Utils
{
public class HttpContextUtils
{
public static ActionExecutingContext MockedActionExecutingContext(
HttpContext context,
IList<IFilterMetadata> filters,
IDictionary<string, object> actionArguments,
object controller
)
{
var actionContext = new ActionContext() { HttpContext = context };
return new ActionExecutingContext(actionContext, filters, actionArguments, controller);
}
public static ActionExecutingContext MockedActionExecutingContext(
HttpContext context,
object controller
)
{
return MockedActionExecutingContext(context, new List<IFilterMetadata>(), new Dictionary<string, object>(), controller);
}
}
}
As you can see, it's quite a mess, you need to create plenty of mocks to simulate different responses of the actuall classes, only to be able to test the ActionAttribute in isolation.
I like #Tseng's above answer but thought of giving one more answer as his answer covers more scenarios (like generics) and could be overwhelming for some users.
Here I have an action filter attribute which just checks the ModelState and short circuits(returns the response without the action being invoked) the request by setting the Result property on the context. Within the filter, I try to use the ServiceLocator pattern to get a logger to log some data(some might not like this but this is an example)
Filter
public class ValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<ValidationFilterAttribute>>();
logger.LogWarning("some message here");
context.Result = new JsonResult(new InvalidData() { Message = "some messgae here" })
{
StatusCode = 400
};
}
}
}
public class InvalidData
{
public string Message { get; set; }
}
Unit Test
[Fact]
public void ValidationFilterAttributeTest_ModelStateErrors_ResultInBadRequestResult()
{
// Arrange
var serviceProviderMock = new Mock<IServiceProvider>();
serviceProviderMock
.Setup(serviceProvider => serviceProvider.GetService(typeof(ILogger<ValidationFilterAttribute>)))
.Returns(Mock.Of<ILogger<ValidationFilterAttribute>>());
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = serviceProviderMock.Object;
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
var actionExecutingContext = new ActionExecutingContext(
actionContext,
filters: new List<IFilterMetadata>(), // for majority of scenarios you need not worry about populating this parameter
actionArguments: new Dictionary<string, object>(), // if the filter uses this data, add some data to this dictionary
controller: null); // since the filter being tested here does not use the data from this parameter, just provide null
var validationFilter = new ValidationFilterAttribute();
// Act
// Add an erorr into model state on purpose to make it invalid
actionContext.ModelState.AddModelError("Age", "Age cannot be below 18 years.");
validationFilter.OnActionExecuting(actionExecutingContext);
// Assert
var jsonResult = Assert.IsType<JsonResult>(actionExecutingContext.Result);
Assert.Equal(400, jsonResult.StatusCode);
var invalidData = Assert.IsType<InvalidData>(jsonResult.Value);
Assert.Equal("some messgae here", invalidData.Message);
}
I'm trying to understand how can I mock the IRedisClientsManager so that I can unit test the Handle Method below using Moq.
Cheers
public class PropertyCommandHandler : ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult>
{
private readonly IRedisClientsManager _manager;
public PropertyCommandHandler(IRedisClientsManager manager)
{
this._manager = manager;
}
public PropertyCommandResult Handle(PropertySaveRequest request)
{
request.Property.OwnerId.ValidateArgumentRange();
using (var client =_manager.GetClient())
{
var propertyClient = client.As<Model.Property>();
var propertyKey = string.Format("property:{0}", request.Property.OwnerId);
propertyClient.SetEntry(propertyKey, request.Property);
client.AddItemToSet("property", request.Property.OwnerId.ToString());
}
return new PropertyCommandResult() {Success = true};
}
}
Which I call from the service like so
public class PropertyService : Service, IPropertyService
{
private readonly ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult> _commandHandler;
public PropertyService(ICommandHandlerFor<PropertySaveRequest, PropertyCommandResult> commandHandler)
{
this._commandHandler = commandHandler;
}
public object Post(PropertySaveRequest request)
{
if (request.Property == null)
throw new HttpError(HttpStatusCode.BadRequest, "Property cannot be null");
var command = _commandHandler.Handle(request);
return command;
}
}
so far this has been the approach - not sure if on right track
[Test]
public void TestMethod1()
{
//arrange
_container = new WindsorContainer()
.Install(new PropertyInstaller());
var mock = new Mock<IRedisClientsManager>();
var instance = new Mock<RedisClient>();
mock.Setup(t => t.GetClient()).Returns(instance);
// cannot resolve method error on instance
// stuck ...
var service = _container.Resolve<IPropertyService>(mock);
}
In short, since RedisClient implements IRedisClient, did you try to create the mock using the interface?
var instance = new Mock<IRedisClient>();
why are you using a real container for your unit test?
You should use an auto-mocking container or simply (since you are already taking care of the mock manually) create a real instance of your test target supplying mocks as dependencies
var target= new PropertyCommandHandler(mock);
BTW IMHO a "command handler" that returns a value sounds like a smell...
I wanna test my method with mock but it throw this exception. My class is this (this class do some simple actions on a file as though unzipping the file) :
public class FileActions
{
public virtual void Decompress(FileInfo fileInfo, DirectoryInfo directoryInfo)
{
ZipFile.ExtractToDirectory(fileInfo.FullName, directoryInfo.FullName);
}
public virtual FileInfo GetConvertedFileToZip(FileInfo fileInfo)
{
try
{
var changeExtension = Path.ChangeExtension(fileInfo.FullName, "zip");
File.Move(fileInfo.FullName, changeExtension);
return new FileInfo(changeExtension);
}
catch (Exception)
{
throw new FileNotFoundException();
}
}
}
and this is my test :
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
var fInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(fInfo)).Verifiable();
mock.VerifyAll();
}
So, why does it get this Error :
Moq.MockVerificationException: The following setups were not matched:
FileActions2 s => s.GetConvertedFileToZip(D:\ZipFiles\elmah.nupkg)
There are several issues with your Unit Test. I will only highlight the mocking side of things, as it relevant to the question you ask. Also your question has refer to "FileActions2", and I think this
a mistake when you originally add the question.
You Test:
[TestMethod]
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(fileInfo)).Verifiable();
mock.VerifyAll();
}
The way you have written this test, Moq won't verify on GetConvertedFileToZip
This test fail fundamentally because Moq cannot provide an override for a virtual method GetConvertedFileToZip. You must create a proxy i,e mock.Object.
If you modify your test in such a way so your SUT (Sysytem Under Test), consumes an instance of the mocked object/proxied object
your verify would work partially (partially means you are heading right direction). Still something else to fix which I have described below.
Assuming your SUT is like below
public class Sut
{
public void Do(FileActions fileActions)
{
var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
var s = fileActions.GetConvertedFileToZip(fileInfo);
}
}
Your Test
[TestMethod]
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(fileInfo)).Verifiable();
var sut = new Sut();
sut.Do(mock.Object);
mock.VerifyAll();
}
This would produce an exception. This is because fileInfo you have setup on does not match the verification, when invoke via the Sut.
If you were to modify this test as below, this would succeed
[TestMethod]
public void TestMockedMethodForNotNull()
{
var mock = new Mock<FileActions>();
//var fileInfo = new FileInfo(#"D:\ZipFiles\elmah.nupkg");
mock.Setup(s => s.GetConvertedFileToZip(It.IsAny<FileInfo>())).Verifiable();
var sut = new Sut();
sut.Do(mock.Object);
mock.VerifyAll();
}
If you look at the example at this link:
http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/
How would one write a unit test for the JsonAdd method? I have a similar situation in my own code, but the RenderPartialViewToString errors when calling:
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView
I've tried different ways of trying to stub that call to no avail. Any help appreciated. Thanks.
I had a lot of trouble to make unit test working with RenderPartialViewToString.
I succeeded by doing 2 things.
I had to mock the view engine and the controller context.
Here the code :
public ViewEngineResult SetupViewContent(string viewName, string viewHtmlContent)
{
var mockedViewEngine = new Mock<IViewEngine>();
var resultView = new Mock<IView>();
resultView.Setup(x => x.Render(It.IsAny<ViewContext>(), It.IsAny<TextWriter>()))
.Callback<ViewContext, TextWriter>((v, t) =>
{
t.Write(viewHtmlContent);
});
var viewEngineResult = new ViewEngineResult(resultView.Object, mockedViewEngine.Object);
mockedViewEngine.Setup(x => x.FindPartialView(It.IsAny<ControllerContext>(), viewName, It.IsAny<bool>()))
.Returns<ControllerContext, string, bool>((controller, view, useCache) =>
{
return viewEngineResult;
});
mockedViewEngine.Setup(x => x.FindView(It.IsAny<ControllerContext>(), viewName, It.IsAny<string>(), It.IsAny<bool>()))
.Returns<ControllerContext, string, string, bool>((controller, view, masterName, useCache) =>
{
return viewEngineResult;
});
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(mockedViewEngine.Object);
return viewEngineResult;
}
public void SetContext(ref PointCollecteLivraisonController controller)
{
SetupViewContent("MyViewName", "TheViewContent");
var httpContextBase = new Mock<HttpContextBase>();
var httpRequestBase = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var routes = new RouteCollection();
RouteConfigurator.RegisterRoutes(routes);
var routeData = new RouteData();
routeData.Values.Add("controller", "PointCollecteLivraison");
routeData.Values.Add("action", "RechercheJson");
httpContextBase.Setup(x => x.Response).Returns(response.Object);
httpContextBase.Setup(x => x.Request).Returns(httpRequestBase.Object);
httpContextBase.Setup(x => x.Session).Returns(session.Object);
session.Setup(x => x["somesessionkey"]).Returns("value");
httpRequestBase.Setup(x => x.Form).Returns(new NameValueCollection());
controller.ControllerContext = new ControllerContext(httpContextBase.Object, routeData, controller);
controller.Url = new UrlHelper(new RequestContext(controller.HttpContext, routeData), routes);
}
And that is the way i use it all :
PointCollecteLivraisonController controller = new PointCollecteLivraisonController();
SetContext(ref controller);
Here are my sources :
View engine mocking : http://thoai-nguyen.blogspot.fr/2011/04/test-mock-mvc-view-engine.html
Controller context mocking : ASP.NET MVC - Unit testing RenderPartialViewToString() with Moq framework?
Hope this help.
Since ViewEninges is a static class, you can't mock it with RhinoMocks. I think your best bet is to create a "partial view renderer" interface. An interface is mockable so you'll be able to stub out the complexity of rendering the view. Here's some quick pseudo-code thrown together.
First, define the partial view renderer interface:
public interface IRenderPartialView
{
string Render(string viewName, object model);
}
Then, change your base class' RenderPartialViewToString to be the implementation of IRenderPartialView.Render:
public abstract class BaseController : Controller, IRenderPartialView
{
...
public string Render(string viewName, object model)
{
// same code as RenderPartialViewToString
}
}
Now we need to change your controller constructors so we can inject an IRenderPartialView during testing -- but use the base class one during production. We can accomplish this by using a pair of constructors:
public class YourController : BaseController
{
private IRenderPartialView partialRenderer;
public YourController()
{
SetRenderer(this);
}
public YourController(IRenderPartialView partialRenderer)
{
SetRenderer(partialRenderer);
}
private void SetRenderer(IRenderPartialView partialRenderer)
{
this.partialRenderer = this;
}
}
Now, JsonAdd can call the partial view renderer:
public JsonResult JsonAdd(AddPersonViewModel AddPersonModel)
{
...
return Json(new
{
Success = true,
Message = "The person has been added!",
PartialViewHtml = partialRenderer.Render("PersonList", new PersonListViewModel {PersonList = _personList})
});
}
So, during testing, you'll mock out an IRenderPartialView and send that to the constructor that accepts an IRenderPartialView. During production, when ASP.NET MVC calls your default constructor, it will use the controller as the renderer (which has the implementation of IRenderPartialView.Render inside the base class).