EntityManger null in seam unit tests - unit-testing

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();
}

Related

On using swipe refresh in recyclerview my adapter is not getting data when it is refreshing

My Latest fragment
public class Latest extends Fragment {
private RecyclerView recyclerLatest;
private SwipeRefreshLayout swipeRecycler;
private RecyclerView.LayoutManager mLayoutManager;
private List<LatestAdDetails> latestAdDetailsList = new ArrayList<>();
private LatestAdapter latestAdapter;
private LatestAdDetails latestAdDetails,latestAdDetails1;
private JSONObject jsonobject;
private Context context;
private String x;
public Latest() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View mainView=inflater.inflate(R.layout.latest_fragment,container,false);
recyclerLatest = (RecyclerView) mainView.findViewById(R.id.recycler_latest);
swipeRecycler= (SwipeRefreshLayout)mainView.findViewById(R.id.swipe_recycler_latest);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerLatest.setLayoutManager(mLayoutManager);
recyclerLatest.setHasFixedSize(true);
context = getContext();
// url for latest add obtaining
UrlConstants.latest_ad_obtained= UrlConstants.latest_ad+ AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+AppController.getString(getActivity().getApplicationContext(),"city_id");
latestAdapter = new LatestAdapter(latestAdDetailsList);
recyclerLatest.setAdapter(latestAdapter);
latestAdd();
swipeRecycler.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(){refreshLatestAd();
}
});
return mainView;
}
private void refreshLatestAd() {
UrlConstants.latset_ad_refresh_obtained=UrlConstants.latest_ad_refresh+
AppController.getString(getActivity().getApplicationContext(),"country_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"city_id")+"/"+
AppController.getString(getActivity().getApplicationContext(),"refresh_ad")+"/"+0;
LatestRefreshHandler latestRefreshHandler = new LatestRefreshHandler("latestRefreshADD");
latestRefreshHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
latestAdapter.clear();
int Ad_id_refresh = jsonarray.getJSONObject(jsonarray.length()).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.addAll(latestAdDetailsList);
latestAdapter.notifyDataSetChanged();
recyclerLatest.setAdapter(latestAdapter);
swipeRecycler.setRefreshing(false);
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}
private void latestAdd() {
LatestRequestHandler latestHandler = new LatestRequestHandler("latestADD");
latestHandler.executeAsStringRequest(new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("response", response);
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < jsonarray.length(); i++) {
try {
jsonobject = jsonarray.getJSONObject(i);
if (jsonobject.getString("default_photo").isEmpty()) {
x = UrlConstants.default_photo;
} else {
x = jsonobject.getString("default_photo");
}
Log.e("x", x);
int Ad_id_refresh = jsonarray.getJSONObject(1).getInt("id");
AppController.setString(context,"refresh_ad", String.valueOf(Ad_id_refresh));
latestAdDetails = new LatestAdDetails(
jsonobject.getInt("id"),
jsonobject.getInt("cityid"),
jsonobject.getInt("price"),
jsonobject.getInt("type"),
jsonobject.getInt("comments"),
jsonobject.getInt("categoryid"),
jsonobject.getInt("MainCategoryID"),
jsonobject.getInt("created"),
jsonobject.getInt("views"),
jsonobject.getString("title"),
jsonobject.getString("default_photo"),
jsonobject.getString("CityName"),
jsonobject.getString("CategoryName"),
jsonobject.getString("storeid"),
jsonobject.getString("currency"),
jsonobject.getString("description"),
jsonobject.getDouble("Latitude"),
jsonobject.getDouble("Longitude")
);
latestAdDetailsList.add(latestAdDetails);
} catch (JSONException e) {
e.printStackTrace();
}
}
latestAdapter.notifyDataSetChanged();
}
}, new BaseRequest.ErrorResponseCallback() {
#Override
public void onError(Exception exception) {
}
});
}}
my Adapter class
public class LatestAdapter extends RecyclerView.Adapter<LatestAdapter.MyViewHolder> {
private ImageLoader imageLoader;
private Context context;
private String text;
private List<LatestAdDetails> latestAddDetailsList;
public LatestAdapter(List<LatestAdDetails> latestAddDetailsList) {
this.latestAddDetailsList = latestAddDetailsList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle, txtDescription, txtCityName, txtPrice, txtCategory, txtHour, txtPhotoNo;
private NetworkImageView imgPhoto;
public MyViewHolder(View itemView) {
super(itemView);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_fad);
txtDescription = (TextView) itemView.findViewById(R.id.description_fad);
txtCityName = (TextView) itemView.findViewById(R.id.city_name_fad);
txtPrice = (TextView) itemView.findViewById(R.id.price_fad);
txtCategory = (TextView) itemView.findViewById(R.id.category_fad);
txtHour = (TextView) itemView.findViewById(R.id.hours_fad);
txtPhotoNo = (TextView) itemView.findViewById(R.id.txt_photo_no_fad);
imgPhoto = (NetworkImageView) itemView.findViewById(R.id.img_photo_lod_fad);
}
}
public void clear() {
latestAddDetailsList.clear();
notifyDataSetChanged();
}// Add a list of items
public void addAll(List<LatestAdDetails> list) {
latestAddDetailsList.addAll(list);
notifyDataSetChanged();
}
#Override
public LatestAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.featured_ad_adapter_layout, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(LatestAdapter.MyViewHolder holder, int position) {
LatestAdDetails latestAddDetails = latestAddDetailsList.get(position);
holder.txtTitle.setText(translate(latestAddDetails.getTitle()));
holder.txtDescription.setText(translate(latestAddDetails.getDescription()));
holder.txtCityName.setText(translate(latestAddDetails.getCityName()));
holder.txtPrice.setText(Integer.toString(latestAddDetails.getPrice()));
holder.txtCategory.setText(translate(latestAddDetails.getCategoryName()));
holder.txtHour.setText(Integer.toString(latestAddDetails.getCreated()));
holder.txtPhotoNo.setText(Integer.toString(0) + " photos ");
try {
imageLoader = VolleyHandler.getImageLoader();
} catch (Exception e) {
e.printStackTrace();
}
holder.imgPhoto.setImageUrl(latestAddDetails.getDefault_photo(), imageLoader);
}
#Override
public int getItemCount() {
Log.e("size", String.valueOf(latestAddDetailsList.size()));
return latestAddDetailsList.size();
}
private String translate(String myString) {
try {
myString = myString.replace("\n", "").replace("\r", "");
byte[] utf8Bytes = myString.getBytes("UTF8");
text = new String(utf8Bytes, "UTF8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return text;
}}
on refreshing adapter size is zero,but getting json correctly,but not adding to adapter,and the recycler view is not showing new data,please help me ,the json is giving 10 datas on every swipe but it is not getting added to recyclerview
It seems like a logical bug :
In method : refreshLatestAd(), Remove these line :
latestAdapter.clear();
latestAdapter.addAll(latestAdDetailsList);
and
recyclerLatest.setAdapter(latestAdapter); // It need not be set again.
Let me know if it helps.
latestAdapter.notifyDataSetChanged() is sufficient to notify the
adapter that the data is changed. Always modify the list
[latestAdDetailsList] which is being set to adapter, this is the sure
shot way to make the changes reflect when you call notifyDataSetChanged.

GWT Unit Testing with RequestFactory / Activities

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.

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.

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);
}

