I use Acceleo to create Java main method, but "[]" causes trouble because Acceleo redeems this as invocation - templates

I am using Acceleo to create Java main method in my ".mtl", like this
[template public generateElement(aMiniFamily : MiniFamily)]
[comment #main/]
[file ('CreateMiniFamily.java', false, 'UTF-8')]
public static void main(String[] args) {
}
[/file]
[/template]
But Acceleo gives me error as "The invocation isn't terminated" around "String[]".
I tried with "\[]" and "/[]", not working.

The acceleo template syntax is kind of annoying when you want to print [], but there's a very simple way to go over this issue, it's to remember that Acceleo will evaluate OCL expressions inside of the [ /]. Consequently, you can put a string inside of the [/] and it will be printed as a string in your result file. The expression will then be ['[]'/] and your code:
[template public generateElement(aMiniFamily : MiniFamily)]
[comment #main/]
[file ('CreateMiniFamily.java', false, 'UTF-8')]
public static void main(String['[]'/] args) {
}
[/file]
[/template]

Related

Kotlin sealed class and type inference

im using a sealed class to report back success or error to client code:
sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}
But im stuck getting even the simplest unit test to compile using it:
val error = Result.Error(IOException("message"))
assertThat(error, instanceOf(Result.Error::class.java))
I get the message : Type Inference failed. Not enough information to infer parameter T in fun instanceOf(type : Class<*>) : Matcher!
Looks like im missing something important in Kotlin.
Thanks for helping me out!
there is no problem with your code for me.
import org.hamcrest.CoreMatchers.instanceOf
import org.junit.Test
import org.junit.Assert.*
import java.io.IOException
class ExampleUnitTest {
#Test
fun test1() {
val error = Result.Error(IOException("message"))
assertTrue(error is Result.Error)
}
#Test
fun test2() {
val error = Result.Error(IOException("message"))
assertThat(error , instanceOf(Result.Error::class.java))
}
sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}
}
Also, I'll suggest you to use the keyword is to check if your class is an instance of something in kotlin (like in test1)
Looks like i was looking in the false API. As im mostly using assertj.
Below code is clean and fluent to read
assertThat(result).isInstanceOf(Result.Error::class.java)
To avoid ::class I prefer this.
assertThat(result is Result.Error).isTrue()

Is possible to finish unit testing when a method is called?

Here is my test method where It should be success if showLoading() and loadDataSuccess(response) was called:
#RunWith(PowerMockRunner.class)
public class PresenterTest {
#Mock
private ProfileContract.View view;
#Mock
private ProfileContract.Handler handler;
#Test
public void onLoadDataClicked() {
presenter.loadData();
verify(mView, times(1)).showLoading();
verify(mHandler, times(1)).loadDataSuccess();
}
}
UPDATE 1
Here is my presenter:
class ProfilePresenter(private val mView: ProfileContract.View) : ProfileContract.Handler {
override fun loadData() {
mView.showLoading()
mUserService.user()
.compose(RxUtil.mapper())
.subscribe({ response ->
loadDataSuccess()
}, { error ->
//stuff
})
}
}
Thanks!
If you use return statment, your test finish with success status.
I think there is a basic problem with your test setup:
You do not use verify to check if one function calles another function within the same class. Verify is used to verify that the tested class calls function on other (mocked) classes. If I am not mistaken, your setup should actually give you an error message saying that you can not use verify on instantiated classes.
What you should do -if you want to check if onCompleteClicked() produces the correct results- is to check if the data that gets changed inside the onStuffComplete() function is set correctly. You can use an assert for that.
As an example, lets say onStuffCompleted() sets completeCounter to 1
#Test
public void onCompleteClicked() {
presenter.onStuffCompleteClicked();
assertEquals(completCounter , 1);
}
And to answer your original question: verify (and assert) will pass if the requirements were met (and by this the whole test will pass) and fail if not. You do not need to add any additional stuff (but once again: verify will only work with mocked classes).

JUnit on failure callback/method

