I have this object
#Validateable
class Foo {
Map<String, String> items
static constraints = {
items minSize: 1
}
}
but this test fail:
#Test
void shouldNotValidateIfItemsIsEmpty() {
Foo foo = new Foo(items: [:])
assert !foo.validate()
}
What do I do wrong? It's supposed to work according to grails 'minSize' documentation: "Sets the minimum size of a collection or number property."
The documentation might be misleading. The minSize constraint will only apply to:
String
Arrays
Classes which implements the java.util.Collection interface
java.util.Map however does not extend the java.util.Collection interface
See the supports method of MinSizeConstraint:
public boolean supports(Class type) {
return type != null && (
String.class.isAssignableFrom(type) ||
Collection.class.isAssignableFrom(type) ||
type.isArray());
}
You can develop your own custom constraint for this or a custom validator as suggested by Thermech
In addition, in order for Grails to mock the validate method properly your test class should be something like:
#TestMixin(ControllerUnitTestMixin) class FooTest {
#Test
void shouldNotValidateIfItemsIsEmpty() {
Foo foo = mockCommandObject Foo
foo.items = [:]
assert !foo.validate()
} }
The only way I found, is with a custom validator:
static constraints = {
items validator: { Map map, obj, errors ->
if (map.size() < 1) errors.rejectValue('items', 'minSize.notmet')
}
}
Related
I have constructor where there is filter logic and wanna test it, though writing test case for constructor is not in practice i wanna have the code coverage , have tried many links but none are explaining about handling a constructor.
public Myclass {
public Myclass(AnotherClass obj)
{
_key = obj.key;
_ID = obj.ID;
_CandidateMode = obj.CandidateMode;
if(_CandidateMode == obj.CandidateMode.numeric
{
//Dosomething
}
else
{
//Do something with special character.
}
}
}
Definitely placing logic inside a constructor is a thing to avoid. Good you know that :-) In this particular case maybe the if could go into each of the public methods of MyClass, or maybe you could use polymorphism (create MyClass or MySpecialCharacterClass base on the AnotherClass object)?
Anyway, to get to a straight answer: if you really must test constructor logic, do it like you would test any other method (in some languages it's just a static method called new, by the way).
[TestMethod]
public void is_constructed_with_numeric_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.numeric };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for numeric candidate
...
}
[TestMethod]
public void is_constructed_with_special_candidate() {
// Given
AnotherClass obj = new AnotherClass { CandidateMode = CandidateMode.special };
// When
MyClass myClass = new MyClass(obj);
// Then
// assert myClass object state is correct for special candidate
...
}
This is giving an error:
class Apple(weightInGrams: Float){
fun grow() {
weightInGrams+= 2.0f
}
}
First of all, the equivalent of void (in Java) is Unit (in Kotlin), and the type a function returns goes at the end, so you should use fun grow(): Unit { ... } instead of fun void grow() { ... }. Moreover, you can omit Unit and just write fun grow() { ... } because the compiler knows that your function doesn't return any meaningful value.
Now, I'll try to explain the basics to answer your question and give you some clarity. In Java, the parameters of a constructor are visible only inside that constructor. In Kotlin, the parameters are only visible in initializer blocks and in property initializers, unless you transform them into properties. Let's explain all this with examples.
In Java, we see constructors in classes like this many times:
public class Person {
public final String name;
public final Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
The parameters are used to initialize the fields of the class Person.
In Kotlin, the equivalent could be:
a) Use the parameters in initializer blocks.
class Person(name: String, age: Int) {
val name: String
val age: Int
init {
this.name = name
this.age = age
}
}
b) Use the parameters in property initializers declared in the class body.
class Person(name: String, age: Int) {
val name = name
val age = age
}
c) Declaring properties and initializing them directly in the primary constructor.
class Person(val name: String, val age: Int)
Therefore, if you write var or val, the parameters of the constructor will be also properties and you will be able to use them in your class like you want to do inside your function grow.
So, your final code should be:
class Apple(var weightInGrams: Float) {
fun grow() {
weightInGrams += 2.0f
}
}
var because you are assigning a value to weightInGrams multiple times.
make your property a class member
class Apple(var weightInGrams: Float){
fun void grow() {
weightInGrams+= 2.0f
}
}
I understand the question was already answered.
If you want to initialize an apple with an initialWeight, you can do it as below. The init block can help initialize the value and the grow function can effectively work on the actual variable without a need to declare the constructor variable as var:
class Apple(initWeight: Float){
var weightInGrams = 0.0f
init {
var weightInGrams = initWeight
}
fun grow() {
weightInGrams+= 2.0f
}
}
fun main(args: Array<String>) {
val a = Apple(10.0f)
a.grow()
println(a.weightInGrams)
};
I am looking for an way to overwrite xor on an groovy script.
I've created a base class for my script where a Object is defined. This object already has a method public Object xor(String var) which works like myobject^"foo". What I want is way to access this method like myobject^foo where foo handled like a normal String.
as i understand you want to do somehow that
(myobject^"foo") == (myobject^foo)
so, in your script you can redefine method getProperty() so in your script access to foo property will return "foo" string..
class A{
public Object xor(Object o){
println "xor $o"
return o
}
}
public getProperty(String key){
if(key in ['out'])return super.getProperty(key) //skip standard properties
return key
}
def myobject=new A()
assert (myobject^foo) == (myobject^"foo")
but i don't see any benefits :)
Based on your answer #daggett I found a method which handles missing properties:
public abstract class MyBaseScript extends Script implements GroovyObject {
protected class A {
public Object xor(String var) {
//do fancy stuff
return var;
}
}
protected A foo = new A();
//method which handles missing properties
public Object propertyMissing(String name) {
return name;
}
}
How do I start my scripts:
Binding binding = new Binding();
// passing parameters
binding.setVariable("arg0", arg0);
binding.setVariable("args", arg1);
// Compiler Config
CompilerConfiguration cc = new CompilerConfiguration();
ImportCustomizer ic = new ImportCustomizer();
// add some imports for e.g.
ic.addImports("java.awt.Color", "java.util.Calendar",...);
cc.addCompilationCustomizers(ic);
// set BaseClass
cc.setScriptBaseClass("de.MyBaseScript");
// execute script
GroovyClassLoader loader = new GroovyClassLoader();
shell = new GroovyShell(loader, binding, cc);
Script gscript = shell.parse(groovyScriptAsAFile);
Object o = gscript.run();
I have a number of classes, POJO style, that shares a single functionality, say readCSV method. So I want to use a single parent (or maybe abstract, not sure if it should be) class that these POJOs can extend. Here's a pseudo-code:
(abstract) class CSVUtil {
private String[] fileHeader = null;
protected void setFileHeader(fileHeader) {
this.fileHeader = fileHeader;
}
protected List<WhateverChildClass> readCSV(String fileName) {
// read CSV using Apache Commons CSV
// and return a List of child type
List<WhateverChildClass> list = null;
// some declarations
try {
list = new ArrayList<WhateverChildClass>();
csvParser = new CSVParser(fileReader, csvFormat);
List csvRecords = csvParser.getRecords();
for (...) {
CSVRecord record = (CSVRecord) csvRecords.get(i);
WhateverChildClass childClass = new WhateverChildClass();
// loop through fields of childClass using reflection and assign
for (// all fields of childClass) {
childClass.setWhateverField(record.get(fileHeader[i]));
}
list.add(childClass);
System.out.println(p);
ps.add(p);
}
}
...
return list;
}
}
on one of the child classes, say ChildA
class ChildA extends CSVUtil {
// fields, getters, setters
}
How do I code the CSVUtil such that I can determine in runtime the child class in readCSV defined in the parent class?
Is it possible to make this method static and still be inherited?
As an alternative, is there API in Apache Commons CSV that can generally read a CSV, determine its schema, and wrap it as a generic Object (I don't know if I make sense here), and return a list of whatever that Object is ?
You want that readCSV to be a static method ?
Then, i would say that ChildA class shouldn't inherit from CSVUtil, but implement an Interface ... something like that :
public final class CSVUtil {
private CSVUtil() {
}
public static <T extends ICSV> List<T> readCSV(String filename) {
...
}
class ChildA implements ICSV
I have an issue, i need to list all the interfaces that are anyhow related to the class? –
For ex:
class Test : interface1
{
public int var1;
classA obj1;
classB obj2;
classC obj3;
}
class classA: interface2
{
testclass obj;
}
class classB: interface3
{
}
class classC: interface4
{
}
class testclass: testinterface
{
myinterface objInterface;
}
interface myinterface{}
My question is how do I list all the interfaces of class Test (it should return all the interfaces anyhow related to the class ex:. interface1, interface2 etc.,).
Anyone help me please?
Thanks in advance
With your current code (almost nothing public, fields instead of properties, etc...), you could do something like that :
var type = typeof(Test);
var interfaces = type.GetInterfaces().ToList();
interfaces.AddRange(type.GetFields(BindingFlags.NonPublic|BindingFlags.Instance)
.SelectMany(x => x.FieldType.GetInterfaces()));
this won't retrieve interfaces of public int var1, as it's... public.
This probably won't fit your exact needs, but without real code and real expected result, it's quite hard to give a better answer.
EDIT
With recursion and your sample, in a console app :
private static void Main()
{
var type = typeof(Test);
var interfaces = type.GetInterfaces().ToList();
GetRecursiveInterfaces(type, ref interfaces);
}
private static IList<Type> GetFieldsType(Type type)
{
return type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Select(m => m.FieldType).ToList();
}
private static void GetRecursiveInterfaces(Type type, ref List<Type> interfaces)
{
foreach (var innerType in GetFieldsType(type))
{
interfaces.AddRange(innerType.IsInterface
? new[] { innerType }
: innerType.GetInterfaces());
GetRecursiveInterfaces(innerType, ref interfaces);
}
}