GWT Unit Testing with RequestFactory / Activities - unit-testing

I'm trying to test the start method of an Activity that uses RequestFactory.
I manage to test RF calls invoking directly the service using this article example, but I'm missing something mocking RF calls called from the tested activity.
It's more clear with the code.
EDIT : more specific
What I really want to know, is how to replace the response of a Receiver method (onSuccess,onFailure...) called in an Activity? This way I would be able to test the code inside the receiver method.
So basically here is my activity :
public class MyActivity extends AbstractActivity implements MyView.Presenter {
private List<MyEntityProxy> entities;
private MyView view;
private ClientFactory cf;
private EntityRequest entityRequest;
private AppRequestFactory rf;
#Inject
public ClientsListActivity(ClientsListViewEditor view, ClientFactory clientFactory) {
this.view = view;
this.clientFactory = clientFactory;
rf = clientFactory.getRequestFactory();
}
#Override
public void start(final AcceptsOneWidget panel, EventBus eventBus) {
view.setPresenter(this);
refreshEntities();
}
public void refreshEntities(){
entityRequest = rf.entityRequest();
entityRequest.getAll().with("opt1,"opt2").fire(new Receiver<List<MyEntityProxy>>() {
#Override
public void onSuccess(List<MyEntityProxy> response) {
entities = response;
entityRequest = requestFactory.clientRequest();
}
});
}
public List<MyEntityProxy> getEntities(){
return entities;
}
}
To test it in JUnit I use GwtMockito, so here is the test class MyActivityTest :
#RunWith(GwtMockitoTestRunner.class)
public class ClientListActivityTest{
private MyActivity activity;
private EventBus eventBus;
private AppRequestFactory rf;
#GwtMock
private ClientFactory cf;
#GwtMock
private MyView;
#GwtMock
private AcceptsOneWidget panel;
#Before
public void setUp(){
eventBus = new SimpleEventBus();
rf = RequestFactoryHelper.create(AppRequestFactory.class);
cf = new ClientFactory(eventBus,rf);
activity = new MyActivity(view,cf);
}
#Test
public void testStartActivity(){
List<EntityProxy> result = new ArrayList<EntityProxy>();
EntityProxy expectedClient = mock(EntityProxy.class);
expectedEntity.setNom("Client 1");
EntityProxy expectedClient2 = mock(EntityProxy.class);
expectedEntity.setNom("Client 2");
result.add(expectedEntity);
result.add(expectedEntity2);
//Here I have to change the requestFactory Call, so I try that but without success :
Request<?> req = mock(Request.class);
doReturn(req).when(mock(MyEntityRequest.class)).getAll();
doAnswer(RequestFactoryHelper.ok(result)).when(req).fire(any(Receiver.class));
activity.start(panel, eventBus);
assertEquals(activity.getEntities().size(),2); //This Test fails size = 0
}
}
My RequestFactoryHelper (inspired from here ) :
public class RequestFactoryHelper {
private static class MockServiceLocator implements ServiceLocator {
private final Map<Class<?>, Object> services = new HashMap<Class<?>, Object>();
#Override
public Object getInstance( Class<?> clazz ) {
// Make sure to return always the same mocked instance for each requested type
Object result = services.get( clazz );
if (result == null) {
result = mock( clazz );
services.put( clazz, result );
}
return result;
}
}
private static class MockServiceDecorator extends ServiceLayerDecorator {
#Override
public <T extends ServiceLocator> T createServiceLocator( Class<T> clazz ) {
return (T) serviceLocator;
}
}
private static MockServiceLocator serviceLocator = new MockServiceLocator();
private static ServiceLayer serviceLayer = ServiceLayer.create( new MockServiceDecorator() );
/**
* Creates a {#link RequestFactory}.
*/
public static <T extends RequestFactory> T create( Class<T> requestFactoryClass ) {
SimpleRequestProcessor processor = new SimpleRequestProcessor( serviceLayer );
T factory = RequestFactorySource.create( requestFactoryClass );
factory.initialize( new SimpleEventBus(), new InProcessRequestTransport( processor ) );
return factory;
}
/**
* Returns the same service instance as used by the RequestFactory internals.
*/
public static <T> T getService( Class<T> serviceClass ) {
T result = (T) serviceLocator.getInstance( serviceClass );
reset( result ); // reset mock to avoid side effects when used in multiple tests
return result;
}
/**
* Returns the value passed to {#link Receiver#onSuccess(Object)}
*/
public static <T> T captureResult( Receiver<T> receiver ) {
ArgumentCaptor<Object> captor = ArgumentCaptor.forClass( Object.class );
verify( receiver ).onSuccess( (T) captor.capture() );
return (T) captor.getValue();
}
public static <T> Answer<T> ok(final T result) {
return new Answer<T>() {
#Override
public T answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Object _receiver = args[args.length - 1];
Receiver<T> receiver = (Receiver<T>)_receiver;
receiver.onSuccess(result);
return null;
}
};
}
}

