gpt4 book ai didi

java - 为什么当我返回模拟值时会收到 NullPointerException?

转载 作者:行者123 更新时间:2023-11-30 03:17:40 26 4
gpt4 key购买 nike

我有一个类:

public CustomerService Implements custStruct {

public Service changeCustomer(Guest guest) {
...

Seats seat = custService.assignSeats(tickets);

if(!seat.full) { // <--- this line is giving Null Pointer (seat is null)
...do something
}
}

我的测试是这样写的:

// ...
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
customerService = new CustomerService();
customerService = Mockito.spy(customerService);
}
// ...
@Test
public void testAssignSeats(){
Guest guest = Mockito.mock(Guest.class);
Seat seat = Mockito.mock(SeatCalc.class);
Tickets tickets = Mockito.mock(Tickets.class);
CustService custService = Mockito.mock(CustService.class);

customerService.set(tickets); //tickets is a setter
customerService.set(custService); //set to use another class's method
Mockito.when(custService.assignSeats(tickets)).thenReturn(seat);

// ...
customerService.changeCustomer(guest);
}

我想知道是否有办法在 if 语句上 stub 值?如果我尝试 stub seat 它将如何工作?

编辑:添加了有关座位等级的更多信息下面是 Seat 类...

public class Seat{
public boolean full= false;
public SeatArrangeRequest seatArrangeReq;
public List<ArrangeOrder> arrangeOrderList;
}

这是从...调用的 custService 方法

public seats custService(Tickets tickets) {

if(tickets!= null) {
...do some algorithm...
return seats
}

seat.full = true;
return seat;
}

最佳答案

发生了两件事之一,我不完全确定您的 MCVE 与您的真实代码相匹配。它是以下之一:

  1. 您正在尝试访问模拟对象的实例字段。相反,请使用真实的对象(如果 Seat 只是 POJO ),或定义一个可以模拟的 getter (seat.isFull())。
  2. 测试中的tickets与您在CustomerService中使用的tickets对象不匹配。您可以使用 Argument Matcher 来解决此问题,它将匹配任何 Tickets 对象,例如

    customerService.set(tickets); //tickets is a setter
    customerService.set(custService); //set to use another class's
    methodMockito.when(custService.assignSeats(Mockito.any(Tickets.class))).thenReturn(seat);

如果这些都不能解决您的问题,那么请edit您的问题可以更准确地反射(reflect)您真正在做什么。

关于java - 为什么当我返回模拟值时会收到 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32189260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com