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

时间:2018-05-08 01:00:29

标签: java unit-testing spring-boot mockito

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

3 个答案:

答案 0 :(得分:1)

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

我遇到了这个问题,因为我正在实例化postgres注释方法中的requestresponse ...如下所述。

@Before

因为 @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); } reqA在技术上相似,所以为什么模拟调用不会返回与注册相同的响应。

如果我在reqB方法中移动了setup()方法代码,那么每件事情都会开始工作!!!!!

答案 1 :(得分:1)

我面临类似的情况,问题是Mockito.when()块中给出的参数可能与弹簧生成的不一样。我将在下面解释我的案例,希望能帮到你:

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

当我发送请求时,spring会生成新的Project对象,该对象与product具有相同的字段,但实例不同。也就是说,Mockito无法捕捉when声明。我改变了它,如下所示,它有效:

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

答案 2 :(得分:0)

我在这里遇到了同样的问题,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";
}
相关问题