gpt4 book ai didi

java - 具有命令和查询方法的对象应该是模拟的还是 stub 的?

转载 作者:太空宇宙 更新时间:2023-11-04 14:05:06 24 4
gpt4 key购买 nike

我有一个问题。

我有一个依赖于其他 DAO 对象的类。 DAO对象包含两种方法:命令方法和查询方法。我想要测试的方法调用这两种方法。

我应该模拟这个对象或 stub 吗?

我将向您展示我的测试的外观。

class RentServiceTest extends Specification {
Map<Integer, Room> rooms = new HashMap<Integer, Room>();

def setup() {
rooms.put(1, new Room(1));
rooms.put(2, new Room(2));
rooms.put(3, new Room(3));
rooms.put(4, new Room(4));
}

def "it should rent concrete room" () {
given:
RoomDAO roomDAOMock = Mock();
RentService rentService = new RentServiceImpl(roomDAOMock);
when:
roomDAOMock.getRooms() >> rooms;
rentService.rentRoom(2);
then:
1* roomDAOMock.editRoom(_);
roomDAOMock.getRooms() == rooms;
}
}

测试失败,因为 getRooms 方法返回 null;

最佳答案

以下测试工作得很好:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class RentServiceTest extends Specification {
Map<Integer, Room> rooms = new HashMap<Integer, Room>();

def setup() {
rooms.put(1, new Room(1));
rooms.put(2, new Room(2));
rooms.put(3, new Room(3));
rooms.put(4, new Room(4));
}

def "it should rent concrete room" () {
given:
RoomDAO roomDAOMock = Mock()
RentService rentService = new RentServiceImpl(roomDAOMock)
when:
roomDAOMock.getRooms() >> rooms
rentService.rentRoom(2)
then:
1 * roomDAOMock.editRoom(_)
}
}

class Room {
Room(int number) {}
}

class RoomDAO {
def editRoom(int number) {
}
}

interface RentService {

}

class RentServiceImpl implements RentService {

RoomDAO dao

RentServiceImpl(RoomDAO dao) {
this.dao = dao
}

def rentRoom(int number) {
dao.editRoom(number)
}
}

一般来说,您应该使用Mock

关于java - 具有命令和查询方法的对象应该是模拟的还是 stub 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28938078/

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