Apex Test Class Object Creation - apex

Could you please let me know If I am having a class called class1, which has 4 method called method1, method2, method3, method4.
When I am creating a test class for class1 called testclass1 with 4 test method called testmethod1, testmethod2, testmethod3, testmethod4.Should I be Instating class1 4 times in all 4 testmethod or I can instatiate once and reuse.
Regards

If you are creating a class with four methods and you need to write a test class to test all four methods, you need to instantiate your class in each of the test methods, from what I have seen in best practices.
Keep in mind that you should be writing all use cases for each method, so your test class could have - and should have - at least an individual test and batch test for each method and that each test method should test a use case both positive and negative. So one method could potentially generate five or more test methods in your test class.
You need to make sure at least 75% but strive for 100% of your class' code lines being tested by your collective test methods.

why you Creating four test methods, i think you can do it all in one
test method, like
public class1 {
public void method1(){} public void method2(){} public void method3(){} public void method4(){} }
and test class
static testMethod void testcostFree(){
class1 c= new class1();
c.method1();
c.method2();
c.method3();
c.method4();
}
}

Related

nunit : global variable initialisation in setupfixture

I am very new to C# and nunit. Pls bear with me if this is basic and has been already been asked here.
We have a global setup,defined by [SetupFixture] class,which is expected to be run only once. The private variables are defined in it's [setup]. We wish to use the same variables in all our testfixtures,hence inheriting the testbase class in all our testfixtures.
But, while executing Testcase1, i observe that globalSetup() is called more than once. Can anyone point me the issue? sample code is as below.
namespace CTB
{
[SetupFixture]
public class Testbase
{
private byte val1;
private byte val2;
[setup]
public void globalSetup
{
val1 = 5;
val2 = 10;
}
[Teardown]
public void globalTeardown
{
//
}
}
}
namespace CTB.Testcase
{
public class TestCase : Testbase
{
[Setup]
public void Setup()
{
}
[Teardown]
public void Teardown()
{
}
[Test]
public void Testcase1()
{
byte val3 = val1 + val2; // Expect 15
}
}
}
I'm assuming that the answer to my comment is "No" and that you are using a current version of NUnit 3. Please correct me if I'm wrong. :-)
You have made the class TestBase serve two functions:
It's the base class for your TestFixture and therefore it's a TestFixture itself.
It's marked as a SetUpFixture so it also serves that function - a completely different function, by the way.
To be clear, you should never do this. It's a sort of "trick" that almost seems designed to confuse NUnit - not your intention of course. Your test fixtures should have no inheritance relationship with any SetUpFixture. Use different classes for the test fixture base and the setup fixture.
With that out of the way, here is the longer story of what is happening...
Before your tests even execute, the SetUpFixture is first "run" - in quotes because it actually does nothing. That's because it doesn't contain any methods marked with [OneTimeSetUp] or '[OneTimeTearDown]`.
NOTE: As an alternate explanation, if you are using a pretty old version of NUnit, the [SetUp] and [TearDown] methods are actually called at this point. Nnit V2 used those attributes with different meanings when encountered in a SetUpFixture versus a TestFixture.
Next your tests execute. Before each test, the inherited [SetUp] and [TearDown] methods are run. Of course, these are actually the same methods as in step 1. NUnit has been tricked into doing this!
Here is some general guidance for the future...
If you want multiple fixtures to use the same data, a base class is useful. Any public or protected fields or properties will be shared by the inheriting fixtures.
If you want to do some common setup or teardown for a group of unrelated test fixtures, use a SetUpFixture. Note that the only way to pass data from a SetUpFixture to the test fixtures is through static fields or properties. Generally, you use a SetUpFixture to set up the environment in which the test is run, not to provide data.
Never use the same class for both purposes.

Normal function in Extbase controller

Is it possible to write a normal function in the controller?
I want to clean up my code a bit, so I want to write some methods for repeated code segments, but I don't want to create a special class.
How is it possible to do this?
If I do a normal
private function xyz () {}
I got a function not found error.
You should use protected, not private unless you have very good reasons to do so. Anyway, defining additional methods work fine for me.
You need to call this method with $this->xyz().
A good solution might be using an abstract class if you want to share methods accross controllers:
abstract class AbstractController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController{
protected function myFunction(){}
}
Your controllers inherit from the abstract class and will have all methods available:
class FirstController extends AbstractController {
public function firstAction(){
// has access to myFunction()
}
}
class SecondController extends AbstractController {
public function secondAction(){
// has access to myFunction()
}
}