This is how I tested the Receiver method "onSuccess". I created a custom Answer for Mockito.doAnswer.
The code to test.
public void myMethod(String arg1, String arg2) {
requestFactory.adminRequest().someMethod(arg1, arg2).fire(new Receiver<Void>() {
#Override
public void onSuccess(Void response) {
placeController.goTo(new MyPlace());
}
});
}
The test.
#Test
public void testMyMethod() {
String arg1 = "arg1";
String arg2 = "arg2";
when(requestFactory.adminRequest()).thenReturn(adminRequest);
when(adminRequest.someMethod(arg1, arg2)).thenReturn(request);
doAnswer(new Answer<Void>() {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Receiver<Void> receiver = (Receiver<Void>) args[0];
receiver.onSuccess(null);
return null;
}
}).when(request).fire(any(Receiver.class));
myActivity.myMethod(arg1, arg2);
verify(adminRequest).someMethod(arg1, arg2);
verify(request).fire(any(Receiver.class));
verify(placeController).goTo(any(myPlace.class));
}
requestFactory, adminRequest, request and placeController are all mocks.

Related

How to write Unit test for ViewModel that contains RxJava/RxAndroid

I'm trying to refactor one pretty old project, so I started implementing new architecture (MVVM) with Dagger2, RxJava, RxAndroid... Now everything is connected and working fine, now the problem is, I have no idea how to write a Unit test for my ViewModel..
I want to start with Login screen first, so I created a LoginViewModel, but first let me show you what I did..
I have a DataModule that provides 2 classes, RestApiRepository and ViewModelFactory. RestApiRepository looks like this:
public class RestApiRepository {
private RestClient restClient;
public RestApiRepository(RestClient restClient) {
this.restClient = restClient;
}
public Observable<AuthResponseEntity> authenticate(String header, AuthRequestEntity requestEntity) {
return restClient.postAuthObservable(header, requestEntity);
}
}
Rest client with api call for login:
public interface RestClient {
#POST(AUTH_URL)
Observable<AuthResponseEntity> postAuthObservable(#Header("Authorization") String authKey, #Body AuthRequestEntity requestEntity);
}
Second class from DataModule is ViewModelFactory:
#Singleton
public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory implements ViewModelProvider.Factory {
private RestApiRepository repository;
#Inject
public ViewModelFactory(RestApiRepository repository) {
this.repository = repository;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> modelClass) {
if (modelClass.isAssignableFrom(LoginViewModel.class)) {
return (T) new LoginViewModel(repository);
}
throw new IllegalArgumentException("Unknown class name");
}
}
And finally, LoginViewModel:
public class LoginViewModel extends ViewModel {
private final CompositeDisposable disposable = new CompositeDisposable();
private final MutableLiveData<AuthResponseEntity> responseLiveData = new MutableLiveData<>();
private RestApiRepository restApiRepository;
private SchedulerProvider provider;
public LoginViewModel(RestApiRepository restApiRepository, SchedulerProvider provider) {
this.restApiRepository = restApiRepository;
this.provider = provider;
}
public MutableLiveData<AuthResponseEntity> getResponseLiveData() {
return responseLiveData;
}
#Override
protected void onCleared() {
disposable.clear();
}
public void auth(String token, AuthRequestEntity requestEntity) {
if (token != null && requestEntity != null) {
disposable.add(restApiRepository.authenticate(token, requestEntity)
.subscribeOn(provider.io())
.observeOn(provider.ui())
.subscribeWith(new DisposableObserver<AuthResponseEntity>() {
#Override
public void onNext(AuthResponseEntity authResponseEntity) {
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onError(Throwable e) {
AuthResponseEntity authResponseEntity = new AuthResponseEntity();
authResponseEntity.setErrorMessage(e.getMessage());
responseLiveData.setValue(authResponseEntity);
}
#Override
public void onComplete() {
}
}
));
}
}
}
So, I'm sure everything is connected well, I can successfuly login...
For the RxAndroid test issues, I found somewhere that I have to use this Scheduler provider like this:
public class AppSchedulerProvider implements SchedulerProvider {
public AppSchedulerProvider() {
}
#Override
public Scheduler computation() {
return Schedulers.trampoline();
}
#Override
public Scheduler io() {
return Schedulers.trampoline();
}
#Override
public Scheduler ui() {
return Schedulers.trampoline();
}
}
Below is my LoginViewModelTest class, but I don't know how to handle RxJava/RxAndroid inside the tests..
#RunWith(MockitoJUnitRunner.class)
public class LoginViewModelTest {
#Mock
private RestApiRepository restApiRepository;
#Mock
private MutableLiveData<AuthResponseEntity> mutableLiveData;
private LoginViewModel loginViewModel;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
AppSchedulerProvider schedulerProvider = new AppSchedulerProvider();
loginViewModel = Mockito.spy(new LoginViewModel(restApiRepository, schedulerProvider));
}
#Test
public void authenticate_error() {
String token = "token";
AuthRequestEntity requestEntity = Mockito.mock(AuthRequestEntity.class);
Mockito.doReturn(Observable.error(new Throwable())).when(restApiRepository).authenticate(token, requestEntity);
loginViewModel.auth(token, requestEntity);
AuthResponseEntity responseEntity = Mockito.mock(AuthResponseEntity.class);
responseEntity.setErrorMessage("Error");
Mockito.verify(mutableLiveData).setValue(responseEntity);
}
}
So, I wanted to write a test for failed case when onError is called, but when I run it, I get this error:
exclude patterns:io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with. Further reading: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling | java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
You can mock the behaviour of restApiRepository:
Mockito.when(restApiRepository.authenticate(token, requestEntity)).thenReturn(Observable.error(error));
and verify that responseLiveData.setValue is being called with the appropriate parameters

JMockit: Mocking all implementations of an interface

Is it possible to mock all implementations of an interface?
I want to mock the WatchService interface like the following
public class ServiceTest {
#Test
public void callTest(
#Capturing
#Injectable
final WatchService ws
) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
new MockUp<ServiceTest>() {
#Mock(invocations = 1)
public void onChange() {
latch.countDown();
}
};
new NonStrictExpectations() {
{
ws.take();
result = new Delegate() {
WatchKey take(Invocation inv) {
System.out.println("> " + inv.getInvokedInstance());
try {
new File("target/newFile").createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return inv.proceed();
}
};
}
};
final Thread thread = new Thread() {
#Override
public void run() {
final Path target = Paths.get("target");
final FileSystem fs = target.getFileSystem();
try {
try (WatchService watcher = fs.newWatchService()) {
target.register(watcher, ENTRY_CREATE);
while (!Thread.currentThread().isInterrupted()) {
WatchKey take = watcher.take();
onChange();
System.out.println("take " + take);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
assertTrue("", latch.await(5, TimeUnit.SECONDS));
thread.interrupt();
}
private void onChange() {
System.out.println("CHANGE");
}
How can I accomplish that?
You can use the #Capturing annotation on a mock field or mock parameter of the interface type. Below we have a complete example test (minus imports).
public class CapturingAndProceedingTest {
static class WatchKey { String key; WatchKey(String k) {key = k;} }
public interface WatchService { public abstract WatchKey take(); }
static class WatchServiceImpl1 implements WatchService {
#Override public WatchKey take() { return new WatchKey("Abc"); }
}
static class WatchServiceImpl2 implements WatchService {
#Override public WatchKey take() { return new WatchKey("123"); }
}
#Test
public void mockAllImplementationsOfAnInterface(
#Capturing // so that all implementing classes are mocked
#Injectable // so that Invocation#proceed() is supported
final WatchService watchService
) {
final List<WatchService> services = new ArrayList<>();
// Record an expectation that will match all calls to
// WatchService#take(), on any class implementing the interface.
new NonStrictExpectations() {{
watchService.take();
result = new Delegate() {
WatchKey take(Invocation inv) throws IOException {
// Do something here...
WatchService service = inv.getInvokedInstance();
services.add(service);
// ...then proceed to the real implementation.
return inv.proceed();
}
};
}};
// Instantiate and use different implementations of the interface.
WatchServiceImpl1 impl1 = new WatchServiceImpl1();
assertEquals("Abc", impl1.take().key);
WatchServiceImpl2 impl2 = new WatchServiceImpl2();
assertEquals("123", impl2.take().key);
assertEquals(Arrays.asList(impl1, impl2), services);
System.out.println(services);
}
}
See the JMockit Tutorial for more examples.

When trying to use Mockito to unit test sending email, I create a multipartemail object in the function, but the test fails, why?

This is my unit testing code.
public class StatsTest extends AbstractTestCase {
#Mock
//EmailInfo mockMetricsEmail = Mockito.mock(EmailInfo.class);
//EmailSenderImpl mockEmailSenderImpl = Mockito.mock(EmailSenderImpl.class);
private MultiPartEmail mockMultiPartEmail = Mockito.mock(HtmlEmail.class);
private static final String testEmailBody = "This is the test email body.";
private static final String testSender = "seemakur#amazon.com";
private static final String testRecipient = ("seemakur#amazon.com");
private static final String testEmailSubject = "subject";
private static final String testHostName = "seemakur.desktop.amazon.com";
private static final MultiPartEmail testHtmlEmail = new HtmlEmail();
EmailSenderImpl emailSenderImplObj = new EmailSenderImpl();
EmailInfo emailInfoObj = new EmailInfo(testEmailBody, testSender, testRecipient, testEmailSubject, testHostName, testHtmlEmail);
#Before
public void setUp() throws Throwable {
super.setUp();
MockitoAnnotations.initMocks(this); // will instantiate "mockMultiPartEmail"
// instantiate our class under test
}
#Test(expected = EmailException.class)
public void testSendEmail() throws EmailException, IOException {
MultiPartEmail testMultiPartEmail = Mockito.spy(new HtmlEmail());
Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail(); //stub(spy.getMultiPartEmail()).toReturn(mockMultiPartEmail);
Mockito.when(mockMultiPartEmail.send()).thenThrow(new EmailException("Failed on multipartEmail.send(), hence could not send the email."));
// when the method under test is called
try {
//testEmailSenderImplObj.sendHtmlTableAsEmail(testMetricsEmail);
emailSenderImplObj.sendHtmlTableAsEmail(emailInfoObj); //inject mock & invoke what to test
fail("Expecting EmailException");
}catch(EmailException e){
e.printStackTrace();
}
Mockito.verify(mockMultiPartEmail).send();Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail(); //stub(spy.getMultiPartEmail()).toReturn(mockMultiPartEmail);
}
}
i have three classes associated with this email function:
firstly below is emailInfo data object
#Data
public class EmailInfo {
private String emailBody;
private String senderEmail;
private String receiversEmails;
private String emailSubject;
private String hostName;
private MultiPartEmail multiPartEmail;
public EmailInfo(String emailBody, String senderEmail, String receiversEmails, String emailSubject, String hostName, MultiPartEmail multiPartEmail) {
this.setEmailBody(emailBody);
this.setSenderEmail(senderEmail);
this.setReceiversEmails(receiversEmails);
this.setEmailSubject(emailSubject);
this.setHostName(hostName);
this.setMultiPartEmail(multiPartEmail);
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getEmailBody() {
return emailBody;
}
public void setEmailBody(String emailBody) {
this.emailBody = emailBody;
}
public String getReceiversEmails() {
return receiversEmails;
}
public void setReceiversEmails(String receiversEmails2) {
this.receiversEmails = receiversEmails2;
}
public String getEmailSubject() {
return emailSubject;
}
public void setEmailSubject(String emailSubject) {
this.emailSubject = emailSubject;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public MultiPartEmail getMultiPartEmail() {
return multiPartEmail;
}
public void setMultiPartEmail(MultiPartEmail multiPartEmail) {
this.multiPartEmail = multiPartEmail;
}
}
second class: EmailSenderImpl.java
public class EmailSenderImpl implements EmailSender{
// public MultiPartEmail getEmail(){
// return multiPartEmail;
// }
//
// public void setEmail(MultiPartEmail multiPartEmail){
// this.multiPartEmail = multiPartEmail;
// }
public void sendHtmlTableAsEmail(EmailInfo emailInfo)throws IOException, EmailException{
MultiPartEmail multiPartEmail = new HtmlEmail();
multiPartEmail.setHostName(emailInfo.getHostName());
multiPartEmail.addTo(emailInfo.getReceiversEmails());
multiPartEmail.setFrom(emailInfo.getSenderEmail());
multiPartEmail.setSubject(emailInfo.getEmailSubject());
multiPartEmail.setMsg((emailInfo.getEmailBody()).toString());
multiPartEmail.send();
}
}
lastly the EMailSender.java interface.
public interface EmailSender{
public abstract void sendHtmlTableAsEmail(EmailInfo emailInfo)throws IOException, EmailException;
}
I reason I have so many classes for one simple function is because i cannot use static methods, and i have to separate "business logic" from "function logic." And I need to have interfaces, that is necessary. If there is a better way to organize this, please let me know.
Now when I run the unit test, it fails on the line: "Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail(); //stub(spy.getMultiPartEmail()).toReturn(mockMultiPartEmail);
");"
the error reads: org.mockito.exceptions.misusing.NotAMockException
In your original code, your problem is that on this line
Mockito.doReturn(mockMultiPartEmail).when(emailInfoObj).getMultiPartEmail();
you are trying to stub the behaviour of the created with this line
EmailInfo emailInfoObj = new EmailInfo(testEmailBody, testSender, testRecipient, testEmailSubject, testHostName, testHtmlEmail);
But this is not a mock or a spy. Mockito only lets you stub the behaviour of mocks and spies, not just arbitrary objects.
I can't tell whether you still have this issue after subsequent updates, as it's impossible to read code that's embedded in comments.

EntityManger null in seam unit tests

Below is the code I am trying to test, but getting null pointer exception on entityManager.find coz entityManager = null. Any suggestions?
#Name("UserProfileConverter")
#BypassInterceptors
#Converter(forClass= UserProfile.class)
public class UserProfileConverter implements javax.faces.convert.Converter {
#Logger
private static Log logger;
public Object getAsObject(FacesContext arg0, UIComponent uiComponent, String s) {
EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");
UserProfile p;
if(s == null || s.equals("null")) {
return null;
} else {
try {
long i = Long.parseLong(s);
return entityManager.find(UserProfile.class, i);
} catch (NumberFormatException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
}
}
return null;
}
public String getAsString(FacesContext context, UIComponent uiComponetn, Object arg2) {
return ((CsaRole)arg2).getCsaRoleId() + "";
}
}
Here is my test class..
public class UserProfileConverterTest extends SeamTest {
private UserProfileConverter converter;
private FacesContext mockFacesContext;
private UIComponent mockUiComponent;
private final static Logger logger = Logger.getLogger(UserProfileConverterTest.class);
#BeforeClass
public void setup() {
converter = new UserProfileConverter();
}
#Test
public void testGetAsObject()
throws Exception {
new ComponentTest() {
#Override
protected void testComponents() throws Exception {
String value = "11111111111";
converter.getAsObject(mockFacesContext, mockUiComponent, value);
}
}.run();
}
}
public class UserProfileConverterTest extends SeamTest {
EntityManager mockEntityManager;
private UserProfileConverter converter;
UIComponent mockUiComponent = null;
MockFacesContext mockFacesContext = null;
#BeforeClass
public void setup() {
converter = new CsaUserProfileConverter();
mockEntityManager = EasyMock.createMock(EntityManager.class);
}
class BaseComponentTest extends ComponentTest {
protected void testComponents() throws Exception {
ScopeType.EVENT.getContext().set("entityManager", mockEntityManager);
}
}
#Test
public void testGetAsObject() throws Exception {
new BaseComponentTest() {
protected void testComponents() throws Exception {
super.testComponents();
UserProfile expectedResult = new UserProfile();
EasyMock.expect(mockEntityManager.find(UserProfile.class,1L)).andReturn(expectedResult);
//Replay Mock
EasyMock.replay(mockEntityManager);
Object target = converter.getAsObject(mockFacesContext,mockUiComponent,"1");
Assert.assertEquals(expectedResult, target);
//Verify the Mock
EasyMock.verify(mockEntityManager);
}
}.run();
}

Mocking, Unit Testing (NUnit) setup problem with HttpHandler

This post relates to two other posts, here and here.
I'm new to Unit Testing & Mocking. I have a test fixture that is trying to mock a HttpContext object including the response and request. I think the test code is not setup properly, as after calling the handler I get an error immediately. There error I am getting is:
UnitTests.UADHandlerFixture.Request_Is_Object:
System.NullReferenceException : Object reference not set to an instance of an object.
at Abstract.BaseHttpHandler.get_Request() in BaseHttpHandler.cs:line 21
at Abstract.BaseHttpHandler.get_IsRequestFromUAD() in BaseHttpHandler.cs:line 23
at Handlers.UADTimeHttpHandler.ProcessRequest(HttpContextBase context) in UADTimeHttpHandler.cs:line 19
at UnitTests.UADHandlerFixture.Request_Is_Object() in UADHttpHanderTests.cs:line 47
The test code is this:
[TestFixture]
public class UADHandlerFixture
{
private Mock<HttpContextBase> _mockHttpContext;
private Mock<HttpRequestBase> _mockHttpRequest;
private Mock<HttpResponseBase> _mockHttpResponse;
private UADTimeHttpHandler _handler;
private WindsorContainer _container;
[SetUp]
public void Init()
{
_mockHttpRequest = new Mock<HttpRequestBase>();
_mockHttpResponse = new Mock<HttpResponseBase>();
_mockHttpContext = new Mock<HttpContextBase>();
_container = new WindsorContainer();
_container.AddComponent<ILogger, FakeLogger>();
_container.AddComponent<IDataRepository, FakeDataRepository>();
_mockHttpContext.SetupGet(x => x.Application[0]).Returns(_container);
_mockHttpContext.SetupGet(x => x.Request).Returns(_mockHttpRequest.Object);
_mockHttpContext.SetupGet(x => x.Response).Returns(_mockHttpResponse.Object);
_handler = new UADTimeHttpHandler();
}
[Test]
public void Request_Is_Object()
{
_handler.ProcessRequest(_mockHttpContext.Object);
}
}
Handler:
public class UADTimeHttpHandler : BaseHttpHandler
{
public override void ProcessRequest(HttpContextBase context)
{
if (IsRequestFromUAD)
{
Logger.Log("Log stuff");
DataRepository.Write("DB stuff");
ReturnResponse(HttpStatusCode.OK, DateTime.Now.ToString());
}
else
ReturnResponse(HttpStatusCode.BadRequest);
}
}
BaseHandler:
public abstract class BaseHttpHandler : IHttpHandler
{
private HttpContext _httpContext;
private ILogger _logger;
private IDataRepository _dataRepository;
protected ILogger Logger { get { return _logger; } }
protected IDataRepository DataRepository { get { return _dataRepository; } }
protected HttpContext Context { get { return _httpContext; } }
protected HttpRequest Request { get { return _httpContext.Request; } }
protected HttpResponse Response { get { return _httpContext.Response; } }
protected bool IsRequestFromUAD { get { return Request.UserAgent == null ? false : Request.UserAgent.Equals("UAD"); } }
public virtual bool IsReusable { get { return false; } }
public void ProcessRequest(HttpContext context)
{
WindsorContainer container = (WindsorContainer)context.Application[0];
_logger = container.Resolve<ILogger>();
_dataRepository = container.Resolve<IDataRepository>();
_httpContext = context;
ProcessRequest(new HttpContextWrapper(context));
}
protected virtual void ReturnResponse(HttpStatusCode httpStatus)
{
Response.StatusCode = (int)httpStatus;
}
protected virtual void ReturnResponse(HttpStatusCode httpStatus, string response)
{
Response.StatusCode = (int)httpStatus;
Response.Write(response);
}
protected virtual string GetInputStream()
{
using (var reader = new StreamReader(Request.InputStream))
{
return reader.ReadToEnd();
}
}
public abstract void ProcessRequest(HttpContextBase context);
}