Sling Remote Junit Test Case - java

I'm trying to execute a JUnit test remotely on an Adobe AEM instance, using the JUnit Servlet. Post for reference: Which Testing framework will suit for Adobe CQ5 Project?
I've defined my testcase and was expecting to be able to see it at this URL
http://localhost:4502/system/sling/junit/
It does not show up though.
The test runs correctly with mvn test.
it's a very simple test case (junit3):
import junit.framework.TestCase;
public class mySampleTest extends TestCase {
public void testSomething(){
return;
}
}
What do I need to do in order for the testcase to be available in the Sling remote JUnit test servlet?

I think you need to add annotation #RunWith(SlingRemoteTestRunner.class). Also you should read about it here and you can see example here

Related

Creating Mockito test case for Spring Boot module

I have a spring boot module :
Mainproject
-web
-model
-repository
-service
I have created mockito test cases for web .
How should i create mockito test cases for service layer .
I am not able to use any of the autowire as i dont have the Application context . it gives me error:
package service;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
#ExtendWith(MockitoExtension.class)
public class ProvidrsServiceTest {
#Autowire
config config;
}
Secondly i have this bean of config:
class config{
#value
#value
#value..
}
it is just having some values from property file . can i mock this ? how . please tell .
Can you tell me how should i structure the mockito test classes . should i place all the test classes in web layer as there i am able to get the context .
Your service layer should be independent from your framework. So you might want to refactor your code to remove all framework dependencies from your service.
Once this is done you can use the org.mockito.Mock annotation on your calling services / repositories to create a mock of them.
If your config is already independent from the framework then you can also mock it.
You may use the Integration test using #SpringBootTest but that is not recommended for unit testing as the spring takes sometime to load the application context and it can delay your entire test suite. I found this tutorial helpful which may help you to identify how to write tests for different modules of spring. Please let me know if this helps!

Is it possible to test the properties injection correctness via JUNIT?

I have developed my application and I have a .properties file containing several key-value properties.
In my code I inject said properties like this:
#Value("${services.host}${services.name}")
private String hostname;
I am searching for a way to check every #Value inside of my code so to make sure that every property will be solved at runtime. Something like simulating my application startup.
Is it possible?
Yes, you can create a JUnit test class that loads your application context (just like your production code would) and then execute a test method that verifies that your property values have been injected.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {AppConfig.class})
public class SpringApplicationTest {
#Autowired
private MyServiceBean serviceBean;
#Test
public void shouldExecuteServiceBean_andProduceExpectedOutcome() {
//TODO test setup
serviceBean.doSomething()
//TODO assert output
}
}
In this example MyServiceBean.java is a class that would be executed from your Main class, so that you are testing the end-to-end logic of your application, including all of the spring dependency injections. Think of it as your "happy path" test scenario. I always include at least one test like this in my projects, to ensure that all of the spring injections are correct and load without error. You wan't to catch the errors before you build and deploy your code.
In the example above AppConfig.java is the same Spring configuration class you use when your code is deployed. You probably want to add another configuration class that overrides some properties/beans specifically for testing only.
#ContextConfiguration(classes = {AppConfig.class, TestConfig.class})
Using a test only class, you can mock out any dependencies that make testing difficult (i.e. use an in-memory database), and also override properties so you can test against "localhost" rather than another service which may or may not be available (so long as you can create an equivalent localhost service in your test setup).
Note: If you are finding it difficult to test your application due to too many dependencies, or external dependencies that cannot be swapped out easily, the pain you are feeling is a good guide to start thinking about how to change your architecture to support ease of testing. You also can just test portions of your application using the above concepts.

Using Mockito for API Stubbing Load Test

I have a Spring Boot application with a REST API. Behind the scenes it uses a vended SDK to call the vendors service. I need to run load tests on my application, but don’t want to call the vendor API and accidentally crash their system during testing.
Is it possible to use Mockito outside of a JUnit test to create a mock for the vendor SDK objects during the normal application runtime?
I figured I would use a profile based configuration beam to enable the mocked object when profile is “performance-test”. But I can find no article/discussion/mention of anyone using Mockito this way and it is making me second guess my approach. Thoughts?
You probably should look for using wiremock or similar software to mock the vendor service, like here: Integration Testing with a fake server
Wiremock is a stub server that you can conveniently start/stop from within JUnit tests. It acts like the remote server when you set up responses. The documentation is really good, I do not want to copy&paste all of it here.
Just a sample:
public class MyTest {
#Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort().dynamicHttpsPort());
#Test
public void exampleTest() {
stubFor(get(urlEqualTo("/my/resource"))
.willReturn(aResponse()
.withStatus(200)
.withBody("<response>Some content</response>")));
...
verify(postRequestedFor(urlMatching("/my/resource/[a-z0-9]+"))
.withRequestBody(matching(".*<message>1234</message>.*")));
}
}
For loadtest, you would rather run the stub standalone somewhere, and have some script set up the responses.
You probably don't find mention of Mockito because embedding mocks with stub responses into your application is a bad idea and will not help you getting realistic results for load tests (because your responses will be much faster and not pass through serialization/deserialization).
Else also look here:
How to mock remote REST API in unit test with Spring?

Struts2 pre-test ServletContext

I have two Struts2 Action classes - 'SetupAction' and 'MainAction'. 'SetupAction' sets up some file locations to read files. It implements the ServletContextListener:
#WebListener
public class SetupAction implements ServletContextListener {....}
I want to test methods in my 'MainAction' using JUnit4, in addition to using Cargo and Failsafe plugins to start a Tomcat7 instance before running tests and tearing it down afterwards.
The problem is I need 'SetupAction' to complete setup before running the tests. I want to run this as if it's on a real server which is why I'm avoiding mocks.
proxy.getAction() in 'MainAction' will return 'SetupAction' if I send a HTTP GET request to the server at the start of the test.
Any help/guidance would be greatly appreciated.

Load testing for java client/server application

I have written a java client server application (not http), which i need to load test. However, most tools out there such as jmeter and grinder seem to be targeted to http requests. Any suggestions?
Thanks!
JMeter allows writing pluginns. If your application uses protocol other than HTTP it seems that the protocol is proprietary, so writing tests requires some custom implementation anyway. JMeter allows this and it is highly recommended.
since we have no idea what protocol you're using, write your own client in a way easily extendable for load testing.
You could have a look at Soatest which claims to be socket based and should be able to use whichever web protocol you are using (hopefully TCP/UDP).
You can use the JUnit4 or JUnit5 based load runners below which can simply accept your Unit tests and generate load on the target server. These need not be HTTP tests, these could be any tests annotated with #Test
JUnit4 based load runner
JUnit5 based load runner
The load configs look like below to ramp up or ramp down your load:
number.of.threads=2
ramp.up.period.in.seconds=10
loop.count=1
Your load test will look like below:
#LoadWith("our_load_config.properties")
#TestMapping(testClass = AnyTestEndPoint.class, testMethod = "anyTestMethod")
#RunWith(ZeroCodeLoadRunner.class)
public class LoadTest {
}
Your JUnit test which is fed to the load generator,
The test class looks like below:
import org.junit.Test;
public class AnyTestEndPoint {
#Test
public void anyTestMethod() throws Exception {
...
// You can have your client code invoking the target server
...
}
}
Note:
You can feed multiple Junit tests too to the load reactor, to generate load on different part of the server logic/apis/processes.
Visit the HelloWorld Examples for more details.

Categories