AS3 Eclipse: How to create template to extends myClass?

How do I create a template that each time when I create a class that extends MyClass, it will automatically add 3 functions.
EDIT:
In other words I am trying to implement Abstract functionality in AS3. Assume that MyClass have both private and protected methods.
I see the only way to write own code template and call it every time you need, in Flash Builder: window->preference->flash builder->editors->code template->action script->new and give the name to the template, for instance myclass.
You can use existed templates as an example for template syntax.
Template code for MyClass child class with three methods:
import my.package.MyClass
/**
* #author ${user}
*/
public class ${enclosing_type} extends MyClass
{
public function ${enclosing_type}()
{
}
override public function publicMethod():void
{
}
override protected function protectedMethod():void
{
}
override private function privateMethod():void
{
}
${cursor}
}
Usage:
Create new "action script file" or "new class",
remove all file content
type myclass and choose from auto-complete options template myclass
If you are actually extending MyClass, all of MyClass's functions are already available to your descendants. You can also override either of them with old header and desired new body, and still be able to call older versions of those functions via super qualifier. So, you add those functions to MyClass and let them be.
Another way is to make an interface - it's a set of declarations without any function bodies, which you have to implement in any class that wants this interface in its content. A short introduction to interfaces. Then your MyClass will be an interface, with 3 function declarations in it, and whichever class will be declared as implements MyClass will have to provide bodies for these functions.
Check other keywords on that page, including extends and implements.
Hope this helps.
EDIT: There are no abstract classes in AS3, however you can emulate abstract functions in a normal class via exception throwing:
protected function abstractFunction(...params):void {
throw new Error("Abstract!");
}

