当前位置:网站首页>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);
}
}
边栏推荐
- Transfer learning - getting started
- 《nlp入门+实战:第四章:使用pytorch手动实现线性回归 》
- [RTOS training camp] course learning methods and C language knowledge (pointer, structure, function pointer, linked list) and student questions
- Browser development and use skills
- Force buckle 25. Turn over the linked list in a group of K
- 《暗黑破坏神:不朽》手游如何多开搬砖及新手入门搬砖攻略
- [software development specification III] [software version naming Specification]
- How can I become an irreplaceable programmer?
- Tutorial on principles and applications of database system (053) -- MySQL query (XV): usage of character functions
- 如何才能修炼成一名不可替代的程序员?
猜你喜欢

Inverse matrix block matrix

Browser development and use skills

FastJson 处理泛型
![[RTOS training camp] continue the program framework, tick interrupt supplement, preview, after-school homework and evening class questions](/img/79/27e4709dd6381c8887e12a1a8da257.jpg)
[RTOS training camp] continue the program framework, tick interrupt supplement, preview, after-school homework and evening class questions

Failed to load DLL

《nlp入门+实战:第三章:梯度下降和反向传播 》

Win11打不开自带杀毒软件怎么办?win11自带杀毒功能打不开

Codeforces Round #810 (Div. 2)A~C

Small sample learning - getting started

【数据挖掘】生成模型和判别模型的区别及优缺点
随机推荐
[Code] refers to the repeated number in the offer 03 array
如何mysql只要重复数据?
[RTOS training camp] operation explanation, queue and ring buffer, queue - transmission data, queue - synchronization tasks and evening class questions
How can I become an irreplaceable programmer?
We have no way out
[RTOS training camp] course learning methods and C language knowledge (pointer, structure, function pointer, linked list) and student questions
Kubernetes Pod启动流程
[RTOS training camp] GPIO knowledge and preview arrangement + evening class questions
What are the ways to quickly improve programming skills in the process of programming learning?
iNFTnews | 假如这是元宇宙20年后的样子
[laser principle and application-4]: internal structure and working principle of laser
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
Implementation process of adding loading effect to easycvr page
"Introduction to natural language processing practice" deep learning foundation - attention mechanism, transformer deep analysis and learning material summary
Inverse matrix block matrix
Game thinking 17: Road finding engine recast and detour learning II: recast navigation grid generation process and limitations
【软件开发规范二】《禁止项开发规范》
Force buckle 25. Turn over the linked list in a group of K
[RTOS training camp] program framework, preview, after-school homework and evening class questions
Arthas watch 命令查看数组中对象的属性