Easiest way to call one same method in two different class junit - eclipse

I have got one method say Login in "First class". Now in my "Second class" again Login is needed to be done, so can anyone tell me what's the easiest way to do this task ?
Should i create object of first class in second class and call to methods of first class.
Should i create base class and extend it ?
Please provide any example if possible
Thanks

Alright let me answer this here:
class MyBase
{
void Login()
{
// TODO base defined login here
}
}
class FirstClass extends MyBase
{
// Define your methods in any order it is fine
void Login()
{
// TODO firstclass defined login here
}
void addTest()
{
// Addtest code here
}
}
int main()
{
MyBase base;
FirstClass firstClass;
base.Login() // Will call the MyBase method for Login
firstClass.Login() // Will call the FirstClass method for Login
}
So the order of defining methods isn't important as long as you are doing them nicely. If possible read about Inheritance in Java to be more clear with your approach.
Do you understand this completely now..? If yes then start coding and if not then let me know and we'll go more deeper...

I would recommend implementing a Page Object Model, and refactor the login code to be a method of the object representing the login screen. That way, the login code will be most easily available to any testcase which needs to perform a login. The code will look something like this simplified version:
public class LogInScreen {
public void LogIn(String username, String password) {
userNameTextField.sendKeys(username);
passwordTextField.sendKeys(password);
loginButton.click();
}
public class MyTests {
#Test
public void testLoginNormalUser() {
String username = "userA";
String password = "badg3rs";
publicscreen.LogIn(username, password);
// carry on with the rest of the test.
}
#Test
public void testLoginAdminUser() {
String username = "userB";
String password = "3lk";
publicscreen.LogIn(username, password);
// carry on with the rest of the test.
}
Notice the benefits you get from this:
The code which interacts with the login controls is in a class representing the login screen; the testcase code doesn't need to concern itself with the UI details too much, so each #test can just concern itself with test logic.
Any testcase can call the login() method.
It's simple: there's no need for inheritance or overloading.

Related

How to verify a method inside a method is called in mockito

I was doing some unit testing in flutter with mockito, and I feels unable to verify a method is called within another method. The code I've written so far as follows,
The class I want to test
class A {
void doSomething() {
callMe();
}
void callMe() {}
}
Mocked class
class MockA extends Mock implements A {}
The test I wrote,
test("Test method is called", () {
A a = new MockA();
a.doSomething();
verify(a.callMe()).called(1);
});
When I run the above test I am getting an error
No matching calls. All calls: MockA.doSomething()
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
If i verify doSomething is called it works, but for a call on callMe within doSomething doesn't work. Is this the default behavior or am I doing something wrong? Please note I need to verify the callMe() method is called when doSomething() is called.
You mocked A and replaced it with MockA. Mocks have no implementation. MockA.doSomething() does nothing and does not and cannot call MockA.callMe().
That A.doSomething() calls A.callMe() should be considered an implementation detail of of doSomething(); making a test rely on that would tightly couple the test to the specific implementation and would be brittle.
You can't use a mock to verify the implementation of the thing being mocked. If you want to verify the implementation of A.doSomething(), you instead should use an actual object and verify observable properties on that object.
But if you still really want to do this, then you would need to modify A to not call methods on itself and to instead call methods on a provided object (i.e., "dependency injection"). For example:
class A {
final late A a;
A({A? a}) {
this.a = a ?? this;
}
void doSomething() {
a.callMe();
}
void callMe() {}
}
test("Test method is called", () {
var mockA = MockA();
var actualA = A(a: mockA);
actualA.doSomething();
verify(mockA.callMe()).called(1);
});
It's a bit unusual for a class to depend on a mock of itself, however, and it would not scale if you then want to verify calls made by callMe().
Another approach that would scale better (but with significantly more work) would be to create your own fake class that tracks method calls:
class TrackedA implements A {
int doSomethingCallCount = 0;
int callMeCallCount = 0;
#override
void doSomething() {
doSomethingCallCount += 1;
super.doSomething();
}
#override
void callMe() {
callMeCallCount += 1;
super.callMe();
}
}
But again, that's very brittle, and I would not recommend it.

Async method in Spring Boot

I have a problem with sending email with method annotated as #Async.
Firstly, I am not sure if it is possible to work as I want so I need help with explanation.
Here is what am doing now:
In main method i have annotation
#EnableAsync(proxyTargetClass = true)
Next I have AsyncConfig class
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import java.util.concurrent.Executor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
#Configuration
public class AsyncConfig extends AsyncConfigurerSupport {
#Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("email-");
executor.initialize();
return executor;
}
}
Of course, its rest application so i have controller, service etc, looks normally, nothing special
My async method looks like this:
#Async
public void sendEmail() throws InterruptedException {
log.info("Sleep");
Thread.sleep(10000L);
//method code
log.info("Done");
}
I executing this method in another service method:
#Override
public boolean sendSystemEmail() {
try {
this.sendEmail();
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("pending sendEmail method");
return true;
}
Now what I want archive is to ignore executing sendEmail() function and execute return true; meanwhile function sendEmail() will be executing in another Thread. Of course it doesn't work now as I want. Unfortunately.
Note that I am new into async programming, so I have lack of knowledge in some parts of this programming method.
Thanks for any help.
First – let’s go over the rules – #Async has two limitations:
it must be applied to public methods only
self-invocation – calling the async method from within the same class – won’t work
The reasons are simple – the method needs to be public so that it can be proxied. And self-invocation doesn’t work because it bypasses the proxy and calls the underlying method directly.
http://www.baeldung.com/spring-async

GWT tokenizer: How to change URL

I am using Activities and Places.
I have a LoginPlace.
The url displayed when I navigate to that place has this at the end:
#LoginPlace:login
How can I change this to just #login or something else?
My tokenizer looks like this:
public class LoginTokenizer implements PlaceTokenizer<LoginPlace> {
private LoginPlace loginPlace;
public LoginTokenizer() {
}
#Override
public LoginPlace getPlace(String token) {
return new LoginPlace(token);
}
#Override
public String getToken(LoginPlace place) {
loginPlace = place;
return loginPlace.getLoginToken();
}
}
And navigation to the LoginPlace is done through the PlaceController:
clientFactory.getPlaceController().goTo(new LoginPlace("login"));
Where can I manipulate the format of the URL?
The mapping is done by the PlaceHistoryMapper.
You can have an implementation generated by GWT based in PlaceTokenizers, but then it's based on a prefix/suffix. The #Prefix allows you configure the prefix (which otherwise defaults to the place class' name).
Or you can implement the interface yourself and have complete control over the process.
Rename the Place class from LoginPlace to Login.
Pass an empty token:
new LoginPlace("")

Print data received by REST call when using #Resource in Grails

Following along with groovies docs on REST, i've setup a model like so:
import grails.rest.*
#Resource(uri='/books')
class Book {
String title
static constraints = {
title blank:false
}
}
I'd print out the parameters I receive when creating and saving. Is there away to override these methods created by the #Resource(uri='/books') annotation? Or handle the annotation a closure or something to do this?
I think you may have 2 choices if you wish to have a default RESTful interface and modify it somewhat for your needs.
Use the $ grails generate-controller [Domain Class Name] command that will generate the appropriate controller and change the generated file as needed.
Create a Book controller and extend the RestfulController; then override the default methods with the #Override annotation, print/log the params, and then call the matching super method.
import grails.rest.RestfulController
class BookController extends RestfulController {
static responseFormats = ['json', 'xml']
BookController() {
super(Book)
}
#Override
def save() {
println params
super.save params
}
#Override
def update() {
println params
super.update params
}
}

Get route params in RESTful controller

In my RestController which extends AbstractRestfulController, I can get the route params in the implemented functions such as...
public function create($data)
{
$entity = $this->params()->fromRoute('entity');
}
... but when I do the same in the constructor like this
public function __construct()
{
$entity = $this->params()->fromRoute('entity');
}
I get Call to a member function getParam() on a non-object.
Why is that? How can I get the route parameters in the constructor?
What I am trying to do
Since I'm trying to create a generic controller, there is a part of the restful route that is shared for all actions (resp. verbs). The entity for which the request is made. I'd like to store this in a class parameter for convenience.
Normally you'd write a method to proxy to whatever value you need, and just call that method, it's only a little more expensive to call $this->getEntity() than it is to call $this->entity, which, as far as I can tell is the stated aim
class RestController
{
protected $entity;
public function getEntity()
{
if (!$this->entity) {
$this->entity = $this->params()->fromRoute('entity');
}
return $this->entity;
}
}
If you really do want to pre-populate the entity property, the simplest method is to use an initializer, and move the code from your __constructor to init(). Have your controller implement \Zend\Stdlib\InitializableInterface
use Zend\Stdlib\InitializableInterface;
class RestController extends AbstractRestfulController implements InitializableInterface
{
protected $entity;
public function init() {
$this->entity = $this->params()->fromRoute('entity');
}
}
Add an initializer to the controller loader in your module boostrap
use Zend\Stdlib\InitializableInterface;
class Module
{
public function onBootstrap(MvcEvent $e)
$sm = $e->getApplication()->getServiceManager();
$controllers = $sm->get('ControllerLoader');
$controllers->addInitializer(function($controller, $cl) {
if ($controller instanceof InitializableInterface) {
$controller->init();
}
}, false); // false tells the loader to run this initializer after all others
}
}
That would not make any sense as the route is matched to a particular action.
You can't route to a constructor, therefore how could you get route parameters there?
If you give an idea of what you are trying to do then I could suggest a better/nicer way to do it