How to deal with polymorphism inside a class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In languages with dynamic typing, the use of polymorphism may trigger errors on a super-class.
I will try to explain my question with a simple example:
Supposing a language with dynamic typing (like ECMAScript) and the following class structure:
class A{
private idA;
public A(){
idA=0;
}
public foo(){
update();
if (this.idA!=3) Throws new Exception(" What is happening? ");
}
private update(){
this.idA = 3;
}
}
class B extends A{
private idB;
public B(){
super();
idB=0;
}
public foo(){
super.foo();
// Any operation between A::update and B::update()
if (this.idB!=0) Throws new Exception("hmmm, that could not happend!");
update();
}
private update(){
this.idB = 5;
}
}
In this very simple example, when i create an object of the class B, B::foo() call the parent A::foo(), which call "update". The object is an instance of B, so the "update" functions called is B::update, after that, in B::foo, the update function is again called (B::update). The final result is that A::update is never called, and idA still 0.
The class A work correctly when used alone, but after to extend it with B, the function foo() fail.
What is the correct solution this problem:
1) Force the class A to call A::update , that mean an ugly code every call to his own function (protect the super-class):
A::foo(){
A::update();
if (this.idA!=3) Throws new Exception(" What is happening? ");
}
2) B::update is an extension of A::update, so B::update must call itself the parent function (prepare the sub-class, and deal with problems):
B::foo(){
super.foo();
... // Any operation that must be performed between A::update and B::update
}
B::update(){
super.update();
this.idB = 5;
}
But in this case is the A::foo which call update, not the B::foo. That mean others problems.
3) Any other solution.
As a summary:
How to protect the super-class code against polymorphism?
Add protections into the super-class.
Deal with these problem creating the child-class
The language must do that! (do not know if it is possible with dynamically typed languages)
I am looking for a very theoretical /canonical solution to this question.
EDITED: to take the problem out of the constructor and clarify some points.
It's generally considered a very bad practice to call instance methods, and especially virtual instance methods from within a constructor exactly for this reason (but also for the reason that the object isn't done being "initialized" yet).
3) Any other solution.
Doc, it hurts when I do this.
Then don't do that!
Seriously, if you need to set IdA in the constructor of A, don't do it by calling update, do it by explicitly setting the value of IdA in the constructor for A.
The base class should protect itself from harmful overrides. In keeping with the open/close principle, it should be open to extension but closed to modification. Overriding update is a harmful modification of the base class's intended behaviour. In your example, there is no benefit in overriding update because both A::update and B::update are private methods that deal with private variables. There isn't even an expectation that they should be executed together judging by your exception in B::foo. If B::update was named differently, there wouldn't be anything wrong with your implementation. It would probably be OK anyway: since no language I know of will let you override a private method, B::update could hide A::update rather than overriding it.
Depending on the language, you can limit which methods can be overridden in different ways. Some languages require an indicator (a keyword or attribute usually) that a method can be overridden, others to show that it can't. Private methods are generally not overridable, but not all languages have access modifiers at all, and everything is effectively public. In this case you would have to use some kind of convention as suggested by #PoByBolek.
tl;dr: Children have no business with their parents' privates.
You're probably not going to like my answer but: convention and disciplin.
Establish conventions for
when it is safe for a child class to override a method without calling the parent class implementation,
when a child class has to call the parent class implementation of an overridden method,
when a child class must not override a parent class method.
Document these conventions and stick to them. They should probably be part of your code; either in form of comments or naming conventions (whatever works for you). I could think of something like this:
/*
* #final
*/
function shouldNotBeOverridden() {
}
/*
* #overridable
* #call-super
*/
function canBeOverriddenButShouldBeCalledFromChildClasses() {
}
/*
* #overridable
*/
function canBeOverridenWithoutBeingCalledFromChildClasses() {
}
This may help someone reading your code to figure out which methods he may or may not override.
And if someone still overrides your #final methods, you hopefully have thorough testing ;)
I like this answer to a somewhat similar question regarding python:
You could put a comment in there to the effect of:
# We'll fire you if you override this method.
If the language allows one class to call a private method of another class this way, the programmer has to understand and live with that. If I'm understanding your objective, foo and update should be overridden and update should be protected. They would then call the method in the parent class, when necessary. The derived foo method wouldn't need to call update, because calling foo in the parent class would take care of that. The code could work like this:
class A{
private idA;
public A(){
idA=0;
}
public foo(){
update();
if (this.idA!=3) Throws new Exception("idA not set by update");
}
protected update(){
this.idA = 3;
}
}
class B extends A{
private idB;
public B(){
super();
idB=0;
}
#Override
public foo(){
super.foo();
// Any operation between A::update and B::update()
if (this.idB!=5) Throws new Exception("idB not set by super.foo");
}
#Override
protected update(){
super.Update()
this.idB = 5;
}
}
I changed the exceptions to match expectations.

Java and main()

I'm messing around with Eclipse(and java in general) for the first time in about a year. among the things I have forgotten is the following:
I have a function (void callvote() that I am hoping will be activated by my main function (that is, automatically, relatively early in the program). I currently have it within the same class (body) as the main function itself.
I try to call it withcallvote(); and get an error, "- Cannot make a static reference to the non-static method callvote() from the type body"
my function callvote is, at the moment, in the space below main and simply says
public void callvote()
{
}
am i committing a horrible sin by putting more functions in the same class as main?
is this a relatively easy fix that I missed somehow?
What does this error mean?
Have I woken Azatoth with this code?
Thanks in advance,
Tormos
Without the static modifier callvote is implicitly an instance method - you need an instance of a class to call it.
You could mark it as static also:
public static void callvote() ...
Or create an instance of the declaring class:
MyClass instance = new MyClass();
instance.callvote();
main() is a static method, meaning you can call it directly from a class whereas non-static members can only be called from an object. In order for you to call the callvote() method you need to first instantiate an object of your class:
public static void main(String [ ] args) {
MyClass myObject = new MyClass();
myObject.callvote();
}
Another way to avoid the error is to make you callvote() method static as well, but it's usually not what you want to do (but it depends on the nature of your class and method).
This post describes some of the dangers with the overuse of static methods: Class with single method -- best approach?
Try this:
public class Main {
public static void main(String[] args) {
new Main().callvote()
}
}
the main() entry point of your java program is static. You cannot call a non static method from a static one.
So you have to instanciate your Class first and call the method after.