Test play controller with session data - junit

I have a simple controller test.
route(fakeRequest(routes.Accounts.accounts()).session("sessionref","fakeSession"));
Secured Autheticator looks like this:
public class Secured extends play.mvc.Security.Authenticator {
#Inject
AuthServices authService;
public String getUsername(Http.Context context) {
return authService.checkSession(context);
}
#Override
public Result onUnauthorized(Http.Context context) {
return ok(index.render(formFactory.form(forms.LoginForm.class)));
}
}
How can i mock authService?
I tried to mock with guice bind but this method don't work
#Before
public void setup() {
startPlay();
MockitoAnnotations.initMocks(this);
Module testModule = new AbstractModule() {
#Override
public void configure() {
bind(AuthServices.class)
.toInstance(authServices);
}
};
GuiceApplicationBuilder builder = new GuiceApplicationLoader()
.builder(new play.ApplicationLoader.Context(Environment.simple()))
.in(Mode.TEST)
.overrides(testModule);
Guice.createInjector(builder.applicationModule()).injectMembers(this);
}

You can read this for testing Play controllers and follow this example for testing with Guice.
For your case it is something like this:
public class MyTest extends WithApplication {
#Mock
AuthServices mockAuthService;
#Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.overrides(bind(CacheProvider.class).toInstance(mockAuthService))
.in(Mode.TEST)
.build();
}
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testAccounts() {
running(provideApplication(), () -> {
RequestBuilder testRequest = Helpers.fakeRequest(controllers.routes.Accounts.accounts()).session("sessionref","fakeSession");
Result result = route(testRequest);
//assert here the expected result
});
}
}

Related

How to mock a void method with no arguments?

For Example:
Class A{
string s = null;
public void method(){
s="Sample String";
}
}
I have a void method with similar scenario. How can I test such void method?
With void methods you should test the interaction with its dependent objects within the void method. I think a void method with no argument is rarely useful to test (but if you have a valid use case, please add it to your question). I provided you a simple example for a method with an argument but void as a return type:
public class A {
private DatabaseService db;
private PaymentService payment;
// constructor
public void doFoo() {
if(n < 2) {
db.updateDatabase();
} else {
payment.payBill();
}
}
}
And the unit test for this can look like the following
#RunWith(MockitoJUnitRunner.class)
public class ATest {
#Mock
DatabaseService db;
#Mock
PaymentService payment;
#Test
public void testDoFooWithNGreaterTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(3);
verify(payment).payBill(); // verify that payment was called
}
#Test
public void testDoFooWithNLessThanTwo() {
A cut = new A(db, payment); // cut -> class under test
cut.doFoo(1);
verify(db).updateDatabase(); // verify that db was called
}
}

I need to write JUNIT for Apache camel route

I have camel route as below
public class IncomingBatchFileRoute extends RouteBuilder {
#Value(CCS_PROCESSING_INCOMING_DIRECTORY)
private String source;
#Override
public void configure() throws Exception {
from(sourceLocation)).autoStartup(false).to("encryptionEndPoint");
}
}
I need to write a JUNIT For above camel route and am new to it and created a structure as below
public class IncomingBatchFileRouteTest extends CamelTestSupport{
#Override
public RoutesBuilder createRouteBuilder() throws Exception {
return new IncomingBatchFileRoute();
}
#Test
public void sampleMockTest() {
}
}
Not sure how to complete it. Request you to help me on this
You need to mock your encryptionEndPoint and start your route with a producerTemplate
#Produce(uri = CCS_PROCESSING_INCOMING_DIRECTORY)
protected ProducerTemplate template;
#EndpointInject(uri = "encryptionEndPoint")
protected MockEndpoint resultEndpoint;
#Test
public void sampleMockTest() {
// GIVEN
this.resultEndpoint.expectedMessageCount(1);
// WHEN
this.template.sendBody("Hey");
// THEN
this.resultEndpoint.assertIsSatisfied();
}

RecyclerView with Retrofit2

I try to do recyclerView with retrofit2, but I do in my code: recyclerView Adapter Constructor and I get a error in my MainActivity part of this line -
"(flowersList, this)": I get error: List anonymous retrofit2.Callback
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
my code my MainActivity is:
try {
APIService service = ApiClient.getRetrofit().create(APIService.class);
retrofit2.Call<List<Flower>> call = service.getFlowerData();
call.enqueue(new Callback<List<Flower>>() {
#Override
public void onResponse(retrofit2.Call<List<Flower>> call, Response<List<Flower>> response) {
List<Flower> flowersList = response.body();
mLinearLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
mRecyclerView.setAdapter(recyclerViewAdapter);
}
and the code in RecyclerViewFlowersAdapter is:
public class RecyclerViewFlowersAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
private List<Flower> mFlowers;
private Context mContext;
public RecyclerViewFlowersAdapter(List<Flower> flowers, Context context) {
mContext = context;
mFlowers = flowers;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.flower_item_card, null);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.mTextViewTitle.setText(mFlowers.get(position).getName());
Picasso.with(mContext)
.load(mFlowers.get(position).getPhoto()).into(holder.mImageViewFlower);
}
#Override
public int getItemCount() {
return mFlowers.size();
}
}
and my code in RecyclerViewHolder is:
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextViewTitle;
public ImageView mImageViewFlower;
public RecyclerViewHolder(View itemView){
super(itemView);
itemView.setOnClickListener(this);
mTextViewTitle = itemView.findViewById(R.id.title);
mImageViewFlower = itemView.findViewById(R.id.imageViewFlower);
}
#Override
public void onClick(View v) {
}
}
I try to do alot of thing but is still error.
thanks for help :)
You are probably using a wrong context, try using MainActivity.this instead of this. Change this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, this);
to this
RecyclerViewFlowersAdapter recyclerViewAdapter = new RecyclerViewFlowersAdapter(flowersList, MainActivity.this);

Configure 2 different MessageConverters for 2 Controllers

I would like to configure two different HttpMessageConverters having the same MediaType for two separate controllers. The reason is that there are some external services that uses different JSON formats. We are not able to change them.
Is it possible? Can I create two WebMvcConfigurerAdapters and split the traffic somehow? If possible, is it a good practice?
Finally, I solved the problem by overriding MessageConverter adding possiblity to configure its jaxbcontext and assign supported packages. So, then I can create 2 different MesssageConverters for the same controller and depending on a return class use one or another.
public class MoxyMessageConverter extends AbstractHttpMessageConverter<Object> {
private final JAXBContext jAXBContext;
private String[] supportedPackages = { ... }; // some defaults
public MoxyMessageConverter(JAXBContext jAXBContext) {
this.jAXBContext = jAXBContext;
}
public String[] getSupportedPackages() {
return supportedPackages;
}
public void setSupportedPackages(String[] supportedPackages) {
this.supportedPackages = supportedPackages;
}
#Override
protected boolean supports(Class<?> clazz) {
String packageName = clazz.getPackage().getName();
for (String supportedPackage : supportedPackages) {
if (packageName.startsWith(supportedPackage))
return true;
}
return false;
}
#Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
..
}
#Override
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
..
}
}
and in the #Configuration class:
#Configuration
#EnableWebMvc
#EnableTransactionManagement
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
super.extendMessageConverters(converters);
MoxyMessageConverter defaultMessageConverter = new MoxyMessageConverter(defaultJAXBContext);
defaultMessageConverter.setSupportedPackages(new String[] { "xxx.xxx.xxx.webservices" });
converters.add(0, defaultMessageConverter );
MoxyMessageConverter payUMessageConverter = new MoxyMessageConverter(payUJAXBContext);
payUMessageConverter.setSupportedPackages(new String[] { "xxx.xxx.xxx.webservices.payu" });
converters.add(0, payUMessageConverter);
}
}

How to add insert query in spring mvc + hibernate project

My hibernate configuration class include following code
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
My package structures like this enter code here
My daoImpl class like this.
#Repository("passArrayDao")
public class PassArrayDaoImpl extends AbstractDao<Integer, Arr> implements PassArrayDao {
#Override
public void passarray(Arr arr) {
}
}
normally we user hibernate for insert update delete data no.
#Override
public Book findBookById(int id) {
return bookDao.findBookById(id);
}
#Override
public List<Book> getAllBooks() {
return bookDao.getAllBooks();
}
#Override
public List<Book> findBooksByTitle(String title) {
return bookDao.findBooksByTitle(title);
}
#Override
public void deleteBookById(int id) {
bookDao.deleteBookById(id);
}
#Override
public void updateBook(Book book) {
bookDao.updateBook(book);
}
bus now i want write insert query into daoImpl class. How I create it.