繁体   English   中英

Spring Boot 模拟对象在调用时返回 null

[英]Spring boot mocked object returning null on call

我正在使用@RunWith(SpringRunner.class)编写单元测试用例来模拟对象。 我正在尝试模拟接受请求对象并返回响应的存储库实例,但在单元测试用例实现中,我使用@MockBean注释模拟了存储库并使用Mockito.when(respository.post(request)).thenReturn(response)注册了它的方法调用Mockito.when(respository.post(request)).thenReturn(response) 但是这个调用返回null

我遇到了类似的情况,问题是Mockito.when()块中给出的参数可能与生成的 spring 不同。 我将在下面解释我的情况,希望对您有所帮助:

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

当我发送请求时,spring 生成新的 Project 对象,该对象与product具有相同的字段但实例不同。 也就是说,Mockito 无法捕获when语句。 我像下面那样改变它并且它起作用了:

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

我想到了。 但解决方案对我来说仍然很奇怪......

我面临这个问题是因为,我在@Before注释方法中实例化requestresponse ......如下所述。

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

既然reqAreqB在技​​术上是相似的,那么为什么reqB调用不返回与注册相同的响应。

如果我将setup()方法代码移动到test()方法中,那么一切都会开始工作!!!!!!

我在这里遇到了同样的问题,vsk.rahul 的评论对我帮助很大。
我试图使用一种方法来返回模拟交互,但没有成功,将其转换为静态方法给了我预期的行为。

问题
方法bar.foo()为任何交互返回null

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

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

解决方案
方法bar.foo()为任何交互返回abc字符串

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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