How to create mock instance of Autowired component in Vert.x - junit

I am trying to create mock instance of the class which is autowired inside Verticle but I am getting it as a null. For synchronous code the way which works is looking not useful for Vert.x.
Verticle is:
#Component
public class MyVerticle extends AbstractVerticle{
#Autowired
private ServiceExecutor serviceExecutor;
#Override
public void start() throws Exception {
super.start();
vertx.eventBus().<String>consumer("address.xyz").handler(handleRequest());
}
private Handler<Message<String>> handleRequest() {
return msg -> {
getSomeData(msg.body().toString())
.setHandler(ar -> {
if(ar.succeeded()){
msg.reply(ar.result());
}else{
msg.reply(ar.cause().getMessage());
}
});
};
}
private Future<String> getSomeData(String inputJson) {
Promise<String> promise = Promise.promise();
String data = serviceExecutor.executeSomeService(inputJson); // Getting NPE here. serviceExecutor is coming as null when trying to create mock of it using Mockito.when.
promise.complete(data);
return promise.future();
}
}
Dependent component is:
#Component
public class ServiceExecutor {
public String executeSomeService(String input){
return "Returning Data";
}
}
Test case is:
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
#RunWith(VertxUnitRunner.class)
public class MyVerticleTest {
#Mock
private ServiceExecutor serviceExecutor;
private Vertx vertx;
#Before
public void setup(TestContext ctx){
MockitoAnnotations.initMocks(this);
Async async = ctx.async();
this.vertx = Vertx.vertx();
vertx.deployVerticle(MyVerticle.class.getName(), h -> {
if(h.succeeded()){
async.complete();
}else{
ctx.fail();
}
});
}
#Test
public void test_consumption(TestContext ctx) {
Async async = ctx.async();
when(serviceExecutor.executeSomeService(Mockito.anyString())).thenReturn("Returning Data");
vertx.eventBus().request("address.xyz","message", h ->{
if(h.succeeded()){
ctx.assertEquals("Returning Data",h.result().body().toString());
async.complete();
}else{
ctx.fail(h.cause());
}
});
}
}
Above Test Case works well if I don't use autowired instance to call a method to get the date. But if used it (which I must do to get the data), it is giving NPE at MyVerticle->getSomeData() method when trying to use serviceExecutor object as a mock. This approach works very well for Synchronous code flow but for Vert.x looks like it won't help. So need help here to mock the autowired instance serviceExecutor inside Verticle.