Loading .eml files into javax.mail.Messages

I'm trying to unit test a method which processes javax.mail.Message instances.
I am writing a converter to change emails which arrive in different formats and are then converted into a consistent internal format (MyMessage). This conversion will usually depend on the from-address or reply-address of the email, and the parts of the email, the subject, and the from- and reply-addresses will be required for creating the new MyMessage.
I have a collection of raw emails which are saved locally as .eml files, and I'd like to make a unit test which loads the .eml files from the classpath and converts them to javax.mail.Message instances. Is this possible, and if so, how would it be done?
After a few tests, I finally successfully loaded a message using the MimeMessage(Session, InputStream) public constructor (as opposed to the Folder-based protected one cited in the other response).
import java.io.FileInputStream;
import java.io.InputStream;
import javax.mail.internet.MimeMessage;
public class LoadEML {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream(args[0]);
MimeMessage mime = new MimeMessage(null, is);
System.out.println("Subject: " + mime.getSubject());
}
}
My problem came from using Mockito to mock the javax.mail.Folder required by javax.mail.internet.MimeMessage's constructor MimeMessage(Folder, InputStream, int). This calls the constructor for javax.mail.Message Message(Folder, int) which then accesses folder.store.session. This resulted in a NullPointerException being thrown by the constructor for MimeMessage.
Solution:
class ClasspathMimeMessage extends MimeMessage {
private ClasspathMimeMessage(Folder folder, InputStream is, int msgnum) throws MessagingException {
super(folder, is, 0);
}
public static MimeMessage create(String resourceName) {
Class<PopEmailMmsReceiverTest> loaderClass = PopEmailMmsReceiverTest.class;
InputStream is = loaderClass.getResourceAsStream(resourceName);
Folder inbox = new MyFolder();
try {
return new ClasspathMimeMessage(inbox, is, 0);
} catch (MessagingException ex) {
throw new RuntimeException("Unable to load email from classpath at " + loaderClass.getResource(resourceName).toString());
}
}
}
class MyFolder extends Folder {
MyFolder() {
super(createMockStore());
}
private static Store createMockStore() {
return mock(Store.class);
}
public void appendMessages(Message[] msgs) throws MessagingException {
}
public void close(boolean expunge) throws MessagingException {
}
public boolean create(int type) throws MessagingException {
return false;
}
public boolean delete(boolean recurse) throws MessagingException {
return false;
}
public boolean exists() throws MessagingException {
return false;
}
public Message[] expunge() throws MessagingException {
return null;
}
public Folder getFolder(String name) throws MessagingException {
return null;
}
public String getFullName() {
return null;
}
public Message getMessage(int msgnum) throws MessagingException {
return null;
}
public int getMessageCount() throws MessagingException {
return 0;
}
public String getName() {
return null;
}
public Folder getParent() throws MessagingException {
return null;
}
public Flags getPermanentFlags() {
return null;
}
public char getSeparator() throws MessagingException {
return 0;
}
public int getType() throws MessagingException {
return 0;
}
public boolean hasNewMessages() throws MessagingException {
return false;
}
public boolean isOpen() {
return false;
}
public Folder[] list(String pattern) throws MessagingException {
return null;
}
public void open(int mode) throws MessagingException {
}
public boolean renameTo(Folder f) throws MessagingException {
return false;
}
}
This looks very ugly to me, so if anyone has a better suggestion, I'd be delighted to hear it.