Is there any possibility to trigger a method whenever a testcase or assertion fails, in order to do some things when a testcase fails (e.g. Screenshot while UI-Testing, writing an error log, and so on...).
Maybe there is something like an annotation, I did not yet notice.
Thanks in advance!
You can use the TestWatcher rule and implement your own failed method to take a screenshot or whatever you need to do upon test failure. Slightly modified example from the official documentation:
public static class WatchmanTest {
private static String watchedLog;
#Rule
public TestRule watchman = new TestWatcher() {
#Override
protected void failed(Throwable e, Description description) {
watchedLog += d + "\n";
// take screenshot, etc.
}
};
#Test
public void fails() {
fail();
}
}

FreeMarker can't access properties of a javabean

According to the documentation, you should be able to pass a javabean to a FreeMarker template, and it will be able to access the getters of the bean. I've been trying to do this, but have not had any luck. Here's my code where I pass the bean to the template.
public class Hello extends HttpServlet {
public static final Logger LOGGER = Logger.getLogger(Hello.class.getName());
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(new File(this.getServletContext().getRealPath("/templates")));
cfg.setObjectWrapper(new DefaultObjectWrapper());
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
cfg.setIncompatibleImprovements(new Version(2, 3, 20)); // FreeMarker 2.3.20
final String name = req.getParameter("name");
// This works when model is a Map, but not when it is a bean
Model model = new Model();
model.setUsername(name);
Template template = cfg.getTemplate("hello.ftl");
template.process(model, resp.getWriter());
} catch (TemplateException ex) {
LOGGER.log(Level.SEVERE, "Unexpected template exception", ex);
resp.sendError(500);
}
}
private static class Model {
private String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
}
When I try to access ${username} in a template, I get the following error.
The following has evaluated to null or missing:
==> username [in template "hello.ftl" at line 8, column 10]
Tip: If the failing expression is known to be legally null/missing... (snip)
The failing instruction (FTL stack trace):
----------
==> ${username} [in template "hello.ftl" at line 8, column 8]
----------
I can get the template to work correctly when I use a Map. I've tried explicitly wrapping the Model object with various TemplateModel wrappers, but nothing I try seems to work.
Any hints?
Model must be a public class for this to work.
Some other notes unrelated to the question: Use setServletContextForTemplateLoading instead setDirectoryForTemplateLoading, or else your app won't work if it's run from an unpacked .war. Also, of course you must not re-create the Configuration for each request, but I assume that's like that only for the sake of this example.

Acceleo invoking Java Service wrapping an OCLHelper

I need to get the OCL model of conditions contained in UML edges from an ACCELEO script navigating the main UML model. To this end I have defined the following Java class:
public class GetOCLModel {
public Constraint getOCLModel(Classifier context, String expression){
OCL<Package, Classifier, Operation, Property, EnumerationLiteral, Parameter,
State, CallOperationAction, SendSignalAction, Constraint, Class, EObject> ocl;
//CL.newInstance(EcoreEnvironmentFactory.INSTANCE);
UMLEnvironmentFactory uef = new UMLEnvironmentFactory();
ocl = OCL.newInstance(uef.createEnvironment());
OCLHelper<Classifier, Operation, Property, Constraint> helper = ocl.createOCLHelper();
helper.setContext(context);
Constraint expr= null;
try {
expr= (Constraint) helper.createInvariant(expression);
System.out.println("Hunky Dory!");
} catch (ParserException e) {
e.printStackTrace();
}
return expr;
}
}
This is the ACCELEO Module wrapping it:
[module generateOclModel('http://www.eclipse.org/ocl/1.1.0/UML','http://www.eclipse.org/uml2/2.1.0/UML')/]
[query public getOclModel(cl:Classifier, str:String): Constraint = invoke('sfg.baleno.src.services.GetOCLModel',
'getOCLModel(org.eclipse.uml2.uml.Classifier, java.lang.String)',Sequence{cl,str}) /]
And here is how I am trying to invoke it from the main ACCELEO module:
[c.getOclModel('self.name=\'Testclass\'')._context.name/]
It does not work and I cant' see why, any idea?
UPDATE
I realized the helper was actually outputting this exception
org.eclipse.ocl.SemanticException: Unrecognized variable: (name)
what am I doing wrong?