Testing DoFn Apache Crunch - java

I am very new to Apache Crunch. This is the first test case I have written. Currently I am writing test cases for DoFn but it says NullPointerException.
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import org.apache.crunch.Emitter;
import org.apache.crunch.Pair;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class OutputResultTest {
#Mock
InMemoryEmitter <String> emitter = new InMemoryEmitter<>();
#Test
public void TestProcess(){
OutputResult outputResult = new OutputResult();
//String expected = "Thor Odinson scored 97.8";
Pair<String,Double> input = Pair.of("Thor Odinson",97.8);
outputResult.process(input,emitter);
assertEquals(expected,emitter.getOutput());
//verify(emitter).emit("Thor Odinson scored 97.8");//this works
//verifyNoMoreInteractions(emitter);//this works
}
}

Related

Apache camel - I want to send to my mock endpoint

I have this test class - currently it is checking the response at the endpoint
Endpoints.SEDA_PROCESS_ENDPOINT
but I need it to check at
"mock:"+Endpoints.SEDA_PROCESS_ENDPOINT
Is there a way to forward the response to this mock endpoint I have just defined?
below is my test class
package com.sams.pricing.prism.data.processor;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.MockEndpoints;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.sams.pricing.prism.data.processor.model.CostIQRetail;
import com.sams.pricing.prism.data.processor.routes.PrismRouter;
import com.sams.pricing.prism.data.processor.service.RulesEngineClient;
import com.sams.pricing.prism.data.processor.util.Endpoints;
#SpringBootTest
#CamelSpringBootTest
#MockEndpoints( Endpoints.SEDA_PROCESS_ENDPOINT)
public class CamelRouteTests3 {
#Autowired
private ProducerTemplate template;
#EndpointInject( "mock:" + Endpoints.SEDA_PROCESS_ENDPOINT)
private MockEndpoint mock;
#Mock
private PrismRouter p;
#Mock
private RulesEngineClient rulesEngineClientMock;
public CostIQRetail costIQObject() {
CostIQRetail obj = new CostIQRetail();
obj.setItemNbr(123);
obj.setLocationNbr(4931);
obj.setIsDcFlag(false) ;
obj.setStatus("SUCCESS");
obj.setOrderableCost(new BigDecimal((10.0)));
obj.setWarehousePackCost(new BigDecimal(100.0));
obj.setOrderablePrepaidCost(null) ;
obj.setOrderableCollectCost(null) ;
obj.setReasonCode("Markdown - category funded");
obj.setEffectiveDate("2022-12-29");
obj.setIsFutureEffectiveDate(false);
obj.setCostType("WAREHOUSE PACK COST");
obj.setSource("COST IQ");
obj.setCreatedBy("lab1 account");
obj.setCreatedByUserId("LB-cost-test");
obj.setCreatedTs("2022-12-29T02:42:25.529Z");
obj.setCurrentRetailPrice(new BigDecimal(55.0)) ;
obj.setCurrentOrderableCost(null);
obj.setCurrentWarehousePackCost(new BigDecimal((0.0)));
obj.setCurrentOrderablePrepaidCost(null) ;
obj.setCurrentOrderableCollectCost(null);
obj.setMarginChange(new BigDecimal((-100.0)));
obj.setOwedToClub(new BigDecimal((0.0)));
obj.setItemSourceId(3572924);
obj.setPriceDestId(701800);
obj.setCategory(87);
obj.setOrderableQty(null);
obj.setOldMargin(new BigDecimal((100.0)));
obj.setNewMargin(new BigDecimal(0.0));
return obj;
}
private String costIQPayloadString() throws JsonProcessingException
{
String key = "{\"retailTypeReasonCode\":{\"retailTypeReasonCodeId\":{\"retailType\":\"BP\",\"retailReasonCode\":\"CC\"}},\"expirationDate\":null,\"customerRetailAmount\":0.0,\"auditMessage\":null,\"createdTimestamp\":null,\"clientID\":\"COST IQ\",\"rowNumber\":0,\"auditRecordTimestamp\":null,\"clubNumber\":4931,\"itemNumber\":123,\"effectiveDate\":\"2022-12-29\",\"submissionID\":null,\"retailAmount\":55.0,\"createdBy\":\"lab1 account\"}";
String key2 = "{\"retailTypeReasonCode\":{\"retailTypeReasonCodeId\":{\"retailType\":\"BP\",\"retailReasonCode\":\"CC\"}},\"expirationDate\":null,\"customerRetailAmount\":0.0,\"auditMessage\":null,\"createdTimestamp\":null,\"clientID\":\"COST IQ\",\"rowNumber\":0,\"auditRecordTimestamp\":null,\"categoryId\":87,\"subCategoryId\":1,\"clubNumber\":4931,\"itemNumber\":123,\"effectiveDate\":\"2022-12-29\",\"submissionID\":null,\"retailAmount\":10.0,\"createdBy\":\"lab1 account\"}";
return key2;
}
#Test
void test() throws Exception {
// Set up the mock endpoints
mock.expectedBodiesReceived(costIQPayloadString());
//p.interceptSendToEndpoint( Endpoints.SEDA_PROCESS_ENDPOINT).to(mock.getEndpointUri());
Mockito.when(rulesEngineClientMock.validateRules((costIQObject()))).thenReturn(costIQObject()); //.thenR
Map<String, Object> headers = new HashMap<>();
headers.put("appName", "costIQ");
// Send the test message to the SEDA_SEND_ENDPOINT
template.sendBodyAndHeaders(Endpoints.SEDA_SEND_ENDPOINT, costIQObject(), headers);
mock.assertIsSatisfied();
}
}
I have looked at advice with but that involves adding in the cameltestsupport and would need to re-write this code. Is there a way to do this with current implementations?

