package com.fitaxis.test;
import java.sql.SQLException;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*;
import com.fitaxis.leaderboard.LeaderBoard;
public class LeaderBoardTests {
#Test
public void TestThatDataIsSavedToTheDatabase()
{
LeaderBoard leaderBoard = mock(LeaderBoard.class);
//doNothing().doThrow(new RuntimeException()).when(leaderBoard).saveData();
when(leaderBoard.saveData()).thenReturn(true);
boolean res = leaderBoard.saveData();
verify(leaderBoard).saveData();
Assert.assertTrue(res);
}
}
I have used mockito to mock a class, but when I use code coverage it does not detect that the method as been called. Am I doing something wrong? Please help!
It looks like you're mocking out the only call you're making to production code.
In other words, your test says:
When I call saveData(), fake the result to return true
Now call saveData() - yay, the result was true!
None of your production code is being calls at all, as far as I can see.
The point of mocking is to mock out dependencies from your production class, or (sometimes, though I prefer not to) to mock out some methods of your production class that the code you're actually testing will call.
You should probably be mocking out the dependencies of Leaderboard rather than Leaderboard itself. If you must mock out saveData(), you should be testing the methods that call saveData()... check that they save the right data, that they act correctly when saveData() returns false, etc.
if i understand your question correctly :
because you are mocking LeaderBoard. that means that you are not testing it.
if you want to test LeaderBoard, you should test the actual class not the mocked one.
let say you want to test class A but this class depends on B and B is a bit difficult to instantiate in testing environment(for any reason). in such cases you can mock B.
but here is your case you are mocking class A itself. that means you are not testing anything.
add runner class as MockitoJUnitRunner, please refer the below sample code
import org.mockito.junit.MockitoJUnitRunner
#RunWith(MockitoJUnitRunner.class)
public class MockitTesterClass{
#Mock
private TestService testServiceMock;
}
now the code coverage will increase
Related
Is there a way to mock a Repository without the #RunWith(MockitoJUnitRunner) annotation on the class?
I have a test that passed without the annotation but fails with it. Without it, my repo test doesn't work. It's a catch 22.
When I use that annotation, my when() methods in my tests no longer stub behavior, mocks do nothing, and despite setting break ppoints and those breakpoints being hit (indicating the line/method is run), verify(..., times(x)) statements say the mocked object never interacted with that method. I've been pulling my hair out on why using the #RunWith(MockitoJUnitRunner) annotation would make the most simple parts of Mockito not work.
I can't find any threads asking about this but maybe someone knows better keywords to use. Does this sound like a known issue?
Here is my test:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
// toggling this below annotation is the source of grief.
//#RunWith(MockitoJUnitRunner.class)
public class LoadEditEntityChangeLogServiceImplTest {
#InjectMocks
private ServiceImpl serviceMock;
#Mock
private EditStepRepository editStepRepository;
#Mock
private EditMapper editMapper;
#Before
public void init() {
initMocks(this);
}
#Test // when the RunWith is commented out, this passes. When it is not, the test fails the verify assert.
public void mapEditEntityFromAction_Test() {
EditDTO editDTO = Mockito.mock(EditDTO.class);
when(editDTO.getSysNum()).thenReturn((long)7334);
EditEntity editEntity = new editEntity();
editEntity.setSysNum(editDTO.getSysNum());
when(editMapper.mapToEntity(eq(editDTO))).thenReturn(editEntity);
editEntity response = serviceMock.mapEditEntityFromAction(editDTO);
verify(loadEditMapper, times(1)).mapToEntity(eq(loadEventDTO));
assertEquals(loadEventDTO.getSystemNumber(), response.getSystemNumber());
}
#Test // this will fail without the #RunWith as the mocked repo will be null and throws NullPointerException when used.
public void updateConvertedEventSegment_Test() {
EditEntity editEntity = new EditEntity();
EditStepEntity editStepEntity = new EditStepEntity();
editEntity.setEditStep(editStepEntity);
doReturn(editStepEntity).when(editStepRepository).save(any());
serviceMock.updateEditStep(editEntity);
verify(editEntity, times(1)).getEditStep();
verify(editStepRepository, times(1)).save(eq(editStepEntity));
}
}
You should understand what does this runner actually do:
Basically it allows injecting mocks (prepared by mockito with Mockito.mock(...) ) into the test fields annotated with #Mock. In the question, since you've commented out the runner, all these fields will be null.
When you annotated something with #InjectMocks - it will inject the mocks into the fields of the object of type of the annotated reference.
One more point to clarify here: MockitoAnnotations.initMocks(this) will do the same as the "runner" so no need to include both (you should use initMocks if you can't use the runner for some reason, like if there is already another runner that must be used)
Now, you ask:
Is there a way to mock a Repository without the #RunWith(MockitoJUnitRunner) annotation on the class?
The answer is - yes, you can, in fact you don't have to use the runner, sometimes its more convenient.
So, assuming you really use this runner, the real question is what exactly do you mean by "my repository doesn't work". Does this mean that there exists a reference in the service that points of this repository and its null?
Does it mean that there is a mock of repository but when you execute the call "under the test" the mock is different?
You don't show it in the code, but I assume you have some like this:
public class ServiceImpl {
private final EditStepRepository editStepRepository;
public ServiceImpl(EditStepRepository editStepRepository) {
this.editStepRepository = editStepRepository;
}
...
}
But if so, once you create a mock (and indeed there should be a mock injected into the ServiceImpl class (check this out with debugger or something), There should be expectatations specified on the repository, usually there should be code like this in the test:
Mockito.when(editStepRepository.doSomething(...)).thenReturn(...)
You haven't placed any of these lines, that why it doesn't work.
But all-in-all since the question contains many uncertain technicalities like this, I can't tell more than that other that speculating...
I have a unit test that is failing and I'm unsure why. I want to be able to see all invocations on the mock that occur in the System Under Test. This is not the behavior that I want for all tests always, simply for a test that I need to quickly tweak to be able to figure out what's wrong.
However, it seems kind of like a hack. Is it possible to do this natively in Mockito, without having to use Thread.currentThread().getStackTrace()?
This is not preferred, because the stack trace includes all the other invocations used internally by Mockito.
This feature is builtin since Mockito 1.9.5. Just use
mock(ClassToMock.class, withSettings().verboseLogging())
From Mockito 2.2.6 you can inspect a mock with MockingDetails Mockito.mockingDetails(Object mockToInspect).
You can either dig into the MockingDetails properties by invoking : getMock(), getStubbings(), getInvocations() and so for ... or simply use the printInvocations() method that returns :
a printing-friendly list of the invocations that occurred with the mock
object. Additionally, this method prints stubbing information,
including unused stubbings. For more information about unused stubbing
detection see MockitoHint.
For example with JUnit 5 :
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.Mock;
import org.mockito.Mockito;
import static org.mockito.Mockito.*;
#ExtendWith(MockitoExtension.class)
public class FooTest {
Foo foo;
#Mock
Bar bar;
#Test
void doThat() throws Exception {
Mockito.when(bar.getValue())
.thenReturn(1000L);
// ACTION
foo.doThat();
// ASSERTION
// ...
// add that to debug the bar mock
System.out.println(mockingDetails(bar).printInvocations());
}
}
And you get an output such as :
[Mockito] Interactions of: Mock for Bar, hashCode: 962287291
1. bar.getValue();
-> at Foo.doThat() (Foo.java:15)
- stubbed -> at FooTest.doThat(FooTest.java:18)
Note that the classes with a referenced line in the output are links to your source code/test class. Very practical.
For some reason I fail to follow a pretty straight forward PowerMock example.
I included powermock-mockito-1.5.1-full in my classpath, and I try to test a public final method (following this example).
For some reason I am not able to make the import to the PowerMock class.
import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cleancode.lifesaver.camera.*;
#RunWith(PowerMockRunner.class)
#PrepareForTest(android.hardware.Camera.class)
public class CameraTests {
private android.hardware.Camera _cameraMock;
#Before
public void setUp() {
_cameraMock = PowerMockito.mock(android.hardware.Camera.class);
}
#Test
public void releaseCamera() {
ICamera camera = new Camera(_cameraMock);
// Compile error: PowerMock can't be resolved
PowerMock.replay(_cameraMock);
// I also tried PowerMockito.replay(_cameraMock) but that also doesn't exist.
camera.release();
Mockito.verify(_cameraMock).release();
}
}
As the comment explains, the PowerMock class can't be imported from the power mock jar.
It feels like a silly question, but I really can't find anything on the internet.
Where should I be able to find the static class PowerMock? I also used Java Decompile to search the powermock library, no hits on powermock / replay.
The example you are following PowerMock.replay(_cameraMock); is using EasyMock, while you seem to be wanting Mockito. Take a look at this tutorial for mockito & power mock
I suggest you not to create your mock in your setUp() (Before) method, because a mock is very complicated, for example you can tell it exactly how many time it should expect a method is called, if you declare a "general" mock for all your tests it's very difficult to control this behaviour.
maybe (without the code I can only guess) you want that your android.hardware.Camera is called inside your Camera.release() method, am I right? so I whould do like this:
The method you are trying to mock is not static, it's a normal final method. You can try to do this:
android.hardware.Camera mock = PowerMock.createMock(android.hardware.Camera.class);
PowerMock.expect(mock.release());
PowerMock.replay();
ICamera camera = new Camera(mock);
camera.release();
PowerMock.verify(mock);
if inside camera.relase() is not called exactly once the android.hardware.Camera.release() method the test fails.
This seems like it shouldn't compile and run as Object does not have a fail() method. At compile time is something funky happening? (I am using NetBeans):
import static org.junit.Assert.*;
import org.junit.Test;
public class Test {
#Test
public void hello() {
fail();
}
}
Regards,
Guido
Your import static line imports all static members of the Assert class into the static namespace of your compilation unit. The fail() call refers to Assert.fail().
The confusion you are experiencing regarding where fail() is defined is precisely why I don't usually recommend using import static. In my own code, I usually import the class and use it to invoke the static methods:
import org.junit.Assert;
import org.junit.Test;
public class Test {
#Test
public void hello() {
Assert.fail();
}
}
Much more readable.
However, as JB Nizet points out, it is fairly common practice to use import static for JUnit's assertions; when you write and read enough JUnit tests, knowing where the assertion methods come from will become second nature.
This is perfectly correct and it will run and compile - I already checked using eclipse.
The reason is the static import:
import static org.junit.Assert.*;
that adds all the static fields or methods from the org.junit.Assert class - hence including fail() method.
Nevertheless a problem that might occur is the fact that the name of your test class is the same as the name of the annotation
#Test
hence it will generate an error:
The import org.junit.Test conflicts with a type defined in the same file
This error is coming because your classname and annotation name are same(Test).Change your class name to 'Test1' or other than Test.
We are using EasyMock for JUnit testing of our Java application inside Eclipse. Using code similar to the below, we found a strange behaviour: when running the full test suite (Eclipse Project -> Run as -> JUnit) one test case fails reproducibly. However when running it standalone it works fine.
Interface:
package de.zefiro.java.easymockexception;
public interface Fruit {
public String fall();
}
Test class:
package de.zefiro.java.easymockexception;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
public class Newton {
private static final Fruit APPLE = createNiceMock(Fruit.class);
#BeforeClass
public static void SetUpClass() {
expect(APPLE.fall()).andReturn("Targeting HEAD").anyTimes();
replay(APPLE);
}
#Test
public void testGravity() {
String target = APPLE.fall();
assertTrue("Missed", target.contains("HEAD"));
}
}
Test suite:
package de.zefiro.java.easymockexception;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
#RunWith(value = Suite.class)
#SuiteClasses( { Newton.class } )
public class ScienceTests { }
Running all tests on the Eclipse project - i.e. both ScienceTests calling Newton as well as Newton directly - produced this exception in the above small example:
java.lang.IllegalStateException: no last call on a mock available
at org.easymock.Easymock.getControlForLastCall(EasyMock.java:175)
There is a similar question here, but it seems to be unrelated.
And in our real testing code (bigger class, but the main actors are identical to the stripped-down example) this exception:
java.lang.IllegalStateException: void method cannot return a value
at org.easymock.internal.MocksControl.andReturn(MocksControl.java:101)
I didn't find an answer either on Google nor here on StackOverflow, but found out myself now, so in the spirit of answering your own questions I'll post my findings below. Worth mentioning is also this post I found, even though it didn't help me in this particular case: EasyMock Cause-Effect Exception Mapping
Putting Breakpoints on the line initializing APPLE and inside SetUpClass() I noticed that APPLE is called exactly once, while SetUpClass is called twice. This is due to the fact that the first reference to Newton creates the class and runs the static initializers, however JUnit calls #BeforeClass for each run of the test. In this case the test is run twice: once as a normal call and once as part of the test suite.
I didn't want to change the logic (i.e. don't use static), but instead changed the static #BeforeClass to a static initialization block:
public class Newton {
[...]
static {
expect(APPLE.fall()).andReturn("Targeting HEAD").anyTimes();
replay(APPLE);
}
// no #BeforeClass needed anymore
[...]
}
This solved the issue in both my simplified test above and in our real test coding.
I didn't find out what the difference was that triggered the different exception message, but the findings were the same - new was called only once, #BeforeClass was called multiple times and failed on the second run. The fix also worked on both.