I am new to JUNIT testing but tried a lot to test the class UserProfileService. Please help or suggest possible errors I am doing:
#Path("/update")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response updateProfile(final PartyProfile partyProfile) {
final ProxyResponse response = new ProxyResponse();
try {
final boolean isUpdated = partyProfileDao.updateProfile(partyProfile);
if (isUpdated) {
LOGGER.info("update Request completed successfully");
setSuccessResponse(response, "Request completed successfully");
try{
final String trailId = partyProfileDao.fetchPartyTrial(partyProfile.getPartyId());
activityPush(trailId, partyProfile.getPartyId());
}catch(Exception ex){
ex.printStackTrace();
LOGGER.error("Exception while triggering segmentation++");
}
} else {
LOGGER.info("Unable to update profile");
setErrorResponse(response, "PRFUPDT500", "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
} catch (Exception exc) {
LOGGER.error("Unable to update profile:" + exc.getMessage());
setInternalErrorResponse(exc, response, "Unable to update profile");
return Response.ok(response).header("valid", FLAG_FALSE).build();
}
return Response.ok(response).build();
}
I have written following JUNIT test:
public class PartyProfileServiceTest {
private PartyProfileDAO partyDAO;
private PartyProfileService partyService;
#Before
public void setUp() throws Exception {
partyDAO = EasyMock.createMock(PartyProfileDAO.class);
partyService = EasyMock.createMock(PartyProfileService.class);
partyService.setUserProfileDAO(partyDAO);
}
#Test
public void testUpdateValidProfile() throws Exception {
System.out.println("inside junit");
PartyProfile partyProfile = new PartyProfile();
partyProfile.setFirstName("adsfsdfg");
partyProfile.setAddress("adressabc");
partyProfile.setPartyId("dfdf");
partyProfile.getSalutation();
partyProfile.setMiddleName("asfsaf");
partyProfile.setLastName("easdsddff");
partyProfile.setNickName("srb");
partyProfile.setGender("m");
partyProfile.setUpdateDate("sdd");
partyProfile.setEducation("srg");
partyProfile.setInsurance("sg");
partyProfile.setState("sdfg");
partyProfile.setSiteId("fdg");
partyProfile.setRandomNo("feddg");
partyProfile.setPartyId("56666");
EasyMock.expect(partyDAO.updateProfile(partyProfile)).andReturn(true);
EasyMock.expect(partyDAO.fetchPartyTrial("validPartyId")).andReturn("pass");
EasyMock.replay(partyDAO);
EasyMock.expect(partyService.activityPush("pass", "validPartyId")).andReturn(true);
EasyMock.replay(partyService);
Response response = partyService.updateProfile(partyProfile);
ProxyResponse proxyResponse = (ProxyResponse) response.getEntity();
Assert.assertSame("Unable to update profile", proxyResponse.getData().get("message"));
}
}
Error:
java.lang.AssertionError:
Unexpected method call PartyProfileService.updateProfile(com.cts.vcoach.proxy.model.PartyProfile#11e170c):
PartyProfileService.setUserProfileDAO(EasyMock for class com.cts.vcoach.proxy.dao.PartyProfileDAO): expected: 1, actual: 0
PartyProfileService.activityPush("pass", "validPartyId"): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)
at com.cts.vcoach.proxy.service.rest.PartyProfileService$$EnhancerByCGLIB$$46a1112f.updateProfile(<generated>)
at com.cts.vcoach.proxy.service.rest.PartyProfileServiceTest.testUpdateValidProfile(PartyProfileServiceTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:44)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
You're trying to test the class PartyProfileService. So you should create an instance of this class, and call its methods in your test. But that's not what you're doing. You're creating a mock instance of this class:
partyService = EasyMock.createMock(PartyProfileService.class);
Replace this line by
partyService = new PartyProfileService();
If you need to partially mock the service, i.e. mock the method activityPush(), but not the other ethods, then see the documentation for how to do that:
ToMock mock = createMockBuilder(ToMock.class)
.addMockedMethod("mockedMethod")
.createMock();
Related
Hi So I'm new to Junit and Mockito, so please bare with some misconception/mistakes that Ive made. I have a springbott service that I wanted to test and I want to mock a method call that is being made in one of the methods that I am testing but It will not work for some reason. I used both when(xxx.method(anyArgs)).return(someData) as well as doReturn(someData).when(xxx).method(anyArgs); But I still get the same type of error: InvalidUseOfMatchersException. I mock the service layer but I can not figure out what causes the issue.
The Exact Stack Trace:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
My Service Layer Code:
// imports here
#Service
#AllArgsConstructor
public class EventServiceImpl implements EventService {
private EventModelRepo eventModelRepo;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
// methods that dont matter
public int createAPost(EventDetails eventDetails) {
//Some where here the isOwner(STRING) is called
}
public static void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
public boolean isOwner(String Owner) {
try {
getRequest("http://localhost:9024/login/isAuth?Username=" + Owner);
} catch (HttpResponseException e) {
System.out.println("Error: " + e.getContent());
return false;
} catch (IOException e) {
System.out.println("Could Not Connect To Site/Make Said Request. \nAre You In Testing? \nIf So This Is Ok.");
}
return true;
}
}
And here is my Junit:
//imports
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
// mocking the HTTP Call in isOwner()
HttpTransport transport = new MockHttpTransport();
HttpRequest request = null;
try {
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpResponse response = request.execute();
} catch (IOException e) {
e.printStackTrace();
}
EventDetails eventDetails = new EventDetails("username1", "resturant", "idk", "location.", ".com",
"no", "no p", "spring", "fair", "tes");
//If Owner Isn't Validate As Owner/Signed In
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
//doReturn(false).when(eventServiceImpl).isOwner(anyString());
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
So turns out one of the commentors on my post was correct. You can not mock a call from a #InjectMocks. But if you want to you need to have another annotation added to it. That annotation being #Spy. This annotation should be added in the test class, above the #InjectMocks.
More can be found here
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#Spy
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
I can't work out how to setup the expectation of a call to a mock class. Here is the JUnit test:
public class AfkTest extends TestCase {
private AfkPlayerManager manager;
private Player player;
private Set<AfkPlayer> afkPlayers;
public void setUp() throws Exception {
super.setUp();
manager = new AfkPlayerManager();
player = EasyMock.createMock(Player.class);
afkPlayers = new HashSet<AfkPlayer>();
}
public void tearDown() {
}
public void testNotifyOfAfkPlayerSuccess() {
AfkPlayer afkPlayer = new AfkPlayer();
afkPlayer.setPlayer(player);
afkPlayer.setReason("TEST REASON");
afkPlayers.add(afkPlayer);
List<Player> onlinePlayers = new ArrayList<Player>();
onlinePlayers.add(player);
onlinePlayers.add(player);
EasyMock.expect(player.getDisplayName()).andReturn("TEST PLAYER");
player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]");
EasyMock.expectLastCall().times(1);
//activate the mock
EasyMock.replay(player);
assertTrue(manager.notifyOfAfkPlayer(onlinePlayers, afkPlayer));
//verify call to sendMessage is made or not
EasyMock.verify(player);
}
}
And the method that I am testing:
public class AfkPlayerManager implements Manager {
public boolean notifyOfAfkPlayer(Collection<Player> onlinePlayers, AfkPlayer afkPlayer) {
if (afkPlayer == null) {
return false;
}
String message = ChatColor.BLUE + afkPlayer.getPlayer().getDisplayName();
message += ChatColor.AQUA + " is AFK.";
if (afkPlayer.getReason().length() > 0) {
message += " [" + afkPlayer.getReason() + "]";
}
if (onlinePlayers != null && onlinePlayers.size() > 1) {
int notified = 0;
for (Player onlinePlayer : onlinePlayers) {
onlinePlayer.sendMessage(message);
notified++;
}
if (notified > 0) {
return true;
}
}
return false;
}
}
Why is this giving me the AssertionError:
java.lang.AssertionError: Unexpected method call
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"):
Player.sendMessage("§9TEST PLAYER§b is AFK. [TEST REASON]"): expected: 1, actual: 0 at
org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at
org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at com.sun.proxy.$Proxy3.sendMessage(Unknown Source) at
crm.afk.AfkPlayerManager.notifyOfAfkPlayer(AfkPlayerManager.java:33)
at crm.test.AfkTest.testNotifyOfAfkPlayerSuccess(AfkTest.java:84) at
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
junit.framework.TestCase.runTest(TestCase.java:176) at
junit.framework.TestCase.runBare(TestCase.java:141) at
junit.framework.TestResult$1.protect(TestResult.java:122) at
junit.framework.TestResult.runProtected(TestResult.java:142) at
junit.framework.TestResult.run(TestResult.java:125) at
junit.framework.TestCase.run(TestCase.java:129) at
junit.framework.TestSuite.runTest(TestSuite.java:252) at
junit.framework.TestSuite.run(TestSuite.java:247) at
org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
The expected and actual are different.
Expected: §9TEST PLAYER§b is AFK. [TEST REASON]
Actual: §9TEST PLAYER§b is AFK. [TEST REASON]
The  at the beginning is missing. So it fails as it should.
Following is the code that I am trying to use for mocking the javax.mail.Message. The message instance is passed to another method call getContent(Message message) which returns String instance. The code for this method is also given below.
Calendar cal = Calendar.getInstance();
mockery.setImposteriser(ClassImposteriser.INSTANCE);
final Message[] messages;
List<Message> ms = new ArrayList<Message>();
ms.add(mockery.mock(Message.class, "m1"));
ms.add(mockery.mock(Message.class, "m3"));
messages = ms.toArray(new Message[10]);
mockery.checking(new Expectations() {
{
allowing(messages[0]).getContentType();
will(returnValue("text/plain"));
allowing(messages[1]).getContentType();
will(returnValue("html"));
}
});
String contentM1 = getPasswordResetJob().getContent(messages[0]);
assertEquals("text/plain", contentM1);
getContent() method code :
log.info("Message content type::" + message.getContentType());
if (message.getContentType().contains("text/plain;")
&& message.getContent() != null) {
content = message.getContent().toString();
} else {
content = getMultipartContent(message);
}
return content;
The test case fails with this message.
unexpected invocation: m1.getContent()
expectations:
allowed, already invoked 2 times: m1.getContentType(); returns "text/plain"
allowed, never invoked: m3.getContentType(); returns "html"
at org.jmock.internal.InvocationDispatcher.dispatch(InvocationDispatcher.java:56)
at org.jmock.Mockery.dispatch(Mockery.java:204)
at org.jmock.Mockery.access$000(Mockery.java:37)
at org.jmock.Mockery$MockObject.invoke(Mockery.java:246)
at org.jmock.internal.InvocationDiverter.invoke(InvocationDiverter.java:27)
at org.jmock.internal.ProxiedObjectIdentity.invoke(ProxiedObjectIdentity.java:36)
at org.jmock.lib.legacy.ClassImposteriser$4.invoke(ClassImposteriser.java:137)
at $javax.mail.Message$$EnhancerByCGLIB$$8abdf7fe.getContent(<generated>)
at com.abc.scheduler.AbstractSchedulerJob.getMultipartContent(AbstractSchedulerJob.java:222)
at com.abc.scheduler.AbstractSchedulerJob.getContent(AbstractSchedulerJob.java:151)
at com.abc.scheduler.PasswordResetJobTest.testCreateAlertList(PasswordResetJobTest.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:168)
at junit.framework.TestCase.runBare(TestCase.java:134)
at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:69)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:79)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
It seems that you didn't define the expectation for m1.getContent()
if (message.getContentType().contains("text/plain;")
&& message.getContent() != null) {
content = message.getContent().toString();//message.getContent() is not defined
I would like to mock the make a JUnit test of the following method toXml:
void toXml(Object obj){
ByteArrayOutputStream out = null;
try{
JAXBContext ctx = getContext(obj.getClass());
Marshaller marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setAttachmentMarshaller(new AttachmentMarshallerImpl());
out = new ByteArrayOutputStream();
marshaller.marshal( obj, out );
}catch( JAXBException e ){
throw new RuntimeException("Problem in parsing", e);
}
}
I have tried the following:
#Test
public void testToXml() throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
SystemPointDto systemPointDto = new SystemPointDto();
verify((marshaller), atLeast(1)).marshal(systemPointDto, out);
}
However I am getting a NullPointerException when I run the test. I am a newbie in testing probably the answer is very easy. Could you please advice? Thanks in advance.
EDIT:
The mocking code as asked in the comments is:
#Mock
AttachmentMarshallerImpl attachmentMarshaller;
#InjectMocks
Marshaller marshaller;
And this is the stack trace:
initMocks(TestingIfTheMarshalGetsCalledWithoutExceptionTest.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
Caused by: org.mockito.exceptions.base.MockitoException: the type 'Marshaller' is an interface.
... 32 more
In your Method you get the Marshaller from a JAXBContext. To use your mock Marshaller, your need a JAXBContext that returns the mock when createMarshaller is called.
assuming the following class under test:
public class XmlMarshaller {
private JAXBContextFactory contextFactory;
public XmlMarshaller(JAXBContextFactory contextFactory) {
this.contextFactory = contextFactory;
}
private JAXBContext getContext(Class<?> type) {
return contextFactory.get(type);
}
public void toXml(Object obj){
// ... your code
}
}
your test setup would need to look like this:
public class XmlMarshallerTest {
#Mock
JAXBContext ctx;
#Mock
Marshaller marshaller;
#Mock
JAXBContextFactory factory;
#InjectMocks
XmlMarshaller classUnderTest;
#Before
public void setup() {
MockitoAnnotations.initMocks(this); // creates mocks and injects the as needed into the classUnderTest
when(ctx.createMarshaller()).thenReturn(marshaller);
}
#Test
public void toXmlCallsJAXBMarshaller() {
when(factory.get(SystemPointDto.class)).thenReturn(ctx);
SystemPointDto systemPointDto = new SystemPointDto();
classUnderTest.toXml(systemPointDto);
verify(marshaller).marshal(eq(systemPointDto), any(ByteArrayOutputStream.class));
}
}
I am new to Java so please bear with me. I am using Java and Selenium to test a web application.
Basically, what I am trying to do is read in data from a cvs file in Class Main and then once I have the data, calling the login method in another class passing through the username and password variables read from the cvs file.
Maybe I am calling the function incorrectly, I am not sure but the line I get the NPE on is
driver.findElement(By.name("j_username")).clear();
in the Login function in the LiveProcess Class. If I move the Login method into the Main class I do not have any problems. I would appreciate any help you can give me - thanks in advance!
Main Class
public void ReadTestData() throws Exception
{
//Open CVS File and extract the contents
try {
CsvReader testData = new CsvReader("C:\\Selenium\\TestData.csv");
testData.readHeaders();
while (testData.readRecord())
{
String testType = testData.get("TestType");
String testName = testData.get("TestName");
String testDescription = testData.get("Description");
String userName = testData.get("UserName");
String password = testData.get("Password");
String firstName = testData.get("FirstName");
String lastName = testData.get("LastName");
int testTypeInt = Integer.parseInt(testType);
RunTests();
}
testData.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void RunTests() throws Exception
{
switch(testTypeInt)
{
case 1:
LiveProcessTests method = new LiveProcessTests();
method.Login(userName, password);
break;
default:
break;
}
}
LiveProcess Class
public void Login(String uName, String pWord) throws Exception
{
System.out.println("USER NAME: " + uName);
System.out.println("USER NAME: " + pWord);
driver.findElement(By.name("j_username")).clear();
driver.findElement(By.name("j_username")).click();
driver.findElement(By.name("j_username")).sendKeys(uName);
}
Actual Error:
java.lang.NullPointerException
at com.testscripts.LiveProcessTests.Login(LiveProcessTests.java:31)
at com.testscripts.Main.RunTests(Main.java:97)
at com.testscripts.Main.ReadTestData(Main.java:75)
at com.testscripts.Main.InitializeTests(Main.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Most likely driver.findElement(By.name("j_username")) is null which means it is unable to find the element you are searching.
Make sure the name is correct and that the element exist. Also You have to initialise the driver but it is not seen in your code
Example:
if (driver.findElement(By.name("j_username")) != null ) {
driver.findElement(By.name("j_username")).clear();
driver.findElement(By.name("j_username")).click();
driver.findElement(By.name("j_username")).sendKeys(uName);
}
UPDATE:
You should initialize your driver. Something like:
driver = new FirefoxDriver();