我有一个问题。
我有依赖于其他DAO对象的类。 DAO对象包含两种方法:命令方法和查询方法。我想测试的方法调用两种方法。
我应该模拟这个对象还是存根?
我会告诉你我的测试看起来如何。
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;
答案 0 :(得分:0)
以下测试完美无缺:
@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
。