How write the Mockito Junit Test Cases for JDBC Template in Spring Boot Application? - mockito

public List<User> getAllUsers() {
String sql = "select * from user_data";
List<User> users = jdbcTemplate.query(sql, new UserRowMapper());
return users;
}
public User getAUser(int userId) {
String sql = "select * from user_data where userid=?";
User user = jdbcTemplate.queryForObject(sql, new Object[] { userId }, new UserRowMapper());
return user;
}
public User addUser(User user) {
String SQL = "INSERT INTO user_data(user_first_name,user_last_name,mobile_no,about) VALUES (?,?,?,?)";
jdbcTemplate.update(SQL, user.getFirstName(), user.getLastName(), user.getMobileNumber(), user.getAbout());
return user;
}
This is my Code. Can anyone please help me how to write Junit Mockito Test cases for that.

For SQL request's testing, you cannot write unit tests. You have to write integration tests.
Two possible strategies :
You can test with an in-memory database with tools like DbUnit (it's an old tool, I think you can find better nowadays)
You can use an integration database. In a test, you execute your code, then you read the database to verify and finally you clean your database (you can use a transaction with rollback to clean automatically your operations).
Don't hesite to ask for advice when you advance in these ways.

Related

Use Multiple DataSource(With CosmosDB) In Spring boot JPA

I'm setting up kind of API with Spring boot, jpa.
At First, I made one CosmosDB and put all things together.
However, now I want to use multiple database one for user with MySQL & one for merchandise with CosmosDB.
How can I make proper config?
In formal case If I want to use multiple datasource in Spring boot with JPA
(For Example, Use MySQL For UserInfo & Use h2 for merchandise data
or
Use MySQL For UserInfo & Use PostgreSQL for merchandise data
or)
I set the properties & just make two Kinds of Config like this
And It works fine.
#configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = {"====.repository"})
public class CustomerDataSourceConfig {
#primary
#bean(name = "dataSource")
#ConfigurationProperties(prefix = "====.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
#primary
#bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, #qualifier("dataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("=====.domain")
.persistenceUnit("customer")
.build();
}
#primary
#bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
#qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
But If I want to use Multiple DataSource(With CosmosDB) this kind of work doesn't work anymore.
I should make different kind of config for CosmosDB?
or
Is there any way I can use multiple datasource with CosmosDB?
(ex. Use MySQL For UserInfo & Use CosmosDB for merchandise data)
thx.
I solved this problem.
below is my github issue.
so someone want to know the answer.
plz check it.
https://github.com/microsoft/spring-data-cosmosdb/issues/403

Insert data into cassandra using datastax driver

We are trying to insert data from CSV file into Cassandra using the DataStax driver for Java. What are the available methods to do so?
We are currently using running cqlsh to load from a CSV file.
The question is quite vague. Usually, you should be able to provide code, and give an example of something that isn't working quite right for you.
That being said, I just taught a class (this week) on this subject for our developers at work. So I can give you some quick examples.
First of all, you should have a separate class built to handle your Cassandra connection objects. I usually build it with a couple of constructors so that it can be called in a couple different ways. But each essentially calls a connect method, which looks something like this:
public void connect(String[] nodes, String user, String pwd, String dc) {
QueryOptions qo = new QueryOptions();
qo.setConsistencyLevel(ConsistencyLevel.LOCAL_ONE);
cluster = Cluster.builder()
.addContactPoints(nodes)
.withCredentials(user,pwd)
.withQueryOptions(qo)
.withLoadBalancingPolicy(
new TokenAwarePolicy(
DCAwareRoundRobinPolicy.builder()
.withLocalDc(dc)
.build()
)
)
.build();
session = cluster.connect();
With that in place, I also write a few simple methods to expose some functionality of the of the session object:
public ResultSet query(String strCQL) {
return session.execute(strCQL);
}
public PreparedStatement prepare(String strCQL) {
return session.prepare(strCQL);
}
public ResultSet query(BoundStatement bStatement) {
return session.execute(bStatement);
}
With those in-place, I can then call these methods from within a service layer. A simple INSERT (with preparing a statement and binding values to it) looks like this:
String[] nodes = {"10.6.8.2","10.6.6.4"};
CassandraConnection conn = new CassandraConnection(nodes, "aploetz", "flynnLives", "West-DC");
String userID = "Aaron";
String value = "whatever";
String strINSERT = "INSERT INTO stackoverflow.timestamptest "
+ "(userid, activetime, value) "
+ "VALUES (?,dateof(now()),?)";
PreparedStatement pIStatement = conn.prepare(strINSERT);
BoundStatement bIStatement = new BoundStatement(pIStatement);
bIStatement.bind(userID, value);
conn.query(bIStatement);
In addition, the DataStax Java Driver has a folder called "examples" in their Git repo. Here's a link to the "basic" examples, which I recommend reading further.

SQLInjection against CosmosDB in an Azure function

I have implemented an Azure function that is triggered by a HttpRequest. A parameter called name is passed as part of the HttpRequest. In Integration section, I have used the following query to retrieve data from CosmosDB (as an input):
SELECT * FROM c.my_collection pm
WHERE
Contains(pm.first_name,{name})
As you see I am sending the 'name' without sanitizing it. Is there any SQLInjection concern here?
I searched and noticed that parameterization is available but that is not something I can do anything about here.
When the binding occurs (the data from the HTTP Trigger gets sent to the Cosmos DB Input bind), it is passed through a SQLParameterCollection that will handle sanitization.
Please view this article:
Parameterized SQL provides robust handling and escaping of user input, preventing accidental exposure of data through “SQL injection”
This will cover any attempt to inject SQL through the name property.
If you're using Microsoft.Azure.Cosmos instead of Microsoft.Azure.Documents:
public class MyContainerDbService : IMyContainerDbService
{
private Container _container;
public MyContainerDbService(CosmosClient dbClient)
{
this._container = dbClient.GetContainer("MyDatabaseId", "MyContainerId");
}
public async Task<IEnumerable<MyEntry>> GetMyEntriesAsync(string queryString, Dictionary<string, object> parameters)
{
if ((parameters?.Count ?? 0) < 1)
{
throw new ArgumentException("Parameters are required to prevent SQL injection.");
}
var queryDef = new QueryDefinition(queryString);
foreach(var parm in parameters)
{
queryDef.WithParameter(parm.Key, parm.Value);
}
var query = this._container.GetItemQueryIterator<MyEntry>(queryDef);
List<MyEntry> results = new List<MyEntry>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
}

Get current user language using javascript

In CRM 2011 it's easy to get current user language using javascript, using the following code:
Xrm.Page.context.getUserLcid();
Is there anyway to do the same in server side using plugins ?
Thanks and best regards
Here is a sample in a Plugin:
class GetUserLanguage : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
//PluginSetup abstracts setup code: http://nicknow.net/dynamics-crm-2011-abstracting-plugin-setup/
var p = new PluginSetup(serviceProvider);
var user = p.Context.InitiatingUserId;
var lcid = RetrieveUserUiLanguageCode(p.Service, user);
}
//From the SDK: http://msdn.microsoft.com/en-us/library/hh670609.aspx
private static int RetrieveUserUiLanguageCode(IOrganizationService service, Guid userId)
{
var userSettingsQuery = new QueryExpression("usersettings");
userSettingsQuery.ColumnSet.AddColumns("uilanguageid", "systemuserid");
userSettingsQuery.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, userId);
var userSettings = service.RetrieveMultiple(userSettingsQuery);
if (userSettings.Entities.Count > 0)
{
return (int)userSettings.Entities[0]["uilanguageid"];
}
return 0;
}
}
There are a couple options for it that I've used before.
Use a Retrieve on the systemuser entity using the userid from the plugin execution context. Don't forget to set the column set to just get the user! Otherwise systemuser can be a hefty retrieve for online envs.
Issue a WhoAmI request to the server.
I personally use the former because Retrieves are very common for devs who use plugins, but not all are familiar with the WhoAmI message (it derives from retrieve: http://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.whoamirequest.aspx)
Unfortunately I have not found a way to get it without issuing a request to the server. Let me know if this helps!
Nick
I think that once the user selects a preferred locale you can pick it up using:
Thread.CurrentUICulture.LCID

Why no SQL for NHibernate 3 Query?

Why is no SQL being generated when I run my Nhibernate 3 query?
public IQueryable<Chapter> FindAllChapters()
{
using (ISession session = NHibernateHelper.OpenSession())
{
var chapters = session.QueryOver<Chapter>().List();
return chapters.AsQueryable();
}
}
If I run the query below I can see that the SQL that gets created.
public IQueryable<Chapter> FindAllChapters()
{
using (ISession session = NHibernateHelper.OpenSession())
{
var resultDTOs = session.CreateSQLQuery("SELECT Title FROM Chapter")
.AddScalar("Title", NHibernateUtil.String)
.List();
// Convert resultDTOs into IQueryable<Chapter>
}
}
Linq to NHibernate (like Linq to entities) uses delayed execution. You are returning IQueryable<Chapter> which means that you might add further filtering before using the data, so no query is executed.
If you called .ToList() or .List() (i forget which is in the API), then it would actually produce data and execute the query.
In other words, right now you have an unexecuted query.
Added: Also use Query() not QueryOver(). QueryOver is like detached criteria.
For more info, google "delayed execution linq" for articles like this

Resources