当前位置:网站首页>Should we test the Dao layer?
Should we test the Dao layer?
2022-07-26 01:14:00 【u012804784】
High quality resource sharing
| Learning route guidance ( Click unlock ) | Knowledge orientation | Crowd positioning |
|---|---|---|
| 🧡 Python Actual wechat ordering applet 🧡 | Progressive class | This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system . |
| Python Quantitative trading practice | beginner | Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system |
It should be tested DAO Tier? ?
There are many people on the Internet discussing whether unit tests should include DAO Layer testing . I feel , For some mainly crud In terms of business ,service Layer and the controller The layers will be very thin , The main logic is mapper On . Right now service Layer and the controller Layer write single test doesn't make much sense . Can only write mapper Single measurement of layer .
On the other hand ,mapper Layer testing can effectively avoid some low-level sql error .
Define single test
Unit testing is a test that only targets one unit , for instance , One Service Each public function of class . And all places where this function calls external dependencies need to be isolated , For example, the dependency of external classes , Or request a server .
In other words, unit testing is just testing the logic of a function of the current class itself , Without involving external logic . Therefore, the execution of single test should be very fast .
stay Java The commonly used dependencies in single test are mainly divided into test framework and Mock frame . A test framework is a framework for executing and managing test methods , It's usually used JUnit. and Mock The framework is used to simulate external dependencies , Isolate all external dependencies of the tested function .
Some misunderstandings
See too many single test tutorials on the Internet , It's a mess . Even if the concept of single test is not clear, publish an article , It's a mistake .
About common misunderstandings , This blog lists well : How to write unit tests well :Mock Break away from the database + Don't use @SpringBootTest
The key point is not to use @SpringBootTest(classes=XXXApplication.class) Annotation test class . This will directly start a springboot process , For a slightly more complex project, it will take at least 1 More than minutes to run . If the project uses remote configuration center ,SOA Such as middleware , Then I suggest going out to make a cup of tea .
So why don't you want to write a single test ? Wait so long , People walk and the tea is cold . But in fact, this is the wrong way to achieve . The following article explains in SpringBoot Examples of test classes at different integration levels in the project : Testing in Spring Boot | Baeldung
Generally speaking , Distinguish between integration testing and unit testing . Don't write single test as integration test .
DAO Implementation of layer test
The selection
The following article is a good summary : Write valuable unit tests - Alicloud developer community
Database testing needs to ensure that the test will not affect the external environment , And the generated data needs to be automatically destroyed after the test . There are generally several ways :
- Connect to the database of the development environment , And rollback after the test . Not recommended
- Use docker Containers :testContainer. Start during the test mysql Containers , Automatically recycle after completion . shortcoming : Every testing machine needs to be installed docker And download the container . This leads to :
- You need to push other developers to install the image
- Need to push devops In the online CI/CD Assembly line installation docker.( Give up )
- Use memory database , Data will not be persisted . More commonly used are h2.
If it is a personal development project , Or the integrated deployment pipeline will not be used . You can try to use testContainer, Because it can not only connect mysql test , For some middleware such as redis,mq Etc. can be simulated . But for complex projects developed by large teams, it is recommended to directly use the memory database .
in addition ,Mybatis Provides a test dependency package , Integrated h2, Reference resources : mybatis-spring-boot-test-autoconfigure – Introduction . But the disadvantage is that you need to rely on different versions springboot, The project developed by the author uses springboot Older version , And should not be updated , So you can configure it manually h2 了 .
Code
notes : The following code is implemented with reference to an article from somewhere , I don't remember the specific source .
We need to manually create 4 individual bean To infuse :
- DataSource, be used for jdbc Connect the corresponding h2 database .
- Server.h2 Of gui server service , You can use the connection database to view data . Not required .
- SqlSessionFactory. by mybatis Create a sqlSessionFactory, To specify mapper Of xml File location
- MapperScannerConfigurer. Is used to mybatis Medium mapper Interface generation agent bean.
There are several points to pay attention to : @ComponentScanYou need to fill in mapper Location of the interface- establish DataSource when ,
addScript()It specifies the table creation and initialization data prepared by yourself sql. Path in test/resources/db/schema-h2.sql - establish sqlSessionFactory when , Appoint resources Medium mapper.xml file .
- establish mapperScannerConfigurer when , Appoint mapper Interface package And the one created in the previous step factory Of bean Name , The default names are used here , That is, the name of the method .
@Configuration
@ComponentScan({ "com.my.app.mapper" })
public class BaseTestConfig {
@Bean()
public DataSource dataSource() {
EmbeddedDatabaseBuilder databaseBuilder = new EmbeddedDatabaseBuilder();
return databaseBuilder
.setType(EmbeddedDatabaseType.H2)
// Initialize the table creation statement at startup
.addScript("classpath:db/schema-h2.sql")
.build();
}
@Bean(name = "h2WebServer", initMethod = "start", destroyMethod = "stop")
// Start a H2 Of web server, When debugging, you can pass localhost:8082 Access to the H2 The content of
//JDBC URL: jdbc:h2:mem:testdb
//User Name: sa
//Password: nothing
// Note if breakpoints are used , Breakpoint type (Suspend Type) Be sure to set it to Thread And can't be All, otherwise web server Unable to access !
public Server server() throws Exception {
// stay 8082 Start a... On the port web server
return Server.createWebServer("-web", "-webAllowOthers", "-webDaemon", "-webPort", "8082");
}
@Bean()
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// Load all sqlmapper file
Resource[] mapperLocations = resolver.getResources("classpath*:mapper/*.xml");
sessionFactory.setMapperLocations(mapperLocations);
return sessionFactory.getObject();
}
@Bean()
public MapperScannerConfigurer mapperScannerConfigurer() {
// You just need to write DAO Interface , No need to write implementation classes , Dynamically generate agents at runtime
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setBasePackage("com.my.app.mapper");
configurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return configurer;
}
}
Create one such Configuration After the class , hinder MapperTest Class only needs to use @Import Just introduce this configuration class , Or put all the annotations on a base class , Let the back mapper All test classes inherit this base class , There is no need to annotate every test class :
@RunWith(SpringJUnit4ClassRunner.class)
@Import(BaseTestConfig.class)
public class BaseMapperTest {
@Autowired
private MyMapper myMapper;
@Test
public void test(){
Object o = myMapper.selectOne();
assertNotNull(o);
}
}
边栏推荐
- Cf1494f delete the edges (Euler circuit)
- 数据库系统原理与应用教程(053)—— MySQL 查询(十五):字符型函数的用法
- android sqlite先分组后排序左连查询
- Linear relationship between vectors
- NIO简易示例
- [RTOS training camp] course learning methods and structural knowledge review + linked list knowledge
- Transfer learning - getting started
- 更换IP地址常见的4种简单有效的方法
- [RTOS training camp] task scheduling (Continued), task comity, scheduling summary, queue and evening class questions
- API测试简介
猜你喜欢

