What unit test case to be performed for this method - unit-testing

I am new to .Net field and i wrote a method in c# which takes a string as a parameter from the data base and returns a BusinessContact type which consists entityid, contactid, name, alias.
Here is my code
public BusinessContact GetAccountExecutiveForBroker(string brokerUserName)
{
SqlStatement select = new SqlStatement();
select.Sql = #"select cb.* from custom_brokers cb
join rolodex_contacts rc on cb.aecontactid = rc.contactid and cb.lenderdatabaseid = rc.lenderdatabaseid
where cb.brokerusername = #brokerUserName";
select.AddParameter("brokerusername", brokerUserName);
return db.SelectObject(select, MapContact);
}
I am unable to figure out what unit test cases can be performed on this method. Please help me with this.

You can test input parameter brokerUserName.
if it is empty.
if it is null
if it contains sql injection data (like 'a' or 1=1 --;)

Related

Mockito Junit for returning List

I want to write junit for this method returning country List
public List<String> getCountries(String countryCd) {
String sql = "select COUNTRY_NAME from MY_COUNTRY WHERE COUNTRY_CD = :countryCd ";
List<String> countries;
SqlParameterSource parameters = new MapSqlParameterSource().addValue("countryCd", countryCd);
countries = namedParameterJdbcTemplate.query(sql,parameters, (resultSet, rowNum) ->
resultSet.getString("COUNTRY_NAME")));
return countries
}
I tried something like this
Mockito.when(namedParameterJdbcTemplate.queryForObject(queryJobs, parameters, String.class))
MapSqlParameterSource inherits its equals method from Object.
This means that 2 parameter sources are equal only if they reference same instance.
You need to provide an argument matcher to compare this argument and not use equals method. The cleanest way to do it is via Custom Argument Matcher.
Alternatively, you relax the requirements for this argument and use any(MapSqlParameterSource.class) matcher.
try using
Mockito.when(namedParameterJdbcTemplate.queryForObject(any(), any(), any())).thenRetrun(you v

grails - how do you pass non string variables to taglib attrs map using testing with applyTemplate?

grails 3.3.9, + tag libs
I create a new taglib like this
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class JavaDateTimeTagLib {
static defaultEncodeAs = [taglib:'html']
//static encodeAsForTags = [tagName: [taglib:'html'], otherTagName: [taglib:'none']]
static encodeAsForTags = [testCall: [taglib:'none']]
static namespace = "jdt" //java8 date time name space for tags
def testCall = { attrs ->
def p1 = attrs.p1
def p2 = attrs.p2
out << "p1:'$p1' with class ${p1.getClass()}"
out << "p2:'$p2' with class ${p2.getClass()}"
}
}
where i want to pass a non string variable to the attrs map.
i then setup the test like this
class JavaDateTimeTagLibSpec extends Specification implements TagLibUnitTest<JavaDateTimeTagLib> {
def setup() {
}
def cleanup() {
}
/**
* restriction params must be quoted values - esentially strings
* taglib has to take that and do any conversions in the taglib
* output by defaults is encoded html using std codec
*/
void "call displayDateTime tag "() {
given:
String result = applyTemplate('<jdt:testCall p1="p1-string" p2="$now" />' , [now:LocalDateTime.now()])
when :
println "$result "
then:
result
}
}
What i'm trying to do is pass a LocalDateTime variable to the attrs map.
if you use applyTemplate and pass p2=ldt, and test map [ldt:LocalDateTime.now()]
the test fails saying the variable must be 'quoted
[Byte array resource [test_1549319950845]:1] Attribute value must be quoted (p1="p1-string" p2=now).
if you quote the p2 variable using p2="$ldt" and test map the sname as [ldt:LocalDateTime.now()], then the test will work - However the type passed to the attrs map is GStringImpl
however reading the OCI guide oci tag lib guide
it implies on page 4 that you can pass attrs.employees as a list of domainobjects and use that in you markup
but theres no way to invoke this using the testing as everything has to be string quoted - which makes it GStringImpl
how do you pass non string variable to a taglibs attrs map from appyTemplate (.. i presume the same restiction applies in live gsp and not just the testing framework )
hah! its such a small thing
if you change the test and write this
String result = applyTemplate('<jdt:testCall p1="p1-string" p2="${now}" />' , [now:LocalDateTime.now()])
with braces round the variable key name from the map - then the actual value of the typed variable is passed into the taglib. so if you look in the attrs.p2 value it has the actual LocalDateTime instance.
now quite sure how applytemplate is working not sure, but expecting its trying to do soemthing like groovy shell evaluate the string - hence the need to use single '' like '
Hope that makes sense
blimey enough to make your head explode sometimes

SpEL expressions - identify fields declared in an expression?

I have the following code which evaluates a SpEL expression using data values defined in a Map object.
// data map
Map dataMap = new HashMap();
dataMap.put("abc",1);
dataMap.put("def",2);
dataMap.put("xyz",1);
dataMap.put("qwerty",2);
// spel rule expression
String ruleExpression = "#abc+#def";
// Set evaluation context
StandardEvaluationContext stdContext = new StandardEvaluationContext();
stdContext.setVariables(map);
// Evaluate the SpEL expression
ExpressionParser parser = new SpelExpressionParser();
Object returnValue = parser.parseExpression(ruleExpression).getValue(stdContext);
// returnValue = 3 :-)
In the real world our map is populated based in a DB query result set and the 'ruleExpression' is only known at runtime. I have a new requirement to log the values defined in the 'ruleExpression' such that a string like this is generated
abc=1,def=2
A brute force approach might see us parsing the 'ruleExpression' string to identify fieldnames that start with '#' using regex but i could see how this could get messy as the complexity of the ruleExpression increases.
I'm wondering since the SpEl engine must identify the fields declared in the 'ruleExpression' during the parseExpress() phase is there a way for us to reuse this logic?
EDIT - I did come across the VariableScope private inner class on the org.springframework.expression.spel.ExpressionState class which seems to do what i want but alas the it's not accessible.
You can try overriding lookupVariable in StandardExpressionContext and adding your logging in there. Replacing your stdContext with the following will catch each variable as it is used:
StandardEvaluationContext stdContext = new StandardEvaluationContext() {
#Override
public Object lookupVariable(String name) {
Object value = super.lookupVariable(name);
//do logging here
System.out.println(name + "=" + value);
return value;
}
};
This outputs:
abc=1
def=2
This will only catch the values which are used from variables. Anything that comes from a bean or other object etc. will not go through lookupVariable. Neither will variable values which are never used (due to a conditional for instance).

Why is my IQueryable LINQtoObject being treated as LINQtoSQL and throwing no supported translation to SQL

I have a LINQ dbml class that I am wrapping in a POCO. I have built overloaded constructors that take the DBML class and init. the wrapper objects properties based on the dbml object passed in.
For example
public class MyPerson{
public MyPerson(DBMLPerson p)
{
this.ID = p.ID;
this.Name = p.Name;
}
}
if I then do something like this where I return an IQueryable
{
return from p in datacontext.DBMLPerson
select new MyPerson(p){};
}
When I try to do further queries on that Iquearble I get "System.NotSupportedException: The member 'MyPerson.ID' has no supported translation to SQL.."
However if I do this
{
return from p in datacontext.DBMLPerson
select new MyPerson(){
ID = p.ID;
Name = p.Name;
};
}
I don't get an error at all and everything works perfect. Basically I want to have my class handle the conversion from LINQ object to POCO itself.
Basically I have to use the Object Initializer or I am unable to match on that field.
Ok not sure this will actually help anyone but but myself but my whole problem is the I shouldn't be using IQuerable after a certain point(outside of my repository)
iqueryable-can-kill-your-dog-steal-your-wife-kill-your-will-to-live-etc

How test SqlParameter for equality

Using NUnit and NMock2 I was not able to compare what I thought were the same SqlParameters:
SqlParameter param1 = new SqlParameter("#Id", 1);
SqlParameter param2 = new SqlParameter("#Id", 1);
Assert.IsTrue(param1.Equals(param2)); // This failed
I stumbled across this problem, when trying to test an execution of a method using NMock2
[Test]
public void UpdateComments()
{
const int arbitraryId = 1;
Comment comment = new Comment();
SqlParameter idParam = new SqlParameter("#ChangeId", arbitraryId);
Expect.Once.On(mockSqlDao).Method("ExecuteNonQuery")
.With("usp_Update_Comment", idParam);
changeDao.UpdateComment(arbitraryId, comment);
mocks.VerifyAllExpectationsHaveBeenMet();
}
I received this error:
NMock2.Internal.ExpectationException: unexpected invocation of sqlDao.ExecuteNonQuery("usp_Update_Comment", )
Expected:
1 time: sqlDao.ExecuteNonQuery(equal to "usp_Update_Comment", equal to <#ChangeId>) [called 0 times]
Questions:
How do you test with NMock2 when you
expected Parameter is SqlParameter?
How do you compare equality of two SqlParameters?
Because .Equals() is using the default implementation of Equals as far as I know (which means that a SqlParameter will only "equal" another SqlParameter if they are the same object), you will need to directly interrogate the properties of the parameter to ensure the correct data is being passed.
The Has.Property call within .With allows you to check the properties of a parameter without requiring that a parameter equals some other value. Try the following:
Expect.Once.On(mockSqlDao).Method("ExecuteNonQuery")
.With("usp_Update_Comment", Has.Property("ParameterName").EqualTo("#Id") &
Has.Property("Value").EqualTo(1));