Add a constructor in your MyVerticle
public MyVerticle(ApplicationContext context) {
context.getAutowireCapableBeanFactory().autowireBean(this);
}
and deploy your verticle something like vertx.deployVerticle(new MyVerticle(context),...
I have application context while deploying the verticle and thats what I am passing in the constructor. Check if this works for you.

Related

How to write Junit test case for start method of consumer Verticle in vert.x?

I have implemented one Verticle as mentioned below. Verticle is working as expected. Now I am trying to write Junit test case for this Verticle which could test the start method, the handler method handleRequest(), and the method getSomeData() inside handler which returns Future. Either single test case to test all three method or individual test case to test individual method should be fine.
I know writing Junit test cases for synchronous code but have no idea how exactly to write Junit TCs for Verticle in vert.x which is asynchronous. Could anyone please guide me here? I also have router verticle from which I am sending message to this consumer verticle MyVerticle but I am thinking to write Jnuit test cases for this consumer verticle first. Please help.
#Component
public class MyVerticle extends AbstractVerticle{
#Override
public void start() throws Exception {
super.start();
vertx.eventBus().<String>consumer("address.xyz").handler(handleRequest());
}
private Handler<Message<String>> handleRequest() {
return msg -> {
getSomeData(msg.body().toString())
.setHandler(ar -> {
if(ar.succeeded()){
msg.reply(ar.result());
}else{
msg.reply(ar.cause().getMessage());
}
});
};
}
private Future<String> getSomeData(String inputJson) {
Promise<String> promise = Promise.promise();
promise.complete("Returning Data");
return promise.future();
}
}
I recommend using the vertx-unit project, wich makes it easy to test async code. For your parcular case it would go like this:
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(VertxUnitRunner.class)
public class MainVerticleTest {
private Vertx vertx;
#Before
public void setup(TestContext ctx){
Async async = ctx.async();
this.vertx = Vertx.vertx();
vertx.deployVerticle(MyVerticle.class.getName(), h -> {
if(h.succeeded()){
async.complete();
}else{
ctx.fail();
}
});
}
#Test
public void test_consumption(TestContext ctx) {
Async async = ctx.async();
vertx.eventBus().request("address.xyz","message", h ->{
if(h.succeeded()){
ctx.assertEquals("Returning Data",h.result().body().toString());
async.complete();
}else{
ctx.fail(h.cause());
}
});
}
}

How do I mock a static method call from a nother static method in the same class?

I have a utilities class wherein one static method calls another. I want to mock the called method but not the target method. Does anyone have an example?
I've got:
#RunWith(PowerMockRunner.class)
#PrepareForTest({SubjectUnderTest.class})
public class SubjectUnderTestTest {
...
SubjectUnderTest testTarget = PowerMockito.mock(SubjectUnderTest.class, Mockito.CALLS_REAL_METHODS);
Starting from the docs, with some minor tweaks, you can either mock or spy the static method, depending on what you need (spying seems a bit less verbose but has different syntax). You can find below a sample for both, based on PowerMockito 1.7.3 & Mockito 1.10.19.
Given the following simple class with the required 2 static methods:
public class ClassWithStaticMethods {
public static String doSomething() {
throw new UnsupportedOperationException("Nope!");
}
public static String callDoSomething() {
return doSomething();
}
}
You can do something like:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.powermock.api.mockito.PowerMockito.*;
// prep for the magic show
#RunWith(PowerMockRunner.class)
#PrepareForTest(ClassWithStaticMethods.class)
public class ClassWithStaticMethodsTest {
#Test
public void shouldMockStaticMethod() {
// enable static mocking
mockStatic(ClassWithStaticMethods.class);
// mock the desired method
when(ClassWithStaticMethods.doSomething()).thenReturn("Did something!");
// can't use Mockito.CALLS_REAL_METHODS, so work around it
when(ClassWithStaticMethods.callDoSomething()).thenCallRealMethod();
// validate results
assertThat(ClassWithStaticMethods.callDoSomething(), is("Did something!"));
}
#Test
public void shouldSpyStaticMethod() throws Exception {
// enable static spying
spy(ClassWithStaticMethods.class);
// mock the desired method - pay attention to the different syntax
doReturn("Did something!").when(ClassWithStaticMethods.class, "doSomething");
// validate
assertThat(ClassWithStaticMethods.callDoSomething(), is("Did something!"));
}
}

Unit test WCMUsePOJO class

I am writing unit test cases for following class which extends WCMUsePOJO. Now, this class is using a getSlingScriptHelper method shown below.
public class ConstantsServiceProvider extends WCMUsePojo {
private static final Logger logger = LoggerFactory.getLogger(ConstantsServiceProvider.class);
private String var1;
#Override
public void activate() throws Exception {
ConstantsService constantsService = getSlingScriptHelper().getService(ConstantsService.class);
if(constantsService != null) {
var1 = constantsService.getVar1();
}
}
public string getVar1() { return var1; }
}
The question is how do I mock getSlingScriptHelper method? Following is my unit test code.
public class ConstantsServiceProviderTest {
#Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
#Mock
public SlingScriptHelper scriptHelper;
public ConstantsServiceProviderTest() throws Exception {
}
#Before
public void setUp() throws Exception {
ConstantsService service = new ConstantsService();
scriptHelper = context.slingScriptHelper();
provider = new ConstantsServiceProvider();
provider.activate();
}
#Test
public void testGetvar1() throws Exception {
String testvar1 = "";
String var1 = provider.getVar1();
assertEquals(testvar1, var1);
}
}
The only thing that you should "have to"* mock is the SlingScriptHelper instance itself, so that it will mimic the dependency injection of the declared service.
Everything else (e.g. the Bindings instance) can be a concrete implementation, for example:
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.junit.Test;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConstantsServiceProviderTest {
private SlingScriptHelper mockSling = mock(SlingScriptHelper.class);
private ConstantsServiceProvider constantsServiceProvider = new ConstantsServiceProvider();
private Bindings bindings = new SimpleBindings();
#Test
public void testFoo() throws Exception {
//Arrange
final String expected = "Hello world";
final ConstantsService testConstantsService = new TestConstantsService(expected);
when(mockSling.getService(ConstantsService.class)).thenReturn(testConstantsService);
bindings.put(SlingBindings.SLING, mockSling);
//Act
constantsServiceProvider.init(bindings);
//Assert
final String actual = constantsServiceProvider.getVar1();
assertThat(actual, is(equalTo(expected)));
}
class TestConstantsService extends ConstantsService {
String var1 = "";
TestConstantsService(String var1) {
this.var1 = var1;
}
#Override
String getVar1() {
return var1;
}
}
}
The entry point here, as you said above, is via the init() method of the WCMUsePojo superclass (as this method is an implementation of the Use.class interface, this test structure also works for testing that via that interface, even if you don't use WCMUsePojo directly.)
*this could be any type of test-double, not necessarily a mock.
You shouldn't create a mock for ConstantsServiceProvider.class if you want to unit-test it. Instead, you should create mocks of its internal objects. So:
Create real instance of ConstantsServiceProvider with new
Mock objects that are returned by getSlingScriptHelper().getService(.) methods. Usually, dependencies are provided (injected) to classes by some container like Spring or simply provided by other classes of your app using setters. In both cases mocks creation is easy.
If your current implementation doesn't allow this - consider refactoring.
You are testing void activate() method which doesn't return anything. So, you should verify calling constantsService.getVar1() method.
I strongly advice you to study Vogella unit-testing tutorial
Here one of possible solution.
The main idea is to have a real object of your class but with overridden getSlingScriptHelper() to return mocked scriptHelper.
I mocked the ConstantsService as well but may be not needed, I don't know your code.
public class ConstantsServiceProviderTest {
#Mock
public SlingScriptHelper scriptHelper;
#Test
public void getVar1ReturnsActivatedValue() throws Exception {
// setup
final String expectedResult = "some value";
// Have a mocked ConstantsService, but if possible have a real instance.
final ConstantsService mockedConstantsService =
Mockito.mock(ConstantsService.class);
Mockito.when(
mockedConstantsService.getVar1())
.thenReturn(expectedResult);
Mockito.when(
scriptHelper.getService(ConstantsService.class))
.thenReturn(mockedConstantsService);
// Have a real instance of your class under testing but with overridden getSlingScriptHelper()
final ConstantsServiceProvider providerWithMockedHelper =
new ConstantsServiceProvider() {
#Override
SlingScriptHelper getSlingScriptHelper() {
return scriptHelper;
}
};
// when
String actualResult = providerWithMockedHelper.getVar1();
// then
assertEquals(expectedResult, actualResult);
}
}

Spring REST docs: How to migrate Rule to JUnit 5

I migrated my Spring tests to JUnit 5, and they work fine. However, I don't know how to migrate #Rule public JUnitRestDocumentation restDocumentation = ....
Any hint is appreciated.
Spring RestDocs 2 introduces a new class : RestDocumentationExtension for JUnit 5. You can use it instead of Rule
#ExtendWith(RestDocumentationExtension.class)
public class JUnit5ExampleTests {
A complete example is available on https://github.com/spring-projects/spring-restdocs/blob/v2.0.0.RELEASE/samples/junit5/src/test/java/com/example/junit5/SampleJUnit5ApplicationTests.java
The extension is documented on https://github.com/spring-projects/spring-restdocs/blob/master/docs/src/docs/asciidoc/getting-started.adoc#setting-up-your-junit-5-tests
Spring RestDocs 2 requires Spring 5 and JDK 8
Until the issue is officially resolved, I was able to get it working with a JUnit 5 extension (below).
Using that extension, I modified my test class thusly:
#ExtendWith(RestDocsExtension.class)
and
#BeforeEach
void setUp(WebApplicationContext wac, ManualRestDocumentation restDocumentation) throws Exception {
Here is the Extension.
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ContainerExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.junit.jupiter.api.extension.TestExtensionContext;
import org.springframework.restdocs.ManualRestDocumentation;
import java.lang.reflect.Method;
import java.util.Optional;
public class RestDocsExtension implements BeforeAllCallback, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final String REST_DOC_STORE_KEY = "restDocumentation";
private ManualRestDocumentation restDocumentation;
#Override
public void beforeAll(ContainerExtensionContext context) throws Exception {
if (restDocumentation == null) {
restDocumentation = new ManualRestDocumentation("target/generated-snippets");
getStore(context).put(REST_DOC_STORE_KEY, restDocumentation);
}
}
#Override
public void beforeEach(TestExtensionContext context) throws Exception {
Optional<Class<?>> testClass = context.getTestClass();
Optional<Method> methodNameOpt = context.getTestMethod();
if (testClass.isPresent() && methodNameOpt.isPresent()) {
getDoc(context).beforeTest(testClass.get().getClass(), methodNameOpt.get().getName());
} else {
throw new Exception("TestExtensionContext with no class or method. wat");
}
}
#Override
public void afterEach(TestExtensionContext context) throws Exception {
getDoc(context).afterTest();
}
#Override
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return parameterContext.getParameter().getType() == ManualRestDocumentation.class;
}
#Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
return getDoc(extensionContext);
}
private ManualRestDocumentation getDoc(ExtensionContext context) {
return (ManualRestDocumentation) getStore(context).get(REST_DOC_STORE_KEY);
}
private ExtensionContext.Store getStore(ExtensionContext context) {
return context.getStore(ExtensionContext.Namespace.DEFAULT);
}
}

Openejb rest integration tests with exception mappers

I'm writing some integration tests towards my jax-rs service where I have a set of exception mappers. So, when performing a given request I expect a certain response code based on the exception mapper. The problem is that I cannot get the exception mappers to be invoked when running in this environment.
My service which should throw a logicalexception in my test:
#Stateless
#Path("/baseCustomer")
public class BaseCustomerService {
#EJB //this one gets mocked in the unittest
private BaseCustomerManagerBean customerManager;
#POST
#Path("crud")
#Consumes({MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML})
public Hkunde createCustomer(Hkunde newCustomer) throws LogicalException {
//throws exception according to mocking
return customerManager.createCustomer(newCustomer);
}
And the exception mapper:
#Provider
public class LogicalExceptionMapper implements ExceptionMapper<LogicalException> {
#Override
public Response toResponse(LogicalException exception) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
I set up my tests like this:
#Mock
private BaseCustomerManagerBean baseCustomerManager;
private HttpClient httpClient;
private BaseCustomerServiceClient client;
#Configuration
public Properties config() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.RemoteInitialContextFactory");
properties.setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
properties.setProperty(DeploymentFilterable.CLASSPATH_INCLUDE, LogicalExceptionMapper.class.getName());
properties.setProperty("openejb.jaxrs.providers.auto", "true");
properties.setProperty("openejb.servicemanager.enabled", "true");
return properties;
}
#MockInjector
public Class<?> mockitoInjector() {
return MockitoInjector.class;
}
#Module
public EjbModule createModule() throws Exception {
final StatelessBean bean = (StatelessBean) new StatelessBean(BaseCustomerService.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
#Module
public Class[] exceptionMappers() {
return new Class[]{LogicalExceptionMapper.class};
}
#Before
public void setup() {
ServiceHost serviceHost = new ServiceHost("http://localhost:4204/BaseCustomerServiceTest");
httpClient = new HttpClient(serviceHost);
client = new BaseCustomerServiceClient(httpClient);
}
#Test
public void createCustomer_givenLogicalException_expectsLogicalException() throws LogicalException {
Hkunde expected = new Hkunde(true);
when(baseCustomerManager.createCustomer(expected)).thenThrow(new LogicalException("mock"));
try {
client.createCustomer(expected);
fail("Expected LogicalException");
} catch (LogicalException ex) {
}
verify(baseCustomerManager).createCustomer(expected);
}
So when I execute the test, my client will read the response code from the response and throw an exception based on this code.
The problem is that the exception mapper is never invoked, and I always receive a 500 internal server error, instead of the "forbidden" response. I'm guessing I need to add some more info when setting up the ejbjar or something like that.
Thanks!
This example http://svn.apache.org/repos/asf/openejb/trunk/openejb/examples/rest-applicationcomposer/src/test/java/org/superbiz/composed/rest/GreetingServiceTest.java (via http://rmannibucau.wordpress.com/2012/09/13/use-mockito-with-openejb/ ;-)) shows exactly what you want.
Add the following after openejbJar.addEjbDeployment(... and it should work.
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", LogicalExceptionMapper.class.getName());
Here is a minimal working example (using openejb-cxf-rs 4.5.0 and openejb-core 4.5.0):
import java.util.Properties;
import javax.ejb.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.openejb.OpenEjbContainer;
import org.apache.openejb.config.EjbModule;
import org.apache.openejb.jee.EjbJar;
import org.apache.openejb.jee.StatelessBean;
import org.apache.openejb.jee.oejb3.EjbDeployment;
import org.apache.openejb.jee.oejb3.OpenejbJar;
import org.apache.openejb.junit.ApplicationComposer;
import org.apache.openejb.junit.Configuration;
import org.apache.openejb.junit.Module;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
#RunWith(ApplicationComposer.class)
public class RestWithExceptionMapper {
#Configuration
public Properties configuration() {
return new Properties() {
{
setProperty(OpenEjbContainer.OPENEJB_EMBEDDED_REMOTABLE, Boolean.TRUE.toString());
}
};
}
#Module
public EjbModule app() {
final StatelessBean bean = (StatelessBean) new StatelessBean(MyResource.class).localBean();
bean.setRestService(true);
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(bean);
final OpenejbJar openejbJar = new OpenejbJar();
openejbJar.addEjbDeployment(new EjbDeployment(ejbJar.getEnterpriseBeans()[0]));
final Properties properties = openejbJar.getEjbDeployment().iterator().next().getProperties();
properties.setProperty("cxf.jaxrs.providers", MyExceptionMapper.class.getName());
final EjbModule module = new EjbModule(ejbJar);
module.setOpenejbJar(openejbJar);
return module;
}
public static class FooException extends RuntimeException {
}
public static class MyExceptionMapper implements ExceptionMapper<FooException> {
#Override
public Response toResponse(final FooException t) {
return Response.ok("Objection!").build();
}
}
#Path(value = "/test")
public static class MyResource {
#GET
#Path(value = "/throw")
public String throwException() {
throw new FooException();
}
}
#Test
public void checkServiceWasDeployed() {
assertEquals("Objection!", WebClient.create("http://localhost:4204/RestWithExceptionMapper").path("/test/throw").get(String.class));
}
}