Unit testing middleware with NUnit and NSubstitute - unit-testing

I've written a bit of middleware in an ASP.NET Core site and I'm trying to unit test it, mainly by following this guide that uses Moq.
My problem is finding an NUnit/NSubstitute equivalent for new DefaultHttpContext(). Substituting HttpContext will trigger the middleware, but it passes the try. I presume this is because of the issue quoted below. Does NUnit have a function to create a real HttpContext, or am I looking at a lot more infrastructure to achieve this?
I am sending an instance of DefaultHttpContext to the Invoke method. I can't use a mocked HttpContext in this scenario because the first middleware (the lambda function that we passed to the constructor) will need to write to the response. Hence the HttpResponse needs to be a real object not mocked.
Here is the code for my Test
[TestFixture]
public class ExceptionHelperTests
{
private IErrorRepository errorRepository;
private ExceptionHandler handler;
[SetUp]
public void Setup()
{
errorRepository = Substitute.For<IErrorRepository>();
}
[Test]
public async void Given_AnExceptionHappens_Then_ItShouldBeLogged()
{
// Arrange
const string username = "aUser";
var user = Substitute.For<ClaimsPrincipal>();
user.Identity.Name.Returns(username);
handler = new ExceptionHandler(
next: async (innerHttpContext) =>
{
innerHttpContext.User = user;
},
repository: errorRepository);
// Act
await handler.Invoke(new DefaultHttpContext());
// Assert
errorRepository.Received().LogException(Arg.Any<string>(), Arg.Any<Exception>(), Arg.Is(username));
}
}
Here is the IErrorRepository
public interface IErrorRepository
{
Exception LogException(string message, Exception ex, string userId);
void LogMessage(string message, string errorDetail, string userId);
}
And here is the middleware (with a simplified HandleException):
public sealed class ExceptionHandler
{
private readonly RequestDelegate _next;
private readonly IErrorRepository repository;
public ExceptionHandler(RequestDelegate next, IErrorRepository repository)
{
_next = next;
this.repository = repository;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
HandleException(ex, context.User.Identity.Name);
}
}
public void HandleException(Exception ex, string userId)
{
repository.LogException("An unhandled exception has occurred.", ex, userId);
}
}

DefaultHttpContext is just the default implementation of HttpContext abstract class.
You just could do
var HttpContextSub = Substitute.For<HttpContext>();

Related

getExchange from mockEndPoint in a unit-test class for Camel Route Not Behaving As Expected

I want to getExchanges from a mockEndPoint in a unit-test class for Camel Route but it doesn't work.
Here is my unit test class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:camel-unit-test.xml")
public class ImportDatabaseRouteTest extends CamelTestSupport {
#Value("${sql.importDatabase}")
String oldEndPoint;
#Autowired
private ImportDatabaseRoute importDatabaseRoute;
#Autowired
private DriverManagerDataSource dataSource;
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return importDatabaseRoute;
}
#Before
public void mockEndpoints() throws Exception {
AdviceWithRouteBuilder adviceTest = new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
interceptSendToEndpoint(oldEndPoint)
.skipSendToOriginalEndpoint()
.to("mock:catchCSVList");
}
};
context.getRouteDefinitions().get(0).adviceWith(context, adviceTest);
}
#Override
public boolean isUseAdviceWith() {
return true;
}
#Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
//use jndi.bind to bind your beans
jndi.bind("dataSource", dataSource);
return jndi;
}
#Test
public void testTheImportRoute() throws Exception {
MockEndpoint mockEndPointTest = getMockEndpoint("mock:catchCSVList");
context.start();
List<List<String>> test = (List<List<String>>) mockEndPointTest.getExchanges().get(0).getIn().getBody();
assertEquals("4227",test.get(1).get(0));
assertEquals("370",test.get(1).get(1));
assertEquals("",test.get(1).get(2));
mockEndPointTest.expectedMessageCount(1);
mockEndPointTest.assertIsSatisfied();
context.stop();
}
}
And here are the results:
java.lang.ArrayIndexOutOfBoundsException: 0
at java.util.concurrent.CopyOnWriteArrayList.get(CopyOnWriteArrayList.java:387)
Please help me to fix it. Thank you so much.
You have to assert the mock before you get the exchanges. As those exchanges are the actual exchange that arrived at the mock. So its expectations has to be meet first, which says 1 message should arrive. And if that is success, then you can get that exchange via index 0, and you will not get an IndexOutOfBoundsException
MockEndpoint mockEndPointTest = getMockEndpoint("mock:catchCSVList");
context.start();
// set expectations on mock here
mockEndPointTest.expectedMessageCount(1);
mockEndPointTest.assertIsSatisfied();
// okay now we can get the exchange's from the mock
List<List<String>> test = (List<List<String>>) mockEndPointTest.getExchanges().get(0).getIn().getBody();
assertEquals("4227",test.get(1).get(0));
assertEquals("370",test.get(1).get(1));
assertEquals("",test.get(1).get(2));
context.stop();

handling exception for RestAPI unit test

I have a method
public class ActivityManager {
private ActivityManager activityManager_;
#Autowired
public ActivityManager(ActivityManager activityManage)
{
activityManager_= activityManage;
}
#RequestMapping(value ="activityManager/", method = RequestMethod.GET)
public List<Data> getData() throws RestControllerException {
try {
return activityManage_.fetchData();
} catch (Exception ex) {
throw new RestControllerException();
}
}
}
And I tried to test the throw exception but it does not work. I got confused into the case what's the status() for resultmatcher should be.
#Test(expected = RestControllerException.class)
public void getDataError() throws Exception {
ActivityManager activityManagerMock = Mockito.mock(ActivityManager
.class);
doThrow(RestControllerException.class).when(activityManagerMock).fetchData();
mockMvc_.perform(get("/activityManager")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isInternalServerError());
}
Is there any document that I can read more about handling exception for restapi unit test?
Thanks
#Autowired
private ActivityManagerService activityManager;
This will inject the actual bean into the controller not the mock which you created.
Add this inside your test class.
#Autowired
private ControllerBean controller;
#Before
public void init(){
ReflectionTestUtils.setField(controller, "activityManager", activityManagerMock);
}
This will set the MockObject into activityManager of Controller.
And hence while running test the mock objects fetchData() will be called which inturn throws the exception.

How to mock event in HttpModule

I have a simple Http module:
public class CustomLoggingModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += BeginRequest;
context.EndRequest += EndRequest;
}
public void BeginRequest(object sender, EventArgs eventArgs)
{
//some code
}
public void EndRequest(object sender, EventArgs eventArgs)
{
//some
}
public void Dispose()
{
}
}
How can I unit test this? Especially how is it possible to mock events? Can anyone give some simple example?
Not sure why you have decided to hardwire the dependencies as new LogService() and new HttpContextWrapper(HttpContext.Current) within the CustomLoggingModule. If want to test whether LogInfo() method is called or not, it becomes lot easier if you can externalize these dependencies so you can inject stubbed/mocked version etc.
Also your question does not state that you are using an IOC container. You can register the HttpModule with the container and provide external dependencies at runtime. Your question also does not state that using an isoloation/mock object framework.
Therefore I will provide you with a solution that you can verify whether LogInfo method is called, using hand written stubs and mocks.
To achieve this, we need to refactor CustomLoggingModule a bit, so it becomes more testable.
System Under Test (SUT)
public class CustomLoggingModule : IHttpModule
{
public ILogService LogService { get; set; }
public Func<ILoggingHttpContextWrapper> LogginHttpContextWrapperDelegate { get; set; }
public void Init(HttpApplication context) {
context.BeginRequest += BeginRequest;
context.EndRequest += EndRequest;
}
public CustomLoggingModule() {
LogginHttpContextWrapperDelegate = () => new LoggingHttpContextWrapper();
}
public void BeginRequest(object sender, EventArgs eventArgs) {
LogService.LogInfo(LogginHttpContextWrapperDelegate().HttpContextWrapper);
}
public void EndRequest(object sender, EventArgs eventArgs) {
//some
}
public void Dispose(){ }
}
As you see above, I have introduced 2 additional properties - ILogService so I can provide a Mocked verion and a delegate Func which allows me to stub the
new HttpContextWrapper(HttpContext.Current);
public interface ILoggingHttpContextWrapper {
HttpContextWrapper HttpContextWrapper { get; }
}
public class LoggingHttpContextWrapper : ILoggingHttpContextWrapper
{
public LoggingHttpContextWrapper() {
HttpContextWrapper = new HttpContextWrapper(HttpContext.Current);
}
public HttpContextWrapper HttpContextWrapper { get; private set; }
}
And then your real ILogService
public interface ILogService {
void LogInfo(HttpContextWrapper httpContextWrapper);
}
public class LogService : ILogService {
public void LogInfo(HttpContextWrapper httpContextWrapper)
{
//real logger implementation
}
}
Unit Test :
You would create a MockLoggerService, so you can verify the interaction i,e whether the LogInfo() method was called, etc. You also need a stubbed LoggingHttpContextWrapper to provide the fake HttpContextWrapper to the SUT (System Under Test)/ CustomLoggingModule.
public class StubLoggingHttpContextWrapper : ILoggingHttpContextWrapper
{
public StubLoggingHttpContextWrapper(){}
public HttpContextWrapper HttpContextWrapper { get; private set; }
}
public class MockLoggerService : ILogService
{
public bool LogInfoMethodIsCalled = false;
public void LogInfo(HttpContextWrapper httpContextWrapper) {
LogInfoMethodIsCalled = true;
}
}
MockLoggerService is very important. It is not the real logger service, but it is the mocked version. When we do public class MockLoggerService : ILogService this means that we are providing another layer of indirection to the logger service so we can verify the interaction of the behaviour.
You also notice that I have provided a boolean variable to verify whether the LogInfo method is called or not. This allows me to call this method from the SUT, and verify whether the method being called or not.
Now Your Unit Test can be implemented as below.
[TestMethod]
public void CustomLoggingModule_BeginRequest_VerifyLogInfoMethodIsCalled()
{
var sut = new CustomLoggingModule();
var loggerServiceMock = new MockLoggerService();
var loggingHttpContextWrapperStub = new StubLoggingHttpContextWrapper();
sut.LogService = loggerServiceMock;
sut.LogginHttpContextWrapperDelegate = () => loggingHttpContextWrapperStub;
sut.BeginRequest(new object(), new EventArgs());
Assert.IsTrue(loggerServiceMock.LogInfoMethodIsCalled);
}
I had the same issue with my custom http module and decided I won't give up that easily and will do all I can to trigger the BeginRequest event in unit test. I had to actually read through the source code of HttpApplication class and use reflection to invoke the method.
[TestMethod]
public void EventTriggered_DoesNotError()
{
using (var application = new HttpApplication())
{
var module = new CustomLoggingModule();
module.Init(application);
FireHttpApplicationEvent(application, "EventBeginRequest", this, EventArgs.Empty);
}
}
private static void FireHttpApplicationEvent(object onMe, string invokeMe, params object[] args)
{
var objectType = onMe.GetType();
object eventIndex = (object)objectType.GetField(invokeMe, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).GetValue(onMe);
EventHandlerList events = (EventHandlerList)objectType.GetField("_events", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(onMe);
EventHandler handler = (EventHandler)events[eventIndex];
Delegate[] delegates = handler.GetInvocationList();
foreach (Delegate dlg in delegates)
{
dlg.Method.Invoke(dlg.Target, args);
}
}

How to mock HttpSession in JSF

i have a service method that get session attribute and i want to make unit test for this service method and i was wondering how to mock the HttpSession in jsf.
1- use the FacesContextMocker class:
public abstract class FacesContextMocker extends FacesContext {
private FacesContextMocker() {}
private static final Release RELEASE = new Release();
private static class Release implements Answer<Void> {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
setCurrentInstance(null);
return null;
}
}
public static FacesContext mockFacesContext() {
FacesContext context = Mockito.mock(FacesContext.class);
setCurrentInstance(context);
Mockito.doAnswer(RELEASE).when(context).release();
return context;
}
}
2- in the test class #Before method do the following:
FacesContextMocker.mockFacesContext();
ExternalContext externalContext = Mockito.mock(ExternalContext.class);
Mockito.when(FacesContext.getCurrentInstance().getExternalContext())
.thenReturn(externalContext);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(
FacesContext.getCurrentInstance().getExternalContext()
.getRequest()).thenReturn(request);
HttpSession httpSession = Mockito.mock(HttpSession.class);
Mockito.when(GeneralUtils.getHttpSession()).thenReturn(httpSession);
3- the getHttpSession method is as follows:
public static HttpSession getHttpSession() {
return ((HttpServletRequest) FacesContext.getCurrentInstance()
.getExternalContext().getRequest()).getSession();
}
4- in the test method do the following:
Mockito.when(
GeneralUtils.getHttpSession().getAttribute(
"userID")).thenReturn("1");
5- this is assuming that in your service method that you are making the unit test for you have code like:
String currentUserID = (String) GeneralUtils.getHttpSession()
.getAttribute(userID);

Mocking digest authentication in RestEasy

I am using RestEasy to develop a REST server and using the mock dispatcher (org.jboss.resteasy.mockMockDispatcherFactory) for testing the service in my unit tests. My service requires digest authentication and I would to make that part of my testing.
Each of my services accepts a #Context SecurityContext securityContext parameter.
Is there any way is inject a fake SecurityContext in the dispatcher so that I can test that my security methods function properly?
You have to add the SecurityContext into the context data map in ResteasyProviderFactory.
public class SecurityContextTest {
#Path("/")
public static class Service {
#Context
SecurityContext context;
#GET
public String get(){
return context.getAuthenticationScheme();
}
}
public static class FakeSecurityContext extends ServletSecurityContext {
public FakeSecurityContext() {
super(null);
}
#Override
public String getAuthenticationScheme() {
return "unit-test-scheme";
}
}
#Test
public void securityContextTest() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new Service());
ResteasyProviderFactory.getContextDataMap().put(SecurityContext.class, new FakeSecurityContext());
MockHttpRequest request = MockHttpRequest.get("/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals("unit-test-scheme", response.getContentAsString());
}
}
For those coming across this issue today, adding Contexts has been moved from the RestEasyProviderFactory class into the Dispatcher class using getDefaultContextObjects() method.
I've edited the old answer with the new call:
public class SecurityContextTest {
#Path("/")
public static class Service {
#Context
SecurityContext context;
#GET
public String get(){
return context.getAuthenticationScheme();
}
}
public static class FakeSecurityContext extends ServletSecurityContext {
public FakeSecurityContext() {
super(null);
}
#Override
public String getAuthenticationScheme() {
return "unit-test-scheme";
}
}
#Test
public void securityContextTest() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new Service());
dispatcher.getDefaultContextObjects().put(SecurityContext.class, new FakeSecurityContext());
MockHttpRequest request = MockHttpRequest.get("/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertEquals("unit-test-scheme", response.getContentAsString());
}
}