Mocked value is not returned - java

I have two classes:
public class Foo {
public int getInt(){
return 10;
}
}
public class Bar {
Foo testClass = new Foo();
public Foo getTestClass() {
return testClass;
}
public void setTestClass(Foo testClass) {
this.testClass = testClass;
}
public int get(){
return testClass.getInt();
}
}
And finally I have test class with mock for Foo:
public class TestClass {
Foo test;
#Before
public void init(){
test = Mockito.mock(Foo.class);
Mockito.when(test.getInt()).thenReturn(5);
}
#Test
public void tst(){
Bar t = new Bar();
Assert.assertEquals(t.get(), 5);
}
}
Could you tell me, why I'm getting 10 from t.get() although in mock "I say" that I want 5 ?
How can I write Mock to get mocking value?
Thanks in advance.

You forgot to actually set your mock with a call to t.setTestClass(test);.

When you're writing :
public class TestClass {
Foo test;
#Before
public void init(){
test = Mockito.mock(Foo.class);
Mockito.when(test.getInt()).thenReturn(5);
}
#Test
public void tst(){
Bar t = new Bar();
Assert.assertEquals(t.get(), 5);
}
}
You are mocking your Foo class, but not using it in the Bar class. So if you call the return method, it won't send the result you tried to mock

Related

PowerMock spy calls original method but returns mocked value

I have following method which I mocked private method foo.
public class Foo {
public int x;
public void init() {
x = foo();
}
private int foo() {
System.out.println("shouldn't print this");
return 11;
}
}
When I mocked the method as following:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Main.class, Foo.class})
public class MainTest {
#Test
public void foo() throws Exception {
Foo f = PowerMockito.spy(new Foo());
PowerMockito.whenNew(Foo.class).withAnyArguments().thenReturn(f);
PowerMockito.when(f, "foo").thenReturn(42);
Main m = new Main();
m.f.init();
System.out.println(m.f.x);
}
}
It prints 42 instead of 11 which is correct but it also prints shouldn't print this.
Is it possible to mock private method without having call to that method?
shouldn' print this is getting printed because of the below line.
PowerMockito.when(f, "foo").thenReturn(42);
Instead, change the line something like
PowerMockito.doReturn(42).when(f,"foo");

How to Mock the void method call which is present inside static method using Mockito and Junit?

I have class TestME which has static main method. I need to avoid the call of b.cool method.
public class TestME {
public static int testme(String ...strings){
System.out.println(strings.length);
B b = new B();
b.cool();
return strings.length;
}
}
My B class is below
public class B {
public void cool(){
System.out.println("I am cool");
}
}
My Junit class for above TestMe class is below
#RunWith(MockitoJUnitRunner.class)
public class JunitTest {
#Spy
B b;
#InjectMocks
TestME test;
#Before
public void setUp(){
test = new TestME();
MockitoAnnotations.initMocks(this);
}
#Test
public void testMe(){
doNothing().when(b).cool();
Assert.assertEquals(2, test.testme("xyz", "omg"));
}
}
You may change your code from:
public class TestME {
public static int testme(String ...strings){
System.out.println(strings.length);
B b = new B();
b.cool();
return strings.length;
}
}
To the following:
public class TestME {
public static int testme(String ...strings){
System.out.println(strings.length);
B b = getInstanceOfB();
b.cool();
return strings.length;
}
static B getInstanceOfB(){
return new B();
}
}
Then in your test code you may spy on the class, stub getInstanceOfB() method to return mock object. Having this true b.cool would be never called in tests.
#RunWith(PowerMockRunner.class)
#PrepareForTest(TestME.class)
public class JunitTest {
#Before
public void setUp(){
B b = PowerMockito.mock(B.class);
PowerMockito.spy(TestME.class);
PowerMockito.when(TestME.getInstanceOfB()).thenReturn(b);
}
#Test
public void testMe(){
Assert.assertEquals(2, TestME.testme("xyz", "omg"));
}
}
You'll need a PowerMockito to accomplish that.
As you are calling static method no need to mock the TestMe. Simple call like TestMe.testme as below.
#Test
public void testMe(){
doNothing().when(b).cool();
Assert.assertEquals(2, TestMe.testme("xyz", "omg"));
}

Test concrete method of an abstract class containing an interface call

I have a class:
public abstract class Foo{
#Inject
private FooBarClient foobarclient;
public abstract long dofoo1();
public abstract long dofoo2();
public void doBar1(){
foobarClient.docall(faa);
}
}
I'd like to test the doBar1() method so I made my test class like this:
#RunWith(MockitoJUnitRunner.class)
public class FooTest {
private Foo foo;
#Mock
private FoobarClient foobarClient;
#Before
public void init() {
foo = new Foo() {
dofoo1(){};
};
}
#Test
public void testControleValiditeSite() throws Exception {
// G
Response response=....;
Mockito.when(foobarClient.docall(Mockito.any(faa.class))).thenReturn(
response);
// W
foo.doBar1();
// T;
}
But I got a null pointer exception on the fooBarclient in doBar1().
I also tried to mock the abstract with:
Foo foo = Mockito.mock(Foo,Mockito.CALLS_REAL_METHODS);
Is there a better method to do this test?
EDIT :
I used reflection. Now the code looks like:
#RunWith(MockitoJUnitRunner.class)
public class FooTest {
private Foo foo;
#Mock
private FoobarClient mockedFoobarClient;
#Before
public void init() {
foo = new Foo() {
dofoo1(){};
};
**MockitoAnnotations.initMocks(this);**
**ReflectionTestUtils.setField(foo , "foobarClient", mockedFoobarClient);**
}
#Test
public void testControleValiditeSite() throws Exception {
// G
Response response=....;
Mockito.when(foobarClient.docall(Mockito.any(faa.class))).thenReturn(
response);
// W
foo.doBar1();
// T;
}
You might not need to mock it, just create an instance in your test (assuming you're able to change the access type of client from private to protected).
Foo foo = new Foo() {
#Override
public long dofoo1() {
return 0;
}
#Override
public long dofoo2() {
return 0;
}
public void setClient(FooBarClient client) {
foobarclient = client;
}
};
foo.setClient(client);
foo.doBar1();
In your test class, create a non-abstract inner class that extends Foo. Use that in your test.

Test argument of a void method with Mockito

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"));
}

Proper usage of Mockito.verify

I'm new to unit testing and i had a simple question regarding the usage of verify method used in Mockito. here's the class i used for testing.
public class Foo{
int n = 0;
void addFoo(String a){
if(a == "a")
add(1);
}
protected void add(int num){
n =1;
}
public int get(){
return n;
}
}
And here's my Unit test.
public class FooTest {
#Mock Foo f;
#Test
public void test() {
MockitoAnnotations.initMocks(this);
f.addFoo("a");
//Passes
Mockito.verify(f).addFoo("a");
//Fails
Mockito.verify(f).add(1);
}
}
And i get a
Wanted but not invoked:
f.add(1);
-> at FooTest.test(FooTest.java:22)
However, there were other interactions with this mock:
-> at FooTest.test(FooTest.java:16)
exception.
How do you verify that add(int num) is called ?
I think you misunderstood the point of verify.
In your test, Foo f is a mock object - Foo's internal implementation is ignored, and only the behavior you recorded on it (using when(f.someMethod().thenXXX) would happen.
The point of mocking and verifying is to test interactions while ignoring the internal implementation.
In this example, you would probably have another class that uses Foo, and you'd want to test whether it invokes the correct methods of the given Foo instance.
Quick example:
Assume you have a class the uses the Foo class you presented in your question:
public class FooUser {
private Foo f;
public void setFoo(Foo f) {
this.f = f;
}
public Foo getFoo() {
return f;
}
public void addToFoo(String string) {
f.add(string);
}
}
Now, you'd want to test that FooUser#addToFoo(String) indeed invokes the correct add(String) method of Foo:
#RunWith (MockitoJUnitRunner.class)
public class FooUserTest {
#Mock Foo f;
FooUser fUser;
#Before
public void init() {
fUser = new FooUser();
fUser.setFoo(f);
}
#Test
public void test() {
fUser.addToFoo("a");
Mockito.verify(f).addFoo("a");
}

Categories