簡體   English   中英

在同一服務類中調用方法時模擬方法

[英]mocking a method while calling a method in same service class groovy grails

我正在尋找類似於犀牛模擬的東西,但是很時髦。

我有時也使用部分模擬。

在ASP中-Rhino模擬

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)
       }

我不知道該怎么做,有人知道嗎?

謝謝

如果使用的是groovy MockFor(例如groovy.mock.interceptor.MockFor ),則需要將用法包含在.use .use{}塊中。

但是,看起來您是從grails.test.GrailsUnitTestCase內部調用了mockFor 在那種情況下,不需要.use{}塊:模擬的范圍是整個測試。

謝謝你的回復

似乎我要完成的工作叫做“ 部分/半模擬” 這里是一些鏈接。

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()提取到其自己的類中,並將XService的模擬注入到B的類中-依賴注入。 我還得知,提取依賴是更好的測試方法。 所以,現在我在使用this。()時非常謹慎

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM