I have a class where I want to write a junit test for.
This method has no parameters, can this method accordingly?
public class classTobeTested {
#Self
SlingHttpServletRequest request;
static final String keyword = "hello";
public boolean isActive() {
boolean check;
String pathChecker;
pathChecker = (request.getRequestURL()).toString();
check= pathChecker.contains(keyword);
return check;
}
}
This would be the testing class i had in mind
#RunWith(MockitoJUnitRunner.class)
public class testclasstobetested {
#Test
public void TestclassTobeTested() throws Exception{
classTobeTested CTT = new classTobeTested();
assertFalse(CTT.isActive("hello how are you"));
}
}
I know my method does not take a parameter but has strings declared inside the method.
How can i use assertFalse correctly to test a non param method.
Using annotations and Junit4 you can do it like this:
#RunWith(MockitoJUnitRunner.class)
public class testclasstobetested {
#InjectMocks
private classTobeTested CTT;
#Mock
private SlingHttpServletRequest request;
#Test
public void TestclassTobeTested() throws Exception{
when(request.getRequestURL()).thenReturn(new StringBuffer("hello how are you"));
assertFalse(CTT.isActive());
}
}
Related
I try to learn PowerMockitoand write a demo
This the parent class A
public abstract class A {
protected String getRoot(Long id) {
if (id == 0) {
return "root";
}
return "not root";
}
}
And this is the childA
public class ChildA extends A {
private String info;
public String getRootInfo(Long id) {
String rootInfo = getRoot(id);
return rootInfo;
}
private void initRootInfo(String info) {
this.info = info;
}
}
And now i want to mock the method A::initRootInfo,so i write a test case like this
#RunWith(PowerMockRunner.class)
#PrepareForTest({A.class, ChildA.class})
public class ChildATest {
#Spy
#InjectMocks
private ChildA childA = PowerMockito.spy(new ChildA());
#Test
public void getRootInfoUT() throws Exception {
PowerMockito.doNothing().when(childA, "initRootInfo", Mockito.anyString());
String rootInfo = childA.getRootInfo(0L);
Assertions.assertEquals("root", rootInfo);
}
}
When i run the test case, the PowerMockito call the real method initRootInfo, so that i get a little bit confused why the A::initRootInfo will be called really, shouldn't it be mock and replaced by PowerMockito? is there have something wrong i use PowerMockito?
How to mock private method by PowerMockito correctly
I have the below flow
#InjectMocks private ClassToTest classToTest;
#Mock private ClassToInject classToInject;
#Before
public void setup() {
initMocks(this);
}
#Test
public void test() {
Classx mockClassObj = Mockito.mock(Classx.class);
when(classToInject.publicMethod1(mockClassObj)).thenReturn(1000);
classToTest.publicMethod();
}
I want to test public method of classToTest. Now this method makes call to a private method, which I am not mocking. Inside this private method another public method is called, which I want to mock publicMethod1. Instead of the private method making use of value 1000 it is behaving as if the publicMethod1 was not mocked and I get NPE inside the flow of the method somewhere. I tried using #Spy with classToTest and also I am using init.mocks/#RunWith but it fails.
In short it is something like
ClassToTest. publicMethod --> ClassToTest.privateMethod(not mocking) --> ClassToInject.publicMethod1(want to mock)
The class looks like below
class ClassToTest {
#Inject ClassToInject classToInject;
public publicMethod() {
privateMethod();
}
private privateMethod() {
int x = classToInject.publicMethod1();
// use the return value
// throw exception
}
You mock classToInject.publicMethod1(mockClassObj) not classToInject.publicMethod1().
But your code invoked classToInject.publicMethod1();
int x = classToInject.publicMethod1(); // you invoked no parameter method
Check method which you want to invoke.
If You want to invoke classToInject.publicMethod1(), reference this code
#RunWith(MockitoJUnitRunner.class)
public class MockedTest {
#InjectMocks
private ClassToTest classToTest;
#Mock
private ClassToInject classToInject;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void test() {
Mockito.when(classToInject.publicMethod1())
.thenReturn(1000);
classToTest.publicMethod();
}
}
class ClassToTest{
ClassToInject classToInject;
public void publicMethod() {
privateMethod();
}
private int privateMethod() {
int x = classToInject.publicMethod1();
throw new NullPointerException(String.valueOf(x));
}
}
class ClassToInject{
public int publicMethod1() {
return 0;
}
}
The result is 1000 success
java.lang.NullPointerException: 1000
Example of the problem:
class ToBeTested {
private MyResource myResource;
public toBeTested() {
this.myResource = getResource();
}
private MyResource getResource() {
//Creating My Resource using information form a DB
return new MyResource(...);
}
}
I would like to mock the getResource() so I would be able to provide a mock instance of MyResource. All the examples I found on how to mock a private method are based on first creating the ToBeTested instance and then replace the function but since it's being called from the constructor in my case it's to late.
Is it possible to mock the private function to all instances in advance of creating them?
Not directly but, you can suppress and then simulate with power mockito
#RunWith(PowerMockRunner.class)
#PrepareForTest(ToBeTested .class)
public class TestToBeTested{
#before
public void setup(){
suppress(method(ToBeTested.class, "getResource"));
}
#Test
public void testMethod(){
doAnswer(new Answer<Void>() {
#Override
public MyResource answer(InvocationOnMock invocation) throws Throwable {
return new MyResource();
}
}).when(ToBeTested.class, "getResource");
}
ToBeTested mock = mock(ToBeTested.class);
mock.myMethod();
//assert
}
I am newbie in Java world, but it is very hard understand why not can I stub method of a mocked object...
#RunWith(MockitoJUnitRunner.class)
public class ChildBLLIT extends BaseInteractorIT {
#InjectMocks
private ChildBLL ChildBLL = Mockito.mock(ChildBLL.class);
#Before
public void setUp() {
ChildBLL.engine = engineMock;
}
/**
* Test of getZipStatistics method, of class ChildBLL.
*/
#Test
public void testGetZipStatistics() {
final String testZipStatisticsText = "DummyZipStatistics";
//This method will throw the null pointer exception
when(ChildBLL.engine.getZIPStatistics()).thenReturn(testZipStatisticsText);
ChildBLL.getZipStatistics();
verify(ChildBLL.engine).getZIPStatistics();
}
}
When I try to stub the getZIPStatistics() method I get always a null pointer exception, of course I get, because in the getZIPStatistics() method there is an private object, which is not mocked... it seems to me the Mockito does not mocking the private fields... and unfortunately this is from another project:
public class BaseIT {
#Mock
protected static FromOtherProject engineMock;
#Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
}
Here I mocked the engine variable, but then how can I mock/stub the getZIPStatistics() method? This is this method:
public class FromOtherProject {
//...
public final String getZIPStatistics() {
return ZIPStatistics.toString();
}
}
What can I do?
Let's assume a simple class...
public class Account {
public String getPassword() {
return "abc";
}
}
...and simple class that contains it...
public class AccountHolder {
private Account account;
public String getAccountPassword() {
return this.account.getPassword();
}
}
So now we have a simple base class for all Account based tests...
public class AccountBasedTest {
#Mock
protected Account account;
}
...and a class that actually tests the AccountHolder...
#RunWith(MockitoJUnitRunner.class)
public class AccountHolderTest extends AccountBasedTest {
#InjectMocks
private AccountHolder accountHolder;
#Test
public void getAccountPasswort_must_return_account_password() {
Mockito.when( this.account.getPassword() ).thenReturn ("xyz");
Assert.assertEquals("xyz", this.accountHolder.getAccountPassword());
}
}
And that's all. The #InjectMocks, etc. annotations will also look in the superclasses, so you get your mocked account and that account will be put into your AccountHolder. No need to call MockitoAnnotations.initMocks. It shouldn't hurt, but it's not needed because you are using the MockitoJUnitRunner already, which does exactly that.
Is it possible to test the values of an instance passed as an argument to a method that is void using Mockito?
public String foo() {
Object o = new ObjectX();
o.setField("hi");
someDao.boo(o);
return "response";
}
boo is void and I want to test that foo sets the field to "hi"
Perhaps you would want to use doNothing method.
#Mock
SomeDao someDao;
#Captor
ArgumentCaptor<ObjectX> captor;
#Test
void test() {
doNothing().when(someDao).boo(captor.capture());
foo();
assertEquals("hi", captor.getValue().getField());
}
Updated
this is what JB in my comments is suggesting.
#RunWith(MockitoJUnitRunner.class)
public class BarTest
{
#Mock
private SomeDao someDao;
#InjectMocks
private Bar bar;
#Before
public void initMocks()
{
MockitoAnnotations.initMocks(this);
}
#Test
public void testFoo()
{
Mockito.doAnswer(new Answer<Object>()
{
#Override
public Object answer(InvocationOnMock invocation) throws Throwable
{
ObjectX x = (ObjectX) invocation.getArguments()[0];
Assert.assertEquals("hi", x.getField());
return null;
}
}).when(someDao).boo(Mockito.any(ObjectX.class));
Assert.assertEquals("response", bar.foo());
}
}
This below is my first answer and correct in its own way.
No it's not possible with Mockito, since ObjectX is a new Object within the void method, to accomplish this with Mockito then you would have to pass ObjectX in as an argument to the method foo(). You might want to look into Powermock if your code can't be changed.
public String foo(ObjectX objectX) {
Object o = objectX;
o.setField("hi");
someDao.boo(o);
return "response";
}
Test case
#Test
public void testFoo()
{
ObjectX mock = Mockito.mock(ObjectX.class);
Assert.assertEquals("response", foo(mock));
Mockito.verify(mock, Mockito.times(1)).setField(Mockito.eq("hi"));
}