【问题标题】:@MockBean return always false@MockBean 总是返回 false
【发布时间】:2017-10-26 18:45:52
【问题描述】:

我正在尝试测试我的应用程序,但是当我使用 @MockBean 时,所有函数都返回 false。 这是我的测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class AppParkingApplicationTests {

@MockBean
Vehicle vehicle;
@MockBean
VehicleController vehicleController;

@Test
public void getValidVehicleTest(){
    //Arrange
    boolean resp=false;
    when(vehicle.getTipo()).thenReturn("Carro");
    //Act
    resp=vehicleController.getValidVehicle(vehicle.getTipo());
    //Assert
    assertEquals(true, resp);
}

这就是函数

public boolean getValidVehicle(String tipo){
        boolean result=false;
        if(tipo.equals("Carro") || tipo.equals("Moto")){
            result= true;
        }
        return result;
    }

【问题讨论】:

    标签: spring-boot junit mocking


    【解决方案1】:

    这是因为当返回类型为原始布尔值时,模拟方法的默认返回为 false。

    我认为您不想模拟您的 Controller,因为这似乎是正在测试的类。直接替换

    @MockBean
    VehicleController vehicleController;
    

    @Autowired
    VehicleController vehicleController;
    

    【讨论】:

    • 很好的答案+1。我爱你的头像。这是什么?
    • 我的控制器也是这么想的……但它有一些连接到BD的方法,所以……在这种情况下我该怎么办?
    • @AndresCastañedaMarin 模拟调用数据库的存储库。
    • @davidxxx 谢谢!来自佩里圣经团契漫画:pbfcomics.com/comics/wise-shitashi
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2021-11-05
    • 2018-11-05
    • 2019-05-06
    • 2017-04-29
    • 2013-04-30
    • 2015-01-20
    相关资源
    最近更新 更多