在同一个服务类中调用方法时嘲讽一种方法groovy grails
即时寻找类似于我会用rhino mock做的事情,但在groovy中。在同一个服务类中调用方法时嘲讽一种方法groovy grails
我有时也使用部分模拟。
在ASP - 犀牛嘲笑
const string criteria = "somecriteriahere";
ISomeRepository mockSomeRepository = MockRepository.GenerateStrictMock<SomeRepository>();
mockSomeRepository.Expect(m => m.GetSomesByNumber(criteria)).Return(new List<Some>() { });
mockSomeRepository.Expect(m => m.GetSomesByName(criteria)).Return(new List<Some>() { });
mockSomeRepository.Expect(m => m.GetSomesByOtherName(criteria)).Return(new List<Some>() { });
mockSomeRepository.SearchForSomes(criteria);
mockSomeRepository.VerifyAllExpectations();
--------注意虚拟-------
public class SomeRepository : ISomeRepository {
public virtual IEnumerable<Some> GetSomesByNumber(string num)
{
//some code here
}
public virtual IEnumerable<Some> GetSomesByName(string name)
{
//some code here
}
public virtual IEnumerable<Some> GetSomesByOtherName(string name)
{
//some code here
}
public IEnumerable<Some> SearchForSomes(string criteria) {
this.GetSomesByNumber(criteria); //tested fully seperatly
this.GetSomesByName(criteria); //tested fully seperatly
this.GetSomesByOtherName(criteria); //tested fully seperatly
//other code to be tested
}
}
GetSomesByNumber,GetSomesByName,GetSomesByOtherName会完全分开测试。如果我实际上提供了价值观并进入了这些功能,对我来说,这看起来就像在集成测试中那样,测试多个功能而不是一个工作单元。
因此,SearchForSomes我只会测试该方法并嘲笑所有其他依赖项。
Grails中
class XService {
def A() {
}
def B() {
def result = this.A()
//do some other magic with result
}
}
我已经试过这一点 - 但未能
def XServiceControl = mockFor(XService)
XServiceControl.demand.A(1..1) { -> return "aaa" }
// Initialise the service and test the target method.
//def service = XServiceControl.createMock();
//def service = XServiceControl.proxyInstance()
// Act
//def result = XServiceControl.B(_params);
XServiceControl.use {
new XService().B(_params)
}
Ive得到了不知道如何做到这一点,没有任何一个知道如何?
感谢
如果您在使用常规MockFor(例如groovy.mock.interceptor.MockFor),那么你需要enclode使用在.use{}
块。
但是,它看起来像你从grails.test.GrailsUnitTestCase内调用mockFor
。在这种情况下,不需要.use{}
块:模拟的范围是整个测试。
感谢您的回复ataylor
似乎什么,我试图完成一种叫做分/半嘲讽。这里有一些链接。
http://www.gitshah.com/2010/05/how-to-partially-mock-class-and-its.html
http://mbrainspace.blogspot.com/2010/02/partial-half-mocks-why-theyre-good-real.html
https://issues.apache.org/jira/browse/GROOVY-2630
https://issues.apache.org/jira/browse/GROOVY-1823
http://java.dzone.com/articles/new-groovy-171-constructor
我没有做到这一点,我最终提取B()成它自己的类和注入的一个模拟X服务到B的类 - 依赖注射。我还被告知,提取依赖关系是一种更好的测试实践。所以,我现在非常小心使用它。():D
它是如何失败? – hvgotcodes 2011-02-28 16:53:51