链表相关面试题

【RTOS训练营】站在更高的角度学习C语言

985 associate professors in Colleges and universities sun their annual salary, and the provident fund tops the monthly salary of ordinary people. Netizen: it is worthy of being in Shanghai

什么是信息化?什么是数字化?这两者有什么联系和区别?
![[RTOS training camp] operation explanation, queue and ring buffer, queue - transmission data, queue - synchronization tasks and evening class questions](/img/59/0b671129e8cfaed28e2fe484ae0467.jpg)
[RTOS training camp] operation explanation, queue and ring buffer, queue - transmission data, queue - synchronization tasks and evening class questions

The difference and application of in and exists in SQL statement

How does the proxy IP server ensure its information security in the network
![[Jizhong] July 16, 2022 1432. Oil pipeline](/img/60/55a7e35cd067948598332d08eccfb1.jpg)
[Jizhong] July 16, 2022 1432. Oil pipeline

Inverse matrix block matrix

Open download! Alibaba Devops Practice Manual
随机推荐
How does the proxy IP server ensure its information security in the network
Tutorial on principles and applications of database system (056) -- MySQL query (18): usage of other types of functions
[RTOS training camp] about classes and Q & A
IP地址能精确到哪步?动态IP及静态IP是什么?切换IP最常用的方法
Timeout settings for feign and hystrix
数据库系统原理与应用教程(054)—— MySQL 查询(十六):日期时间型函数的用法
FreeBSD bnxt以太网驱动源码阅读记录二:
Selenium assertion and JS actuator
Tutorial on principles and applications of database system (054) -- MySQL query (16): usage of date time function
How to copy and paste QT? (QClipboard)
[laser principle and application-4]: internal structure and working principle of laser
typing‘ has no attribute ‘_ SpecialForm‘
Implementation process of adding loading effect to easycvr page
数据库系统原理与应用教程(053)—— MySQL 查询(十五):字符型函数的用法
1.30 升级bin文件添加后缀及文件长度
What is the dynamic IP address? Why do you recommend dynamic IP proxy?
全国一半人跑长沙,长沙一半人跑哪?
How can MySQL just duplicate data?
"Introduction to natural language processing practice" deep learning foundation - attention mechanism, transformer deep analysis and learning material summary
Regular expression