本文介绍了Grails单元还是集成测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道是否在我的Grails 2.2.3应用程序中使用单元或集成测试来测试我想测试的内容。我希望像这样运行一些测试:
@TestFor(Student)
@Mock(Student)
class StudentTests {
void testFoundStudent(){
def s = Student.findById(myId)
assert s!= null
assert s.firstName =' Grant'
assert s.lastName ='McConnaughey'
}
}
这需要使用我们的测试数据库,那么这会使它成为一个集成测试吗?当我将这段代码作为一个单元测试运行时,它在 assert s!= null
时失败。这意味着它没有使用我们的数据库,因为它应该找到具有该ID的学生。
在Grails单元测试中,可以使用Gorm测试域类交互,并且在场景后面,Grails将使用内存数据库(一个ConcurrentHashMap的实现)来模拟这种行为。所以是的,你会得到null,因为这个学生不存在于内存数据库中,你需要先插入这些数据。
Student.findOrSaveWhere(名字:'Grant',姓氏:'McConnaughey')
在您的示例中,如果目的是测试数据的存在,则需要使用集成测试并使用<$ c将其连接到数据库$ c> datasource.groovy ,这真的不是一个好主意,除非你有充足的理由来测试你的数据。
如果你是试图再次测试 def s = Student.findById(myId)
,因为这是Grails动态查找器,您可能需要信任您正在使用的框架。然而,一般而言,
我希望这可以帮助
I don't know whether to use unit or integration tests for what I am wanting to test in my Grails 2.2.3 application. I want to run some tests against like this:
@TestFor(Student)
@Mock(Student)
class StudentTests {
void testFoundStudent() {
def s = Student.findById(myId)
assert s != null
assert s.firstName = 'Grant'
assert s.lastName = 'McConnaughey'
}
}
This is going to require the use of our test database, so would that make it an integration test? When I run this code as a unit test it fails at assert s != null
. Which means it isn't using our database, because it SHOULD find a student with that ID.
解决方案
In Grails unit test you can test domain class interactions using Gorm and behind the scene Grails will use in-memory database(an implementation of a ConcurrentHashMap) to mimic this behavior here. So yes you get null because that student does not exist in in-memory database and you need to insert that data first.
Student.findOrSaveWhere (firstName: 'Grant',lastName : 'McConnaughey')
In your example, if the intention is to test the existence of that data you need to use integration test and connect it to your database using datasource.groovy
, which is really not a good idea unless you have a good reason to test your data.
If you are trying to test def s = Student.findById(myId)
again that is not adding any value as that is Grails dynamic finder and you probably need to trust the framework you are using.
However, in general
I hope this helps
这篇关于Grails单元还是集成测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!