Mockito returning results from database and not results from when()

I have this problem where Mockito returns the result the actual controller would have given if the service has started. I want it to return the goats list I made and set in the when() function.
package com.goatpool.goatpool;
import com.goatpool.goatpool.controller.GoatController;
import com.goatpool.goatpool.model.Goat;
import com.goatpool.goatpool.service.HBMGoatService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#RunWith(MockitoJUnitRunner.class)
class GoatControllerTest {
#InjectMocks
GoatController goatController;
#Mock
HBMGoatService hbmgoatService;
#Before
public void setup(){
//runs before the tests
}
#Test
void testGetAllGoats() throws Exception {
//Arrange
List<Goat> goats = new ArrayList<>();
goats.add(new Goat(1, "1","20001","buck", new Date() ,12.02f,1,3,24.68f,null,"Some Info",true,100));
goats.add(new Goat(2,"2","20056","doe",new Date() ,16.02f,1,3,20.68f,null ,"Some Info",true,12));
goats.add(new Goat(3,"3","21060","doe",new Date() ,16.02f,1,3,0f,null,"No Info",true,12));
goats.add(new Goat(4,"4","1212","buck",new Date() ,1.3f,1,3,0.5f,null,"No Info",true,12));
//Act
MockitoAnnotations.initMocks(this);
Mockito.when(hbmgoatService.getGoatList()).thenReturn(goats); //mock
List<Goat> result = goatController.getAllGoats();
//Assert
String actualResults = result.toString();
String expectedResults = goats.toString();
Assert.assertEquals(expectedResults, actualResults);
}
}

How to fix java.lang.IllegalStateException: You have not started an Objectify context

I am trying to take a test driven development approach to building a Java based app running on App Engine, but I am having difficulties getting the setup working.
My servlet
package mobi.grocerymonkey.groceryapp;
import com.google.appengine.api.utils.SystemProperty;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.Properties;
import org.json.JSONObject;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import static com.googlecode.objectify.ObjectifyService.ofy;
import com.googlecode.objectify.ObjectifyService;
/* This is the servlet */
#WebServlet(name = "GroceryServlet", value = "/grocery")
public class GroceryServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(GroceryServlet.class.getName());
#Override
public void init() throws ServletException {
log.info("context init");
ObjectifyService.init();
ObjectifyService.register(Grocery.class);
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain");
response.getWriter().println("Hello Kitty");
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
BufferedReader reader = request.getReader();
String line = null;
StringBuffer stringBuffer = new StringBuffer();
while((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
String jsonString = stringBuffer.toString();
JSONObject json = new JSONObject(jsonString);
log.info("JSON "+ jsonString);
Grocery grocery = new Grocery();
grocery.setName((String) json.get("name"));
grocery.setQuantity((Integer) json.get("quantity"));
ofy().save().entity(grocery).now();
log.info("JSON name "+ grocery.getName());
response.setContentType("application/json");
response.getWriter().println(jsonString);
}
}
web.xml file
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>ObjectifyFilter</filter-name>
<filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ObjectifyFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
</web-app>
My unit test
package mobi.grocerymonkey.groceryapp;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.DatastoreOptions;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.json.JSONObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.Reader;
import java.io.Closeable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Unit tests for {#link HelloAppEngine}.
*/
#RunWith(JUnit4.class)
public class GroceryServletTest {
private static final String MOCK_URL = "/grocery";
// Set up a helper so that the ApiProxy returns a valid environment for local testing.
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private Closeable closeable;
#Mock
private HttpServletRequest mockRequest;
#Mock
private HttpServletResponse mockResponse;
private StringWriter responseWriter;
private GroceryServlet servletUnderTest;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
helper.setUp();
ObjectifyService.init(new ObjectifyFactory(
DatastoreOptions.newBuilder()
.setHost("http://localhost:8081")
.setProjectId("enduring-trees-259812")
.build()
.getService()
));
closeable = ObjectifyService.begin();
// Set up some fake HTTP requests
when(mockRequest.getRequestURI()).thenReturn(MOCK_URL);
JSONObject grocery = new JSONObject();
grocery.put("name", "Beer");
Reader inputString = new StringReader(grocery.toString());
BufferedReader reader = new BufferedReader(inputString);
when(mockRequest.getReader()).thenReturn(reader);
// Set up a fake HTTP response.
responseWriter = new StringWriter();
when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
servletUnderTest = new GroceryServlet();
servletUnderTest.init();
}
#After public void tearDown() throws Exception {
closeable.close();
helper.tearDown();
}
#Test
public void doGetWritesResponse() throws Exception {
servletUnderTest.doGet(mockRequest, mockResponse);
// We expect our hello world response.
assertThat(responseWriter.toString())
.contains("Hello Kitty");
}
#Test
public void doPostWritesResponse() throws Exception {
JSONObject reqObj = new JSONObject();
reqObj.put("name", "Beer");
reqObj.put("quantity", 5);
StringReader reader = new StringReader(reqObj.toString());
when(mockRequest.getReader()).thenReturn(new BufferedReader(new StringReader(reqObj.toString())));
servletUnderTest.doPost(mockRequest, mockResponse);
// We expect our hello world response.
assertThat(responseWriter.toString())
.contains(reqObj.getString("name"));
}
}
The test fails with the following error message
[ERROR] Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time
elapsed: 0.103 s <<< FAILURE! - in
mobi.grocerymonkey.groceryapp.GroceryServletTest [ERROR]
doPostWritesResponse(mobi.grocerymonkey.groceryapp.GroceryServletTest)
Time elapsed: 0.078 s <<< ERROR! java.lang.IllegalStateException: You
have not started an Objectify context. You are probably missing the
ObjectifyFilter. If you are not running in the context of an http
request, see the ObjectifyService.run() method. at
mobi.grocerymonkey.groceryapp.GroceryServletTest.doPostWritesResponse(GroceryServletTest.java:109)
which is caused by this line ofy().save().entity(grocery).now() in my servlet. When I remove it, the test is run without errors.
I have tried to follow different approaches to resolve this error found here on stackoverflow but without luck.
How should the test/app be setup to be able to develop it using a test driven approach? What I am looking for is a way to be able to write the unit test first and then the actual application. But how to succeed?
(Disclaimer, I haven't worked with Java in over a decade)
UPDATE
ServletContext file
package mobi.grocerymonkey.groceryapp;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.Closeable;
import java.io.IOException;
import com.googlecode.objectify.ObjectifyService;
import static com.googlecode.objectify.ObjectifyService.ofy;
#WebListener
public class GroceryContextListener implements ServletContextListener {
private ServletContext context;
private Closeable closeable;
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
ObjectifyService.init();
this.closeable = ObjectifyService.begin();
ObjectifyService.register(Grocery.class);
System.out.println("Context initialized");
}
public void contextDestroyed(ServletContextEvent event) {
try {
this.closeable.close();
} catch(IOException ioe) {
}
}
}
Unittest file
package mobi.grocerymonkey.groceryapp;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.mock;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.DatastoreOptions;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.json.JSONObject;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.Reader;
import java.io.Closeable;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
/**
* Unit tests for {#link HelloAppEngine}.
*/
#RunWith(JUnit4.class)
public class GroceryServletTest {
private static final String MOCK_URL = "/grocery";
// Set up a helper so that the ApiProxy returns a valid environment for local testing.
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private Closeable closeable;
#Mock
private HttpServletRequest mockRequest;
#Mock
private HttpServletResponse mockResponse;
private ServletContextListener contextListener;
private ServletContext context;
private StringWriter responseWriter;
private GroceryServlet servletUnderTest;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
helper.setUp();
contextListener = new GroceryContextListener();
context = mock(ServletContext.class);
// Set up some fake HTTP requests
when(mockRequest.getRequestURI()).thenReturn(MOCK_URL);
JSONObject grocery = new JSONObject();
grocery.put("name", "Beer");
Reader inputString = new StringReader(grocery.toString());
BufferedReader reader = new BufferedReader(inputString);
when(mockRequest.getReader()).thenReturn(reader);
// when(mockRequest.getServletContext()).thenReturn(context);
// Set up a fake HTTP response.
responseWriter = new StringWriter();
when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter));
servletUnderTest = new GroceryServlet();
}
#After
public void tearDown() throws Exception {
helper.tearDown();
}
#Test
public void doGetWritesResponse() throws Exception {
servletUnderTest.doGet(mockRequest, mockResponse);
// We expect our hello world response.
assertThat(responseWriter.toString())
.contains("Hello Kitty");
}
#Test
public void doPostWritesResponse() throws Exception {
contextListener.contextInitialized(new ServletContextEvent(context));
JSONObject reqObj = new JSONObject();
reqObj.put("name", "Beer");
reqObj.put("quantity", 5);
StringReader reader = new StringReader(reqObj.toString());
when(mockRequest.getReader()).thenReturn(new BufferedReader(new StringReader(reqObj.toString())));
servletUnderTest.doPost(mockRequest, mockResponse);
// We expect our hello world response.
assertThat(responseWriter.toString())
.contains(reqObj.getString("name"));
}
}
Servlet file
package mobi.grocerymonkey.groceryapp;
import com.google.appengine.api.utils.SystemProperty;
import java.io.IOException;
import java.io.BufferedReader;
import java.util.Properties;
import org.json.JSONObject;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import static com.googlecode.objectify.ObjectifyService.ofy;
import com.googlecode.objectify.ObjectifyService;
/* This is the servlet */
#WebServlet(name = "GroceryServlet", value = "/grocery")
public class GroceryServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(GroceryServlet.class.getName());
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain");
response.getWriter().println("Hello Kitty");
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
BufferedReader reader = request.getReader();
String line = null;
StringBuffer stringBuffer = new StringBuffer();
while((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
String jsonString = stringBuffer.toString();
JSONObject json = new JSONObject(jsonString);
log.info("JSON "+ jsonString);
Grocery grocery = new Grocery();
grocery.setName((String) json.get("name"));
grocery.setQuantity((Integer) json.get("quantity"));
ofy().save().entity(grocery).now();
log.info("JSON name "+ grocery.getName());
response.setContentType("application/json");
response.getWriter().println(jsonString);
}
}
Now I am getting a "com.google.cloud.datastore.DatastoreException: Unauthenticated" error when running the test, so looks like I am on the right way. Would I store the datastore credentials in the web.xml and then pass them to the context similar to
ObjectifyService.init(new ObjectifyFactory(
DatastoreOptions.newBuilder()
.setHost("http://localhost:8081")
.setProjectId("enduring-trees-259812")
.build()
.getService()
));
ObjectifyService.factory().register(Grocery.class);
New Update
I upgraded to Junit5 and rewrote the entire test to this
package mobi.grocerymonkey.groceryapp;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.util.Closeable;
import static com.googlecode.objectify.ObjectifyService.factory;
import static com.googlecode.objectify.ObjectifyService.ofy;
import com.googlecode.objectify.Key;
import com.google.cloud.datastore.Datastore;
import com.google.cloud.datastore.DatastoreOptions;
import com.google.cloud.datastore.testing.LocalDatastoreHelper;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import mobi.grocerymonkey.groceryapp.util.TestBase;
import mobi.grocerymonkey.groceryapp.domain.Grocery;
import mobi.grocerymonkey.groceryapp.domain.GroceryList;
public class MyFirstTest extends TestBase {
// Maximum eventual consistency.
private final static LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
.setDefaultHighRepJobPolicyUnappliedJobPercentage(100));
Closeable closeable;
#BeforeAll
public static void setUp() {
helper.setUp();
}
#AfterAll
public static void tearDown() {
helper.tearDown();
}
#BeforeEach
public void setUpEach() {
ObjectifyService.init(new ObjectifyFactory(
DatastoreOptions.getDefaultInstance().getService()));
closeable = ObjectifyService.begin();
}
#AfterEach
public void tearDownEach() {
closeable.close();
}
#DisplayName("Test MyFirstTest.testAddition()")
#Test
public void testAddition() {
assertEquals(1 + 1, 2);
}
#DisplayName("Testing testGroceryList()")
#Test
public void testGroceryList() {
factory().register(GroceryList.class);
GroceryList list = new GroceryList("Weekend Beer List");
Key<GroceryList> k1 = ofy().save().entity(list).now();
assertEquals(1+1, 2);
}
}
It is deliberately kept in a single file for now. But for some reason, the datastore cannot find the emulator that is running when the test is run. I am getting a Datastore Unauthenticated error.
I ran gcloud beta emulators datastore start and $(gcloud beta emulators datastore env-init) before running the unit test.
The problem is that you're calling ObjectifyService.init() twice, but you only called begin() on the first (abandoned) factory.
You call init() in your setUp() method, which initializes the static ObjectifyFactory. You then open a session on that factory with the ObjectifyService.begin() call.
At the end of your setUp() you call servletUnderTest.init(), which also calls ObjectifyService.init(). This replaces the static ObjectifyFactory. When you next execute your servlet and call ofy()..., you're using a factory that has not started a session.
Take a look at the code for ObjectifyService. It's quite literally just a few lines of code to wrap a static ObjectifyFactory instance.
If you have more than one servlet, this code will not work well in production either - you only want to initialize and register your classes once. I recommend doing this with a ServletContextListener.
The core of test-driven development revolves around five steps, which you repeated throughout the software development life cycle.
Test-driven development life-cycle:
Write the test
Run the test (without implementation code, test does not pass)
Write just enough implementation so the test passes
Run all tests (test pass)
Refactor
Repeat
By following this steps you can create a TDD implementation for your application.
There is no specific way for Google Cloud to do beside the steps I have specified above.
As specified in your error, you can see that you have not started an Objectify context, and you are missing the ObjectifyFilter.
Here is a implementation of a list in Java, which follows the TDD, which may be helpful to clear some of your concerns.

Tested class is calling actual object, instead of mocked object

I'm trying to mock an external library, however the actual object created in APKDecompiler is being used, instead of the mock object.
Test code
import com.googlecode.dex2jar.v3.Dex2jar;
import jd.core.Decompiler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import APKDecompiler;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.easymock.PowerMock.*;
import java.io.File;
import java.io.IOException;
#RunWith(PowerMockRunner.class)
#PrepareForTest({Dex2jar.class})
public class TestAPKDecompiler {
//As this only uses external libraries, I will only test that they are called correctly by mocking them.
#Test
public void testAPKDecompiler() {
try {
File testFile = new File("ApkExtractor/src/test/resources/testApp.jar");
String expectedDirectory = testFile.getAbsolutePath().substring(0, testFile.getAbsolutePath().length() - 4);
mockStatic(Dex2jar.class);
Dex2jar mockApkToProcess = createMock(Dex2jar.class);
Decompiler mockDecompiler = createNiceMockAndExpectNew(Decompiler.class);
expect(Dex2jar.from(testFile)).andStubReturn(mockApkToProcess);
mockApkToProcess.to(new File(expectedDirectory + ".jar"));
expectLastCall();
PowerMock.expectNew(Decompiler.class).andReturn(mockDecompiler).anyTimes();
expect(mockDecompiler.decompileToDir(expectedDirectory + ".jar", expectedDirectory)).andReturn(0);
replay(mockApkToProcess);
PowerMock.replay(mockDecompiler);
replayAll();
String actualDirectory = APKDecompiler.decompileAPKToDirectory(testFile);
verify(mockApkToProcess);
verify(mockDecompiler);
verifyAll();
assertEquals(expectedDirectory, actualDirectory);
testFile.delete();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Class code
import com.googlecode.dex2jar.v3.Dex2jar;
import jd.core.Decompiler;
import jd.core.DecompilerException;
import java.io.File;
import java.io.IOException;
public class APKDecompiler {
public static String decompileAPKToDirectory(File filename) throws IOException, DecompilerException {
String filenameWithoutFileExtension = filename.getAbsolutePath().substring(0, filename.getAbsolutePath().length() - 4);
Dex2jar apkToProcess = Dex2jar.from(filename);
File jar = new File(filenameWithoutFileExtension + ".jar");
apkToProcess.to(jar);
Decompiler decompiler = new Decompiler();
decompiler.decompileToDir(filenameWithoutFileExtension + ".jar", filenameWithoutFileExtension);
return filenameWithoutFileExtension;
}
I've tried this and I haven't had any luck. EasyMock: Mocked object is calling actual method
I get a FileNotFoundException when decompiler.decompileToDir is called, which shouldn't happen as I should be mocking the class.
Any help would be greatly appreciated.
The answer was I didn't include the class i was testing in the #PrepareForTest annotation.
#PrepareForTest({APKDecompiler.class, Dex2jar.class, Decompiler.class})

Annotations not firing in SharedDriver with cucumber-jvm

This is driving me nuts. I'm running a test framework using cucumber-jvm and trying to get it to take screenshots.
I have looked at the java-webbit-websockets-selenium example that's provided and have implemented the same method of calling my webdriver using the SharedDriver module.
For some reason, my #Before and #After methods are not being called (I've put print statements in there). Can anyone shed any light?
SharedDriver:
package com.connectors;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.Scenario;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import java.util.concurrent.TimeUnit;
public class SharedDriver extends EventFiringWebDriver {
private static final WebDriver REAL_DRIVER = new FirefoxDriver();
private static final Thread CLOSE_THREAD = new Thread() {
#Override
public void run() {
REAL_DRIVER.close();
}
};
static {
Runtime.getRuntime().addShutdownHook(CLOSE_THREAD);
}
public SharedDriver() {
super(REAL_DRIVER);
REAL_DRIVER.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
REAL_DRIVER.manage().window().setSize(new Dimension(1200,800));
System.err.println("DRIVER");
}
#Override
public void close() {
if(Thread.currentThread() != CLOSE_THREAD) {
throw new UnsupportedOperationException("You shouldn't close this WebDriver. It's shared and will close when the JVM exits.");
}
super.close();
}
#Before()
public void deleteAllCookies() {
manage().deleteAllCookies();
System.err.println("BEFORE");
}
#After
public void embedScreenshot(Scenario scenario) {
System.err.println("AFTER");
try {
byte[] screenshot = getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (WebDriverException somePlatformsDontSupportScreenshots) {
System.err.println(somePlatformsDontSupportScreenshots.getMessage());
}
}
}
Step file:
package com.tests;
import com.connectors.BrowserDriverHelper;
import com.connectors.SharedDriver;
import com.connectors.FunctionLibrary;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.runtime.PendingException;
import org.openqa.selenium.*;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.support.events.EventFiringWebDriver;
/**
* Created with IntelliJ IDEA.
* User: stuartalexander
* Date: 23/11/12
* Time: 15:18
* To change this template use File | Settings | File Templates.
*/
public class addComponentsST {
String reportName;
String baseUrl = BrowserDriverHelper.getBaseUrl();
private final WebDriver driver;
public addComponentsST(SharedDriver driver){
this.driver = driver;
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
#Given("^I have navigated to the \"([^\"]*)\" of a \"([^\"]*)\"$")
public void I_have_navigated_to_the_of_a(String arg1, String arg2) throws Throwable {
// Express the Regexp above with the code you wish you had
assertEquals(1,2);
throw new PendingException();
}
CukeRunner:
package com.tests;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#Cucumber.Options(tags = {"#wip"}, format = { "pretty","html:target/cucumber","json:c:/program files (x86)/jenkins/jobs/cucumber tests/workspace/target/cucumber.json" }, features = "src/resources/com/features")
public class RunCukesIT {
}
Put SharedDriver in the same package as RunCukesIT, i.e. com.tests.
When using the JUnit runner, the glue becomes the unit test package (here com.tests), and this is where cucumber-jvm will “scan” the classes for annotations.

Categories

Resources