JUnit Testing with Google App Engine dev server - google-app-engine

I'm new to GAE and trying to setup a few JUnit tests. In this example provided by Google:
public class LocalDatastoreTest {
private final LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
#Before
public void setUp() {
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
// run this test twice to prove we're not leaking any state across tests
private void doTest() {
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
assertEquals(0, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
ds.put(new Entity("yam"));
ds.put(new Entity("yam"));
assertEquals(2, ds.prepare(new Query("yam")).countEntities(withLimit(10)));
}
#Test
public void testInsert1() {
doTest();
}
#Test
public void testInsert2() {
doTest();
}
}
the following line is used to add an Entity to the local datastore:
ds.put(new Entity("yam"));
That works just fine for me. However, I'm using JDO and want to persist one my own POJOs (e.g. Cars) but Cars is not of type Entity, which is what this method requires. Is there a different method or service I can use to accomplish this?

maybe you could use objectify-appengine.. for example
package com.intranet.entity;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
#Entity
public class Voto {
#Id Long id;
#Index String email;
#Index String actividad;
public Voto(){}
public Voto(String email, String actividad) {
this.email = email;
this.actividad = actividad;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getActividad() {
return actividad;
}
public void setActividad(String actividad) {
this.actividad = actividad;
}
}
TEST
public class VotoTest {
private final static LocalServiceTestHelper helper = new LocalServiceTestHelper(
new LocalDatastoreServiceTestConfig());
#Before
public void setUp() {
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
#Test
public void testEmbedded(){
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Voto voto1 = new Voto("test#localhost","actividad1");
ofy().save().entity(voto1).now();
assertEquals(1, ds.prepare(new Query("Voto")).countEntities(withLimit(10)));
}
}
It works perfectly

Related

sometimes my database does not update with the same code

my code in android studio and JAVA language has a problem with its database. I have a edittext in a fragment and I use it for update database. the database is initialized using Room library in activity and the DAO file is defined public and static in mainActivity, and use method DAO.update(photo) in a fragment, but sometimes when type in edittext it updates the field in database but sometimes not, I do not know why? can you please help me on it and do you have same experience?
related code in activity:
public class MainActivity extends AppCompatActivity {
public AppDB appDB;
public static AlbumDAO albumDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appDB= Room.databaseBuilder(this, AppDB.class, "db_App")
.allowMainThreadQueries()
.build();
albumDAO= appDB.getAlbumDAO();
and then I used the database initialized in main activity in this fragment:
public class PhotoFragment extends Fragment {
private Album album;
EditText title;
String inputTitle;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.album=getArguments().getParcelable("key");
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return LayoutInflater.from(getContext()).inflate(R.layout.fragment_photo,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
title=view.findViewById(R.id.txt_postTitle);
title.setText(album.getTitle());
title.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
inputTitle=charSequence.toString();
}
#Override
public void afterTextChanged(Editable editable) {
album.setTitle(inputTitle);
albumDAO.updateAlbum(album);
}
});
}
and the albumDAO is:
#Dao
public interface AlbumDAO {
#Insert
long addAlbum(Album album);
#Query("SELECT * FROM tbl_album")
List<Album> getAllAlbums();
#Update
void updateAlbum(Album album);
#Delete
void deleteAlbum(Album album);
#Query("DELETE FROM tbl_album")
void deleteAllAlbum();
}
and the Album class is:
#Entity(tableName = "tbl_album")
public class Album implements Parcelable {
#PrimaryKey (autoGenerate = true)
private int id;
private String title;
public Album() {
}
protected Album(Parcel in) {
title = in.readString();
}
public static final Creator<Album> CREATOR = new Creator<Album>() {
#Override
public Album createFromParcel(Parcel in) {
return new Album(in);
}
#Override
public Album[] newArray(int size) {
return new Album[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
In the overidden afterTextChanged method. You are updating the database and then changing the title in the album, so the database will not reflect the changed title.
Try using :-
#Override
public void afterTextChanged(Editable editable) {
album.setTitle(inputTitle); //<<<<< MOVED UP
albumDAO.updateAlbum(album);
}
You can also utilise the value (int) returned by the #Update annotated function, to see if anything has been updated by changing it to:-
#Update
int updateAlbum(Album album)
Then you could use something along the lines of:-
#Override
public void afterTextChanged(Editable editable) {
album.setTitle(inputTitle);
if (album.setTitle(inputTitle)> 0) {
.... do whatever here to indicate update was OK
} else {
.... do whatever here to indicate not updated
}
}

Data not inserting into the Database room Android

I'm new to android and this is the first time I'm using room in my application. Either insert operation is not performed or the database is not created or any other error.
I don't know what I'm doing wrong so I need your help.
This program is running but No result is displayed. Nothing is showing on the screen.
Here is my code-
please let me know what is wrong in this code and what I should do to correct it.
Car_details.java
#PrimaryKey
#NonNull
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("desc")
#Expose
private String desc;
#SerializedName("image")
#Expose
private String image;
CarDao.java-
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Car_Details car_details);
#Query("Select * from car_table")
LiveData<List<Car_Details>> selectAll();
CarListDatabase.java
private static CarListDatabase instance;
public abstract CarDao carDao();
public static synchronized CarListDatabase getInstance(Context context){
if(instance==null)
{
instance= Room.databaseBuilder(context.getApplicationContext(),
CarListDatabase.class,"Car_database").fallbackToDestructiveMigration()
.build();
}
return instance;
}
CarRepository.java
public void getCarList(){
CarlistInterface carlistInterface= retrofit.create(CarlistInterface.class);
Call<List<Car_Details>> carList= carlistInterface.carList();
carList.enqueue(new Callback<List<Car_Details>>() {
#Override
public void onResponse(Call<List<Car_Details>> call, final Response<List<Car_Details>> response) {
if(response.body() != null){
List<Car_Details> car_details = response.body();
for (int i = 0; i < car_details.size(); i++) {
String id=car_details.get(i).getId();
String names = car_details.get(i).getName();
String desc=car_details.get(i).getDesc();
String image= car_details.get(i).getImage();
Car_Details car = new Car_Details();
car .setId(id);
car .setName(names);
car .setDesc(desc);
car .setImage(image);
new InsertNoteAsyncTask(carDao).execute(car);
}
}
}
});
}
public LiveData<List<Car_Details>> getCarLists(){
return allCarList;
}
private static class InsertNoteAsyncTask extends AsyncTask<Car_Details,Void,Void> {
private CarDao carDao;
private InsertNoteAsyncTask(CarDao carDao){
this.carDao= carDao;
}
#Override
protected Void doInBackground(Car_Details... car_details) {
carDao.insert(car_details[0]);
return null;
}
CarViewModel.java
public CarViewModel(#NonNull Application application) {
super(application);
repository= new CarRepository(application);
carList= repository.getCarLists();
}
public LiveData<List<Car_Details>> getListLiveData() {
return carList;
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
repository = new CarRepository(this);
carViewModel = ViewModelProviders.of(this).get(CarViewModel.class);
recyclerView= findViewById(R.id.cars_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List = new ArrayList<>();
recyclerAdapter = new RecyclerAdapter(List);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter = new RecyclerAdapter(List);
recyclerView.setAdapter(recyclerAdapter);
carViewModel.getListLiveData().observe(this, new
Observer<java.util.List<Car_Details>>() {
#Override
public void onChanged(java.util.List<Car_Details> car_details) {
recyclerAdapter.setUserList(List);
}
});
repository.getCarList();
}
RecyclerAdapter.java
public class RecyclerAdapter extends RecyclerView.Adapter {
List<Car_Details> carList= new ArrayList<>();
public RecyclerAdapter(List<Car_Details> carList) {
this.carList = carList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater= LayoutInflater.from(parent.getContext());
View view= layoutInflater.inflate(R.layout.row_item,parent,false);
return new RecyclerAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.car_name.setText(carList.get(position).getName());
holder.car_desc.setText(carList.get(position).getDesc());
}
public void setUserList(List<Car_Details> userList) {
this.carList = userList;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return carList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView car_name,car_desc;
public ViewHolder(#NonNull View itemView) {
super(itemView);
car_name= itemView.findViewById(R.id.car_name);
car_desc= itemView.findViewById(R.id.car_desc);
}
}
}
#Override
public int getItemCount() {
return carList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView car_name,car_desc;
public ViewHolder(#NonNull View itemView) {
super(itemView);
car_name= itemView.findViewById(R.id.car_name);
car_desc= itemView.findViewById(R.id.car_desc);
}
}
}
There is nothing wrong with your insert operation with room.
The way you have used live date in your application seems wrong that's why your program is running but no result is coming.
You have to check the part where you are using live data.
Hope this help you out.

testng how to dynamically set groups from Factory?

Before I setup a test class like the code below:
1. the Factory and test Dataprovider both used excel as the dataprovider.
2. In the Factory dataprovider table, it has a list of url
3. Each time, it will find one of the url in the factory dataprovider table, and run the test in each test methods..
public class Test {
WebDriver driver;
private String hostName;
private String url;
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url) {
this.hostName = hostName;
this.url = url;
}
#BeforeMethod
#Parameters("browser")
public void start(String browser) throws Exception {
driver = new FirefoxDriver();
driver.get(url);
Thread.sleep(1000);
}
#Test(priority = 10, dataProvider = "dataprovider Test A", dataProviderClass = xxx.class)
public void TestA(Variable1,
Variable2,Variable3) throws Exception {
some test here...
}
#Test(priority = 20, dataProvider = "dataprovider Test B", dataProviderClass = xxx.class)
public void TestB(Variable1,
Variable2,Variable3)
throws Exception {
some test here...
}
#AfterMethod
public void tearDown() {
driver.quit();
}
Now I want to dynamically assign different group for each test for different url. I am thinking add a variable 'flag' in the #Factory dataprovider:
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url, String flag) {
this.hostName = hostName;
this.url = url;
this.flag = flag;
}
That when flag.equals("A"), it will only run test cases in test groups={"A"}.
When flag.equals("B"), it will only run test cases in test groups ={"B"},
When flag.equals("A,B"), it will only run test cases in test groups ={"A","B"}
Is there any way I can do that?
Thank you!
TestNG groups provides "flexibility in how you partition your tests" but it isn't for conditional test sets. For that you simply use plain old Java.
You can use inheritance or composition (I recommend the latter, see Item 16: Favor composition over inheritance from Effective Java).
Either way the general idea is the same: use a Factory to create your test class instances dynamically creating the appropriate class type with the appropriate test annotations and/or methods that you want to run.
Examples:
Inheritance
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
/**
* Base test class with code for both A-tests and B-tests.
*
* Note that none of these test methods are annotated as tests so that
* subclasses may pick which ones to annotate.
*/
public static abstract class BaseTest {
protected void testA() {
// test something specific to flavor A
}
protected void testB() {
// test something specific to flavor B
}
}
// extend base but only annotate A-tests
public static class FlavorATest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
}
// extend base but only annotate B-tests
public static class FlavorBTest extends BaseTest {
#Test
#Override
public void testB() {
super.testB();
}
}
// extend base and annotate both A-tests and B-tests
public static class FlavorABTest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
#Test
#Override
public void testB() {
super.testB();
}
}
}
Composition
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
private static void testA() {
// test something specific to flavor A
}
private static void testB() {
// test something specific to flavor B
}
// only create A-test methods and delegate to shared code above
public static class FlavorATest {
#Test
public void testA() {
DemoTest.testA();
}
}
// only create B-test methods and delegate to shared code above
public static class FlavorBTest {
#Test
public void testB() {
DemoTest.testB();
}
}
// create A-test and B-test methods and delegate to shared code above
public static class FlavorABTest {
#Test
public void testA() {
DemoTest.testA();
}
#Test
public void testB() {
DemoTest.testB();
}
}
}
Your factory methods won't be as simple as you'll need to use your "flag" from your test data to switch off of and create instances of the appropriate test classes.

Getting AssertionError while using ObjectifyService.register

I am in the middle of trying to refactor some of my data models, but I've run into a problem that I don't understand.
Originally I had a simple data model comprised of 3 entity classes, which looked something like this:
#Entity
public final class Teacher {
#Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
#Entity
public final class Student {
#Id
private String username;
#Load
#Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
#Entity
public final class School {
#Id
private String name;
#Load
private Set<Ref<Teacher>> teachers;
#Load
private Set<Ref<Student>> students;
public School() {}
public School(String name) {
this.name = name;
}
//getters & setters
}
And this all worked fine.
But we decided that it would be more useful for us to embed the entities directly instead of Refs...
#Entity
#Embed
public final class Teacher {
#Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
#Entity
#Embed
public final class Student {
#Id
private String username;
#Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
#Entity
public final class School {
#Id
private String name;
private Set<Teacher> teachers;
private Set<Student> students;
public School() {}
public School(String name) {
this.name = name;
}
//getters & setters
}
After making those changes, then all of our junit tests started to fail with an AssertionError during registration of the School class in our test setup methods which look like:
#Before
public void setUp() throws Exception {
helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
ObjectifyService.register(Teacher.class);
ObjectifyService.register(Student.class);
ObjectifyService.register(School.class);
// more setup
}
The AssertionError doesn't appear until the line that registers the School class, and according to the stack trace is being thrown from the method "com.googlecode.objectify.impl.translate.CreateContext.enterCollection" but I'm not certain how to go about fixing it.
Does anyone have any ideas?
I suspect the error you are getting is to do with the fact that you are trying to register a class which you have annotated with #Embed.
The objectify documentation clearly states that #Embed classes do not have to be registered - maybe this is the cause of the issue.
Also, I'm not 100% sure on this but I don't think you need #Id on an embedded class.
I would suggest you give the following changes a go:
#Embed
public final class Teacher {
#Id
private Long id;
private String primarySubject;
public Teacher() {}
public Teacher(String primarySubject) {
this.primarySubject = primarySubject;
}
//getters & setters
}
#Embed
public final class Student {
#Id
private String username;
#Index
private Ref<Teacher> homeRoomTeacher;
public Student() {}
public Student(String username, Teacher teacher) {
this.username = username;
homeRoomTeacher = Ref.create(teacher);
}
//getters & setters
}
#Before
public void setUp() throws Exception
{
helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
helper.setUp();
ObjectifyService.register(School.class);
// more setup
}
Hope this helps!

Save gwt entities to google application engine datastore with jdo, using rpc

Hello iam new to GWT framework. I want to persist my domain objects/entities to google application engine datastore using rpc. A simple implementation to test if i can make multiple rpc calls ( greetServer() , saveStudent() )
Student
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.gwt.user.client.rpc.IsSerializable;
#PersistenceCapable
public class Student implements IsSerializable {
private static final long serialVersionUID = 1L;
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
#Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
private int studentId;
#Persistent private String firstName;
#Persistent private String lastName;
public Student(){}
public Student(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public int getStudentId() {
return studentId;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
}
GreetingService (default code generated by Eclipse IDE)
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
String greetServer(String name) throws IllegalArgumentException;
**String saveStudent(Student s) throws IllegalArgumentException;**
}
GreetingServiceAsync
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GreetingServiceAsync {
void greetServer(String input, AsyncCallback<String> callback)
throws IllegalArgumentException;
**void saveStudent(Student s, AsyncCallback<String> callback)
throws IllegalArgumentException;**
}
GreetingServiceImpl
import javax.jdo.PersistenceManager;
import com.d.client.GreetingService;
import com.d.client.Student;
import com.d.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
#SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
GreetingService {
public String greetServer(String input) throws IllegalArgumentException
...
String serverInfo = getServletContext().getServerInfo();
String userAgent = getThreadLocalRequest().getHeader("User-Agent");
...
}
#Override
public String saveStudent(Student s) throws IllegalArgumentException {
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(s);
return "student save - ok";
}
}
PMF
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
private PMF() {
}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
EntryPoint
...
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
greetingService.greetServer("greet",
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
}
public void onSuccess(String result) {
//Show success message
}
});
greetingService.saveStudent(new Student("kostas","trichas"),
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
}
public void onSuccess(String result) {
//Show success message
}
});
...
Is the above implementation correct? I deployed this sample application to gae and it did not persisted the object student (you can browse the entities at gae datastore viewer)
check it please:
http://gwtgaedatastore.appspot.com
Change your int studentID to Long id to get it working
This works with your original code (ie., Long id):
#Extension (vendorName="jpox", key="key-auto-increment" ,value="true")
Or, change id to String and your orig code works.
I could not get Long PK to work with datanucleus using gae.pk-id.

Resources