mocking a constructor to see if it throws an exception - java

Java 8
I have the following constructor I want to test using Mockito.
I want the test to throw an exception if a null is passed for the repository.
public PresenterImp(#Nonnull IRepository repository, IScheduler scheduler) {
super(schedulerFactory);
this.repository = Preconditions.checkNotNull(repository);
}
What would be the best way to do this? As my presenter is not a mock so I can’t use a when..
In my setup I do the following:
#Before
public void setup() throws Exception {
repository = Mockito.mock(IRepository.class);
iScheduler = Mockito.mock(IScheduler.class);
viewContract = Mockito.mock(ViewContract.class);
presenter = new PresenterImp(repository, iScheduler);
optInNotificationPresenter.attachView(viewContract);
}
Many thanks for any suggestions

Can do it as:
#Test(expected=NullPointerException.class )
public void testNullCheck() throws Exception
new PresenterImp(null, mock);
}

Related

AEM JUnit java.lang.NullPointerException

I need to create a Junit test for a class in an AEM project and I'm having NullPointerException problems:
I create the ClassTestImpl
#ExtendWith({AemContextExtension.class, MockitoExtension.class})
class TestImpl {
private final AemContext ctx = new AemContext();
#Mock
private Test test;
#Mock
private ModelFactory modelFactory;
#BeforeEach
void setUp() throws Exception {
ctx.addModelsForClasses(TestImpl.class);
ctx.load().json("/com/project/core/models/adobe/TestImplTest.json","/content");
lenient().when(modelFactory.getModelFromWrappedRequest(eq(ctx.request()),
any(Resource.class), eq(Test.class)))
.thenReturn(test);
}
#Test
void testGetText() {
final String expected = "textTEST";
ctx.currentResource("/content/text");
Test test = ctx.request().adaptTo(Test.class);
String actual = test.getText();
assertEquals(expected,actual);
}
and the json structure:
"text": {
"jcr:primaryType": "nt:unstructured",
"sling:resourceType": "project/components/core/title",
"text": "textTEST"
}
}
when i Run test i give that result:
#Test
void testGetText() {
final String expected = "titleTEST";
ctx.currentResource("/content/title");
Title title = ctx.request().adaptTo(Title.class);
-->String actual = title[NullPointerException].getText();<--
assertEquals(expected,actual);
}
It looks like your model is a null reference. You do try to mock it with MockitoExtension but that's largely superfluous, given that you're also using AemContextExtension and it's probably the cause of the issue.
Null pointers aside, this code doesn't even test anything. Everything is mocked, even the Test class which I understand to be the subject under test.
Also, the parameter you're passing to addModelsForClasses looks like the test class (TestImpl) rather than the class of the Sling Model Test.
Instead of relying on Mockito, let the AEM Mocks library set up all the underlying objects by itself and make sure the class you're testing is the real thing, rather than a mock.
#ExtendWith(AemContextExtension.class)
class TestImpl {
private final AemContext ctx = new AemContext();
#BeforeEach
void setUp() throws Exception {
ctx.addModelsForClasses(Test.class); // Give it the Sling Model
ctx.load().json("/com/project/core/models/adobe/TestImplTest.json","/content");
}
#Test
void testGetText() {
final String expected = "textTEST";
ctx.currentResource("/content/text");
Test test = ctx.request().adaptTo(Test.class); // It'll use the actual class, not a mock this way
String actual = test.getText();
assertEquals(expected,actual);
}
}
See
https://sling.apache.org/documentation/development/sling-mock.html#sling-models-1
https://wcm.io/testing/aem-mock/usage-content-loader-builder.html

Mock an exception object (JUnit/Mockito)

I am facing an issue testing a legacy code using JUnit/Mockito,
my method throws an exception (HandlerException) which is derived from (BaseException) which is part of our infrastructure.
public class HandlerException extends BaseException
My system-under-test is super simple:
public static void parse(JsonElement record) throws HandlerException
{
JsonElement element = record.getAsJsonObject().get(ID_TAG);
if(element == null) {
throw new HandlerException("Failed to find Id ...");
}
...
}
And also the test itself
#Test (expected=HandlerException.class)
public void testParseg() throws HandlerException {
JsonElement jsonElement = new JsonParser().parse("{}");
Parser.parse(jsonElement);
}
The problem is with BaseException. It is a complex class and depends on an initialization. Without initializing it BaseException throws an exception in its constructor :( which in turn causes StackOverflowException.
Is it possible to Mock BaseException or HandlerException in any way to avoid this initialization keeping my test simple?
Looks like the answer to my issue was using PowerMockito
First I use #PrepareForTest on my system-under-test (Parser.class)
#RunWith(PowerMockRunner.class)
#PrepareForTest({Parser.class})
Then I mocked the HandlerExeption class using PowerMockito.whenNew
#Mock
HandlerException handlerExceptionMock;
#Before
public void setup() throws Exception {
PowerMockito.whenNew(HandlerException.class)
.withAnyArguments().thenReturn(handlerExceptionMock);
}
#Test (expected=HandlerException.class)
public void testParseg() throws HandlerException {
JsonElement jsonElement = new JsonParser().parse("{}");
Parser.parse(jsonElement);
}
This way BaseException was not constructed and my test passed without the need to initialize it.
Note: I am aware that this is not the best practice, however, in my case, I had to since I cannot edit BaseException.

mocking nested function is giving NPE

Hi I am getting Null Pointer Exception while trying to write unit test cases
Here is the class detail:
public CreateDraftCampaignResponse createDraftCampaign(CreateDraftCampaignRequest request) throws InvalidInputsException,
DependencyException, UnauthorizedException {
CreateDraftCampaignResponse draftCampaignResponse = null;
try {
DraftCampaignDetails createdDraft = draftCampaignI.createDraftCampaign(ConvertionUtil
.getDraftCampaignDetailsfromCreateDraftRequest(request));
draftCampaignResponse = new CreateDraftCampaignResponse();
draftCampaignResponse.setDraftCampaignId(createdDraft.getDraftId());
}
catch (Exception e) {
log.error("Create Draft Campaign Exception", e);
throw e;
}
return draftCampaignResponse;
}
This is the ConvertionUtil class:
public static DraftCampaignDetails getDraftCampaignDetailsfromCreateDraftRequest(CreateDraftCampaignRequest request) {
DraftCampaignDetails draftCampaign = new DraftCampaignDetails();
DraftCampaignDetailsBase draftCampaignDetailsBase = request
.getDraftCampaignDetailsBase(); (This is giving exception)
draftCampaign.setCampaignBudget(draftCampaignDetailsBase
.getCampaignBudget());
draftCampaign.setCampaignName(draftCampaignDetailsBase
.getCampaignName());
draftCampaign.setDraftCampaignState(draftCampaignDetailsBase
.getDraftCampaignState());
draftCampaign.setCreatedUser(request.getUser());
draftCampaign.setObfuscatedEntityId(request.getObfuscatedEntityId());
draftCampaign.setCampaignInfo(request.getCampaignInfo());
return draftCampaign;
}
Thsi is what I tried:
#Test
public void createDraft_newDraft() {
DraftCampaignActivity draftContoller = new DraftCampaignActivity();
CreateDraftCampaignRequest request = createRequest();
DraftCampaignDetails details = buildDraftDetails();
if(draftCampaignI == null){
System.out.println("sccdscscd");
}
//ConvertionUtil action1 = PowerMockito.mock(ConvertionUtil.class);
//PowerMockito.when(action1.getDraftCampaignDetailsfromCreateDraftRequest(request)).thenReturn(details);
when(util.getDraftCampaignDetailsfromCreateDraftRequest(request)).thenReturn(details);
when(draftCampaignI.createDraftCampaign(details)).thenReturn(details);
CreateDraftCampaignResponse response = new CreateDraftCampaignResponse();
draftContoller.createDraftCampaign(request);
response.setDraftCampaignId(details.getDraftId());
Assert.assertEquals(response.getDraftCampaignId(),"ww");
}
I am getting NPE. I am a novice in Mockito and other framework. Please help!
It doesn't work because you try to mock a static method and you don't do it properly such that it calls the real method which leads to this NPE in your case.
To mock a static method using Powermock, you need to:
Use the #RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
Use the #PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.
Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class.
So in your case, you should have something like:
#RunWith(PowerMockRunner.class)
public class MyTestClass {
#Test
#PrepareForTest(ConvertionUtil.class)
public void createDraft_newDraft() {
...
PowerMockito.mockStatic(ConvertionUtil.class);
PowerMockito.when(
ConvertionUtil.getDraftCampaignDetailsfromCreateDraftRequest(request)
).thenReturn(details);
...
}
More details about How to mock a static method with Powermock.

Unit testing Amazon SWF child workflows

I have a parent workflow (ParentWorkflow) calling a child workflow (ChildWorkflow) and I'm trying to test out the call.
The parent code looks something like this:
public class ParentWorkflow {
private final ChildWorkflowClientFactory childWorkflowClientFactory =
new ChildWorkflowClientFactoryImpl();
public void runWorkflow() {
new TryCatch() {
#Override
protected void doTry() throws Throwable {
Promise<Void> workflowFinished = childWorkflowClient.childWorkflow(x);
...
}
...
}
}
I want to mock out the
childWorkflowClient.childWorkflow(x)
call, however when I am hooking up the unit test I don't appear to have the option to inject the client factory, the unit test code looks like this:
#Rule
public WorkflowTest workflowTest = new WorkflowTest();
#Mock
private Activities mockActivities;
private ParentWorkflowClientFactory workflowFactory
= new ParentWorkflowClientFactoryImpl();
#Before
public void setUp() throws Exception {
// set up mocks
initMocks(this);
workflowTest.addActivitiesImplementation(mockActivities);
workflowTest.addWorkflowImplementationType(ParentWorkflowImpl.class);
workflowTest.addWorkflowImplementationType(ChildWorkflowImpl.class);
I don't appear to be able to pass anything into the workflow implementation classes, is there another way I can mock the child workflow out?
You can test workflow code directly mocking its dependencies without using workflowTest:
/**
* Rule is still needed to initialize asynchronous framework.
*/
#Rule
public WorkflowTest workflowTest = new WorkflowTest();
#Mock
private ActivitiesClient mockActivities;
#Mock
private BWorkflowClientFactory workflowFactory;
#Before
public void setUp() throws Exception {
// set up mocks
initMocks(this);
}
#Test
public void myTest() {
AWorkflowImpl w = new AWorkflowImpl(workflowFactory);
w.execute(); // whatever execute method of the workflow
}
This approach allows testing parts of the workflow encapsulated in other objects instead of the entire workflow.
If for whatever reason (for example you are using other testing framework than JUnit) you don't want to rely on WorkflowTest #Rule asynchronous code can be always executed using AsyncScope:
#Test
public void asyncTest() {
AsyncScope scope = new AsyncScope() {
protected void doAsync() {
// Any asynchronous code
AWorkflowImpl w = new AWorkflowImpl(workflowFactory);
w.execute(); // whatever execute method of the workflow
}
};
scope.eventLoop();
}
EDIT: The below only applies to SpringWorkflowTest; WorkflowTest doesn't have addWorkflowImplementation for some reason.
The correct way to use the WorkflowTest would be to add a mock implementation for the child workflow rather than adding the actual type:
#Rule
public SpringWorkflowTest workflowTest = new SpringWorkflowTest();
#Mock
private Activities mockActivities;
#Mock
private ChildWorkflow childWorkflowMock;
private ParentWorkflowClientFactory workflowFactory
= new ParentWorkflowClientFactoryImpl();
#Before
public void setUp() throws Exception {
// set up mocks
initMocks(this);
workflowTest.addActivitiesImplementation(mockActivities);
workflowTest.addWorkflowImplementationType(ParentWorkflowImpl.class);
workflowTest.addWorkflowImplementation(childWorkflowMock);
...
}
The framework will then call this mock instead of the actual implementation when you use the factory.

Spy a method parameter while testing with Mockito?

Suppose that I have a class like;
public class FooBar {
public int getMethod(List<String> code){
if(code.size() > 100)
throw new Exception;
return 0;
}
}
and I have a test class like this;
#RunWith(PowerMockRunner.class)
#PrepareForTest(FooBar.class)
public class FooBarTest{
FooBar fooBarInstance;
#Before
public void setUp() {
//MockitoAnnotations.initMocks(this);
fooBarInstance = new FooBar();
}
#Test(expected = Exception.class)
public void testGetCorrelationListCodesParameter() {
List<String> codes = Mockito.spy(new ArrayList<String>());
Mockito.doReturn(150).when(codes).size();
fooBarInstance.getMethod(codes);
}
}
How can I make this test method to throw an exception ? I've dealing for hours to do this. Well thanks anyway.
Spying is not needed, mocking is enough. As #David said, also mocking is not needed and not recommended for value object.
Using #Test(expected = Exception.class) has many drawbacks, test can pass when exception is thrown from not expected places. Test is not working but is visible as green.
I prefer BDD style testing with catch-exception.
Reasons for using catch-exceptions
(...) in comparison to the use of try/catch blocks.
The test is more concise and easier to read.
The test cannot be corrupted by a missing assertion. Assume you forgot to type fail() behind the method call that is expected to throw an exception.
(...) in comparison to test runner-specific mechanisms that catch and verify exceptions.
A single test can verify more than one thrown exception.
The test can verify the properties of the thrown exception after the exception is caught.
The test can specify by which method call the exception must be thrown.
The test does not depend on a specific test runner (JUnit4, TestNG).
import static com.googlecode.catchexception.CatchException.caughtException;
import static com.googlecode.catchexception.apis.CatchExceptionAssertJ.*;
public class FooBarTest {
FooBar sut = new FooBar(); // System Under Test
#Test
public void shouldThrowExceptionWhenListHasTooManyElements() {
when(sut).getMethod(listWithSize(150));
then(caughtException()).isInstanceOf(Exception.class);
}
private List<String> listWithSize(int size) {
return new ArrayList<String>(Arrays.asList(new String[size]));
}
}
Full working code for this test: https://gist.github.com/mariuszs/8543918
Not recommended solution with expected and mocking.
#RunWith(MockitoJUnitRunner.class)
public class FooBarTest {
#Mock
List<String> codes;
FooBar fooBarInstance = new FooBar();
#Test(expected = Exception.class)
public void shouldThrowExceptionWhenListHasTooManyElements() throws Exception {
when(codes.size()).thenReturn(150);
fooBarInstance.getMethod(codes);
}
}
A list is a value object. It's not something we should mock. You can write this whole test without mocking anything, if you're prepared to build a list that has a size in excess of 100.
Also, I prefer to use JUnit's ExpectedException mechanism, because it lets you check which line of the test method threw the exception. This is better than passing an argument to the #Test annotation, which only lets you check that the exception was thrown somewhere within the method.
public class FooBarTest {
#Rule
public ExpectedException exceptionRule = ExpectedException.none();
private FooBar toTest = new FooBar();
#Test
public void getMethodThrowsException_whenListHasTooManyElements() {
List<String> listWith101Elements =
new ArrayList<String>(Arrays.asList(new String[101]));
exceptionRule.expect(Exception.class);
toTest.getMethod(listWith101Elements);
}
}

Categories