简体   繁体   English

JUnit + Mockito如何测试DAO层

[英]JUnit + Mockito how to test DAO layer

I am using Spring, SpringMVC, Mybatis in the project. 我在项目中使用Spring,SpringMVC,Mybatis。
First time to play with Mockito. 第一次和Mockito一起玩。

Before using Mockito, the test code looked like this 在使用Mockito之前,测试代码如下所示

@Test
@Transactional
@Rollback
public void setNewUnifyPriceRoom() throws Exception {
    Map reqMap = new HashMap();
    reqMap.put("typeId", 21);
    reqMap.put("roomId", 19);

    roomDockingsMapper.setNewUnifyPriceRoom(reqMap);

    String isUnifyPriceRoom = roomDockingsMapper.isUnifyPriceRoom(19, 21);
    Assert.assertEquals("Y", isUnifyPriceRoom);
}

Then I found Mockito since I did not want to touch database during testing. 然后我发现了Mockito,因为我不想在测试期间接触数据库。 I tried to write a BeforeClass as a data provider. 我试图写一个BeforeClass作为数据提供者。 However, I got stuck when I tried to return something after I did the setNewUnifyPriceRoom action 但是,在执行setNewUnifyPriceRoom操作后尝试返回某些内容时,我陷入了困境

 private static RoomDockingsMapper mockRoomDockingsMapper;
    @BeforeClass
    public static void setup(){
        Map reqMap = new HashMap();
        reqMap.put("typeId", 21);
        reqMap.put("roomId", 19);
        mockRoomDockingsMapper = mock(RoomDockingsMapper.class);
        when(mockRoomDockingsMapper.setNewUnifyPriceRoom(reqMap)).thenReturn(??????);
    }

Basically what I want to do is after do setNewUnifyPriceRoom , then in the thenReturn section to set isUnifyPriceRoom method return "Y". 基本上我想做的是在执行setNewUnifyPriceRoom之后 ,然后在thenReturn部分中设置isUnifyPriceRoom方法,返回“ Y”。

Any help will be appreciated. 任何帮助将不胜感激。

You don't want to mock out the very method that you are testing. 您不想模拟正在测试的方法。 You want to mock out the database interaction that happens inside setNewUnifyPriceRoom , so that you can verify that the rest of the code is working correctly. 您想模拟setNewUnifyPriceRoom内部发生的数据库交互,以便可以验证其余代码是否正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM