简体   繁体   中英

Spring boot mocked object returning null on call

I am using @RunWith(SpringRunner.class) to writing unit test case to mock the object. I am trying to mock the repository instance which is accepting request object and returning response, but in unit test case implementation I have mocked the repository using @MockBean annotation and register the it's method call using Mockito.when(respository.post(request)).thenReturn(response) . But this call is returning null .

I faced similar situation, the problem is given parameter in Mockito.when() block may not be the same as spring generated. I'll explain my case below, hope to help you:

Product product = new Product(..);
Mockito.when(service.addProduct(product)).thenReturn(saveProduct)

When I send a request, spring generates new Project object which has same fields with product but instance is different. That is, Mockito cannot catch when statement. I changed it like below and it's worked:

Mockito.when(service.addProduct(Mockito.any())).thenReturrn(savedProduct)

I figured it out. But the solution is still weird to me...

I was facing this issue because, I was instantiating the request and response in @Before annotated method... as describing below.

    @Before
public void setup() {
    Request reqA = new Request();
    reqA.set..(..);

    Response res = new Response();
    res.set..(..);

    Mockito.when(this.respository.post(reqA)).thenReturn(res);
}

@Test
public void test() {

    // Creating Request instance again with all same properties. 
    // Such that this req instance is technically similarly as instantiated in @Before annotated method (above). 
    // By, implementing the equals and hashCode method.
    Request reqB = new Request();
    reqB.set..(..);

    // Getting res as 'null' here....
    Response res = this.service.post(reqB);
}

Since, reqA and reqB are technically similar then why mocked call not returning the same response as registered.

If I moved setup() method code inside test() method every thing starts working !!!!!

I had the same issue here, vsk.rahul's comment helped me a lot.
I was trying to to use a method to return a mock interaction, but not succeeded, turning it into a static method gave me the expected behavior.

Problem :
The method bar.foo() was returning null for any interaction

public void test1() {
    doReturn(mockReturn()).when(bar).foo();
}

private String mockReturn() {
    return "abc";
}

Solution :
The method bar.foo() is returning abc String for any interaction

public void test1() {
    doReturn(mockReturn()).when(bar).foo();
}

private static String mockReturn() {
    return "abc";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM