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

vsk*_*hul 5 java unit-testing mockito spring-boot

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

far*_*aya 6

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

Product product = new Product(..);
Mockito.when(service.addProduct(product)).thenReturn(saveProduct)
Run Code Online (Sandbox Code Playgroud)

当我发送请求时,spring 生成新的 Project 对象,该对象具有相同的字段,product但实例不同。也就是说,Mockito 无法捕获when语句。我将其更改如下并且有效:

Mockito.when(service.addProduct(Mockito.any())).thenReturn(savedProduct)
Run Code Online (Sandbox Code Playgroud)


vsk*_*hul 3

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

我面临这个问题是因为,我正在实例化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);
}
Run Code Online (Sandbox Code Playgroud)

由于reqAreqB在技术上相似,那么为什么模拟调用没有返回与注册相同的响应。

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