【问题标题】:Spring boot mocked object returning null on callSpring Boot 模拟对象在调用时返回 null
【发布时间】:2018-10-17 20:37:54
【问题描述】:

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

【问题讨论】:

  • 试试@RunWith(MockitoJUnitRunner.class),或者如果你需要使用SpringRunner,初始化你的模拟——见stackoverflow.com/questions/10806345/…
  • 您是否已将@SpringBootTest 添加到您的测试中?
  • @tgdavies 同意,但这是一个完全不同的故事。我确信@RunWith(MockitoJUnitRunner.class) 会起作用。 @Luay - @SpringBootTest 也不起作用。

标签: java unit-testing spring-boot mockito


【解决方案1】:

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

我遇到了这个问题,因为我在 @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 在技术上相似,那么为什么模拟调用不返回与注册相同的响应。

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

【讨论】:

  • 如果Request 没有以reqA.equals( actualRequest ) 返回true 的方式实现equals,那么Mockito 将不会知道这个“actualRequest”就是你要找的那个。通过将其移动到测试方法中,我假设您使用 reqA 作为实际请求,这当然有效,因为 reqA == reqA 允许 Mockito 意识到这是您正在等待的。
【解决方案2】:

我遇到了类似的情况,问题是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())).thenReturn(savedProduct)

【讨论】:

    【解决方案3】:

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

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

    public void test1() {
        doReturn(mockReturn()).when(bar).foo();
    }
    
    private String mockReturn() {
        return "abc";
    }
    

    解决方案
    方法 bar.foo() 正在返回 abc String 以进行任何交互

    public void test1() {
        doReturn(mockReturn()).when(bar).foo();
    }
    
    private static String mockReturn() {
        return "abc";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多