pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

    <bdo id='VEdMN'></bdo><ul id='VEdMN'></ul>

<small id='VEdMN'></small><noframes id='VEdMN'>

    <i id='VEdMN'><tr id='VEdMN'><dt id='VEdMN'><q id='VEdMN'><span id='VEdMN'><b id='VEdMN'><form id='VEdMN'><ins id='VEdMN'></ins><ul id='VEdMN'></ul><sub id='VEdMN'></sub></form><legend id='VEdMN'></legend><bdo id='VEdMN'><pre id='VEdMN'><center id='VEdMN'></center></pre></bdo></b><th id='VEdMN'></th></span></q></dt></tr></i><div class="9db77ph" id='VEdMN'><tfoot id='VEdMN'></tfoot><dl id='VEdMN'><fieldset id='VEdMN'></fieldset></dl></div>
    <legend id='VEdMN'><style id='VEdMN'><dir id='VEdMN'><q id='VEdMN'></q></dir></style></legend>

      <tfoot id='VEdMN'></tfoot>

      Mockito 何時/然后不返回預期值

      Mockito when/then not returning expected value(Mockito 何時/然后不返回預期值)

        <small id='wEYp8'></small><noframes id='wEYp8'>

          1. <i id='wEYp8'><tr id='wEYp8'><dt id='wEYp8'><q id='wEYp8'><span id='wEYp8'><b id='wEYp8'><form id='wEYp8'><ins id='wEYp8'></ins><ul id='wEYp8'></ul><sub id='wEYp8'></sub></form><legend id='wEYp8'></legend><bdo id='wEYp8'><pre id='wEYp8'><center id='wEYp8'></center></pre></bdo></b><th id='wEYp8'></th></span></q></dt></tr></i><div class="zrp5z7j" id='wEYp8'><tfoot id='wEYp8'></tfoot><dl id='wEYp8'><fieldset id='wEYp8'></fieldset></dl></div>

            <legend id='wEYp8'><style id='wEYp8'><dir id='wEYp8'><q id='wEYp8'></q></dir></style></legend>
              <tbody id='wEYp8'></tbody>

                <bdo id='wEYp8'></bdo><ul id='wEYp8'></ul>
                <tfoot id='wEYp8'></tfoot>

                本文介紹了Mockito 何時/然后不返回預期值的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                問題描述

                我正在嘗試使用任何"匹配器來存根此 getKeyFromStream 方法.我嘗試過更加明確和不明確(anyObject()),但似乎無論我嘗試什么,這個存根都不會在我的單元測試中返回 fooKey.

                I'm trying to stub this getKeyFromStream method, using the 'any' matchers. I've tried being more explicit and less explicit (anyObject()), but it seems like no matter what I try, this stub will not return the fooKey in my unit test.

                我想知道是因為它受到保護還是我遺漏了其他東西或做錯了什么.我在整個測試中還有其他 when/then 語句正在運行,但由于某種原因,這里不是.

                I'm wondering if it is because it is protected or there is something else I'm missing or doing incorrectly. I have other when/then statements throughout the tests that are working but for some reason here, it is not.

                注意:getKeyFromStream 一般使用 byteArrayInputStream,但我正在嘗試將其與 InputStream 匹配,我都嘗試過均無濟于事.

                Note: The getKeyFromStream generally uses a byteArrayInputStream, but I'm trying to match it with an InputStream, I've tried both to no avail.

                public class FooKeyRetriever() //Mocked this guy
                {
                    public FooKey getKey(String keyName) throws KeyException {
                
                        return getKeyFromStream(getKeyStream(keyName, false), keyName);
                    }
                
                    //Stubbed this method to return a key object which has been mocked
                    protected FooKey getKeyFromStream(InputStream keyStream, String keyName){
                        //Some code
                        return fooKey;
                    }
                }
                

                單元測試

                @Mock
                private FooKeyRetriever mockKeyRetriever;
                
                @Mock
                private FooKey fooKey;
                
                @Before
                public void setUp() throws Exception {
                        MockitoAnnotations.initMocks(this);
                }
                
                @Test
                public void testGetFooKey() throws Exception {
                
                
                
                    when(foo.getKeyFromStream(any(InputStream.class),any(String.class))).thenReturn(fooKey);
                
                    FooKey fooKey = mockKeyRetriever.getKey("irrelevant_key");
                
                    assertNotNull(fooKey);
                }
                

                推薦答案

                你的單元測試的問題是,你試圖模擬你想要測試的實際類的方法,但你實際上不能調用一個模擬方法,因為這將返回 null ,除非您在該調用的方法上聲明一個模擬返回值.通常,您只模擬外部依賴項.

                The problem with your unit-test is, that you are trying to mock a method of your actual class which you want to test but you can't actually invoke a mock method as this will return null unless you declare a mocked return value on that invoked method. Usually, you only mock external dependencies.

                實際上有兩種方法可以創建測試對象:mockspy.入門者將根據您提供的類創建一個新對象,該對象具有內部狀態 null 并且在每個調用的方法上都返回 null.這就是為什么您需要為方法調用定義某些返回值.spy 另一方面,如果為某些方法定義了模擬定義",則會創建一個真實對象并攔截方法調用.

                There are actually two ways to create test-objects: mock and spy. The primer one will create a new object based on the class you provided which has internal state null and also return null on every invoked method. That's why you need to define certain return values for method invocations. spy on the other hand creates a real object and intercepts method invocations if "mock definitions" are defined for certain methods.

                Mockito 和 PowerMock 提供了兩種定義模擬方法的方法:

                Mockito and PowerMock provide two ways of defining your mocked methods:

                // method 1
                when(mockedObject.methodToMock(any(Param1.class), any(Param2.class),...)
                    .thenReturn(answer);
                when(mockedObject, method(Dependency.class, "methodToMock", Parameter1.class, Parameter2.class, ...)
                    .thenReturn(answer);
                

                // method 2
                doReturn(answer).when(mockedObject).methodToMock(param1, param2);
                

                不同之處在于,方法 1 將執行方法實現,而后一個不會.如果您處理 spy 對象,這一點很重要,因為您有時不想在調用的方法中執行真正的代碼,而只是替換代碼或返回預定義的值!

                The difference is, that the method 1 will execute the methods implementation while the later one won't. This is important if you deal with spy objects as you sometimes don't want to execute the real code inside the invoked method but instead just replace the code or return a predefined value!

                盡管 Mockito 和 PowerMock 提供了一個 doCallRealMethod(),您可以定義它來代替 doReturn(...)doThrow(...),這將在您的真實對象中調用并執行代碼,并忽略任何模擬方法返回語句.但是,在您想要模擬被測類的方法的情況下,這并不是很有用.

                Although Mockito and PowerMock provide a doCallRealMethod() which you can define instead of doReturn(...) or doThrow(...), this will invoke and execute the code within your real object and ignores any mocked method return statements. Though, this is not that useful in your case where you want to mock a method of your class under test.

                方法實現可以被

                doAnswer(Answer<T>() { 
                    @Override 
                    public T answer(InvocationOnMock invocation) throws Throwable {
                        ...
                    }
                )
                

                您可以簡單地聲明被調用方法的邏輯應該是什么.您可以利用它來返回受保護方法的模擬結果,因此如下所示:

                where you simply can declare what the logic of the invoked method should be. You can utilize this to return the mock result of the protected method therefore like this:

                import static org.hamcrest.core.IsSame.sameInstance;
                import static org.junit.Assert.assertThat;
                import static org.mockito.Mockito.mock;
                import static org.mockito.Mockito.spy;
                import static org.mockito.Mockito.doReturn;
                import static org.mockito.Mockito.doAnswer;
                import static org.mockito.Matchers.any;
                import static org.mockito.Matchers.anyString;
                
                import java.io.InputStream;
                
                import org.junit.Test;
                import org.mockito.invocation.InvocationOnMock;
                import org.mockito.stubbing.Answer;
                
                public class FooKeyRetrieverTest {
                
                    @Test
                    public void testGetFooKey() throws Exception {
                        // Arrange
                        final FooKeyRetriever sut = spy(new FooKeyRetriever());
                        FooKey mockedKey = mock(FooKey.class);
                
                        doReturn(mockedKey)
                            .when(sut).getKeyFromStream(any(InputStream.class), anyString());
                        doAnswer(new Answer<FooKey>() {
                
                            public FooKey answer(InvocationOnMock invocation) throws Throwable {
                                return sut.getKeyFromStream(null, "");
                            }
                        }).when(sut).getKey(anyString());
                
                        // Act
                        FooKey ret = sut.getKey("test");
                
                        // Assert
                        assertThat(ret, sameInstance(mockedKey));
                    }
                }
                

                上面的代碼可以工作,但是請注意,這與簡單地將 getKey(...) 的返回值聲明為

                The code above works, however note that this has the same semantic as simply declaring a return value for the getKey(...) as

                doReturn(mockedKey).when(sut).getKey(anyString());
                

                嘗試僅使用以下內容修改 getKeyFromStream(...):

                Trying to modify only getKeyFromStream(...) with something like this:

                doReturn(mockedKey)
                    .when(sut).getKeyFromStream(any(InputStream.class), anyString());
                

                不修改您的被測系統 (SUT) 的 getKey(...) 將無法實現任何實際代碼 getKey(...) 將被執行.但是,如果您模擬 sut 對象,則無法調用 //Act 部分中的方法,因為這將返回 null.如果你嘗試

                without modifying getKey(...) of your System-Under-Test (SUT) won't achieve anything as the real code of getKey(...) would be executed. If you however mock the sut-object, you could not invoke the method in your // Act section as this would return null. If you try

                doCallRealMethod().when(sut).getKey(anyString());
                

                在模擬對象上,將調用真正的方法,如前所述,這也將調用 getKeyFromStream(...)getKeyStream(...) 的真正實現 不管你指定什么模擬方法.

                on a mock object, the real method woulb be called and as mentiond beforehand, this would also invoke the real implementations of getKeyFromStream(...) and getKeyStream(...) regardless what you specified as mock-method.

                正如您自己可能看到的那樣,實際測試類的模擬方法并沒有那么有用,而且給您帶來的負擔比它提供的任何好處都多.因此,如果您想要或需要測試私有/受保護的方法,或者您堅持只測試公共 API(我會推薦),這取決于您或您的企業的政策.您還可以重構您的代碼 以提高可測試性,盡管主要目的是重構應該是提高整體代碼設計.

                As you probably can see by yourself, mocking methods of your actual class under test is not that useful and puts more burden to you than it provides any good. Therefore, it's up to you or your enterprise' policy if you want or need to test private/protected methods at all or if you stick to testing only the public API (which I would recommend). You also have the possibility to refactor your code in order to improve testability although the primary intent of refactoring should be to improve the overall design of your code.

                這篇關于Mockito 何時/然后不返回預期值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

                【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

                相關文檔推薦

                How can I detect integer overflow on 32 bits int?(如何檢測 32 位 int 上的整數溢出?)
                Local variables before return statements, does it matter?(return 語句之前的局部變量,這有關系嗎?)
                How to convert Integer to int?(如何將整數轉換為整數?)
                How do I create an int array with randomly shuffled numbers in a given range(如何在給定范圍內創建一個隨機打亂數字的 int 數組)
                Inconsistent behavior on java#39;s ==(java的行為不一致==)
                Why is Java able to store 0xff000000 as an int?(為什么 Java 能夠將 0xff000000 存儲為 int?)

                    <bdo id='DCJqz'></bdo><ul id='DCJqz'></ul>

                  • <legend id='DCJqz'><style id='DCJqz'><dir id='DCJqz'><q id='DCJqz'></q></dir></style></legend>
                      <tbody id='DCJqz'></tbody>
                  • <tfoot id='DCJqz'></tfoot>
                  • <i id='DCJqz'><tr id='DCJqz'><dt id='DCJqz'><q id='DCJqz'><span id='DCJqz'><b id='DCJqz'><form id='DCJqz'><ins id='DCJqz'></ins><ul id='DCJqz'></ul><sub id='DCJqz'></sub></form><legend id='DCJqz'></legend><bdo id='DCJqz'><pre id='DCJqz'><center id='DCJqz'></center></pre></bdo></b><th id='DCJqz'></th></span></q></dt></tr></i><div class="mkic2ge" id='DCJqz'><tfoot id='DCJqz'></tfoot><dl id='DCJqz'><fieldset id='DCJqz'></fieldset></dl></div>
                  • <small id='DCJqz'></small><noframes id='DCJqz'>

                          主站蜘蛛池模板: SDI车窗夹力测试仪-KEMKRAFT方向盘测试仪-上海爱泽工业设备有限公司 | 咖啡加盟-咖啡店加盟-咖啡西餐厅加盟-塞纳左岸咖啡西餐厅官网 | 辽宁资质代办_辽宁建筑资质办理_辽宁建筑资质延期升级_辽宁中杭资质代办 | 电池高低温试验箱-气态冲击箱-双层电池防爆箱|简户百科 | 对夹式止回阀厂家,温州对夹式止回阀制造商--永嘉县润丰阀门有限公司 | 通风天窗,通风气楼,屋顶通风天窗,屋顶通风天窗公司 | 深圳快餐店设计-餐饮设计公司-餐饮空间品牌全案设计-深圳市勤蜂装饰工程 | 江苏全风,高压风机,全风环保风机,全风环形高压风机,防爆高压风机厂家-江苏全风环保科技有限公司(官网) | 粉末包装机-给袋式包装机-全自动包装机-颗粒-液体-食品-酱腌菜包装机生产线【润立机械】 | 高效节能电机_伺服主轴电机_铜转子电机_交流感应伺服电机_图片_型号_江苏智马科技有限公司 | 京马网,京马建站,网站定制,营销型网站建设,东莞建站,东莞网站建设-首页-京马网 | vr安全体验馆|交通安全|工地安全|禁毒|消防|安全教育体验馆|安全体验教室-贝森德(深圳)科技 | 产业规划_产业园区规划-产业投资选址及规划招商托管一体化服务商-中机院产业园区规划网 | 石家庄救护车出租_重症转院_跨省跨境医疗转送_活动赛事医疗保障_康复出院_放弃治疗_腾康26年医疗护送转诊团队 | 手术室净化厂家_成都实验室装修公司_无尘车间施工单位_洁净室工程建设团队-四川华锐16年行业经验 | 蓄电池在线监测系统|SF6在线监控泄露报警系统-武汉中电通电力设备有限公司 | 贵州科比特-防雷公司厂家提供贵州防雷工程,防雷检测,防雷接地,防雷设备价格,防雷产品报价服务-贵州防雷检测公司 | 充气膜专家-气膜馆-PTFE膜结构-ETFE膜结构-商业街膜结构-奥克金鼎 | 混合生育酚_醋酸生育酚粉_琥珀酸生育酚-山东新元素生物科技 | 恒温水槽与水浴锅-上海熙浩实业有限公司 | 槽钢冲孔机,槽钢三面冲,带钢冲孔机-山东兴田阳光智能装备股份有限公司 | 防水套管厂家_刚性防水套管_柔性防水套管_不锈钢防水套管-郑州中泰管道 | 郑州宣传片拍摄-TVC广告片拍摄-微电影短视频制作-河南优柿文化传媒有限公司 | 气象监测系统_气象传感器_微型气象仪_气象环境监测仪-山东风途物联网 | 螺旋丝杆升降机-SWL蜗轮-滚珠丝杆升降机厂家-山东明泰传动机械有限公司 | 数控专用机床,专用机床,自动线,组合机床,动力头,自动化加工生产线,江苏海鑫机床有限公司 | MES系统-WMS系统-MES定制开发-制造执行MES解决方案-罗浮云计算 | 芝麻黑-芝麻黑石材厂家-永峰石业| 外观设计_设备外观设计_外观设计公司_产品外观设计_机械设备外观设计_东莞工业设计公司-意品深蓝 | 众品家具网-家具品牌招商_家具代理加盟_家具门户的首选网络媒体。 | 采暖炉_取暖炉_生物质颗粒锅炉_颗粒壁炉_厂家加盟批发_烟台蓝澳采暖设备有限公司 | 德国GMN轴承,GMN角接触球轴承,GMN单向轴承,GMN油封,GMN非接触式密封 | 振动筛-交叉筛-螺旋筛-滚轴筛-正弦筛-方形摇摆筛「新乡振动筛厂家」 | 汽液过滤网厂家_安平县银锐丝网有限公司 | 儿童语言障碍训练-武汉优佳加感统文化发展有限公司 | 外观设计_设备外观设计_外观设计公司_产品外观设计_机械设备外观设计_东莞工业设计公司-意品深蓝 | 济南网站策划设计_自适应网站制作_H5企业网站搭建_济南外贸网站制作公司_锐尚 | 合肥展厅设计-安徽展台设计-合肥展览公司-安徽奥美展览工程有限公司 | 多功能三相相位伏安表-变压器短路阻抗测试仪-上海妙定电气 | 档案密集柜_手动密集柜_智能密集柜_内蒙古档案密集柜-盛隆柜业内蒙古密集柜直销中心 | 低温柔性试验仪-土工布淤堵-沥青车辙试验仪-莱博特(天津)试验机有限公司 |