Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In
Continue with Google
Continue with Facebook
or use


Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here
Continue with Google
Continue with Facebook
or use


Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

Sorry, you do not have a permission to ask a question, You must login to ask question.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Stack Ask

Stack Ask Logo Stack Ask Logo

Stack Ask Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 6074
Next
In Process
monkey
  • 0
monkeyEnlightened
Asked: June 3, 20222022-06-03T02:04:41+00:00 2022-06-03T02:04:41+00:00In: Spring

Spring Boot Integration test sử dụng có cả mockup lẫn service thật

  • 0

Spring Boot Integration test sử dụng có cả mockup lẫn service thật theo các bước như sau:

1. Khởi tạo project theo các bước này: https://stackask.com/question/huong-dan-su-dung-spring-boot-test-controller/
2. Giả sử chúng ta có GoodbyeController thế này:

package com.example.spring_test.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.spring_test.service.GoodByeService;
import com.example.spring_test.service.HelloService;

import lombok.AllArgsConstructor;

@RestController
@AllArgsConstructor
public class GoodbyeController {

    private final HelloService helloService;
    private final GoodByeService goodByeService;

    @GetMapping("/hello-and-goodbye")
    public String hello(@RequestParam String who) {
        return helloService.hello(who) + " and " + goodByeService.goodBye(who);
    }
}

Và lớp GoodByeService thế này:

package com.example.spring_test.service;

import org.springframework.stereotype.Service;

@Service
public class GoodByeService {

    public String goodBye(String who) {
        return "Goodbye " + who + '!';
    }
}

Tuy nhiên chúng vì một lý do nào đó (có thê do lớp GoodbyeService cần gọi sang service thứ 3) nên chúng ta cần mockup nó, vậy hãy sang bước tiếp theo.

integration-testspring boot
  • 2 2 Answers
  • 54 Views
  • 0 Followers
  • 1
Answer
Share
  • Facebook
  • Report

2 Answers

  • Voted
  • Oldest
  • Recent
  1. monkey Enlightened
    2022-06-03T02:06:35+00:00Added an answer on June 3, 2022 at 2:06 am
    This answer was edited.

    Giả sử bạn có lớp startup thế này:

    package com.example.spring_test;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringJUnitTestStartup {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringJUnitTestStartup.class);
        }
    }
    

    3. Chúng ta cần tạo ra lớp BaseIntegrationTest thế này:

    package com.example.spring_test.test;
    
    import org.junit.jupiter.api.extension.ExtendWith;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.context.ApplicationContextInitializer;
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.context.annotation.Bean;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit.jupiter.SpringExtension;
    
    import com.example.spring_test.SpringJUnitTestStartup;
    import com.example.spring_test.service.GoodByeService;
    import com.example.spring_test.test.BaseIntegrationTest.Initializer;
    import com.example.spring_test.test.BaseIntegrationTest.SomeTestConfiguration;
    
    @ExtendWith(SpringExtension.class)
    @SpringBootTest(
        classes = SpringJUnitTestStartup.class,
        webEnvironment = WebEnvironment.DEFINED_PORT
    )
    @ContextConfiguration(
        initializers = Initializer.class,
        classes = SomeTestConfiguration.class
    )
    public class BaseIntegrationTest {
    
        @MockBean
        protected GoodByeService goodByeService;
    
        public static class Initializer
            implements ApplicationContextInitializer {
    
            @Override
            public void initialize(ConfigurableApplicationContext applicationContext) {
                // init something
            }
        }
    
        public static class SomeTestConfiguration {
    
            @Bean
            public Object someBean() {
                return "someBean";
            }
        }
    }
    

    4. Cuối cùng chúng ta sẽ tạo ra lớp GoodbyeControllerTest thế này:

    package com.example.spring_test.test;
    
    import static org.mockito.Mockito.times;
    import static org.mockito.Mockito.verify;
    import static org.mockito.Mockito.when;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
    import org.springframework.test.web.servlet.MockMvc;
    
    @AutoConfigureMockMvc
    public class GoodbyeControllerTest extends BaseIntegrationTest {
    
        @Autowired
        private MockMvc mockMvc;
    
        @Test
        public void helloAndGoodByeTest() throws Exception {
            // given
            final String who = "World";
            final String goodBye = "I will never say good bye";
            when(goodByeService.goodBye(who)).thenReturn(goodBye);
    
            // when
            // then
            final String expected = "Hello World! and " + goodBye;
            mockMvc.perform(get("/hello-and-goodbye?who=World"))
                   .andExpect(status().isOk())
                   .andExpect(content().string(expected));
    
            verify(goodByeService, times(1)).goodBye(who);
        }
    }
    

    Done!!!

    • 1
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
    • Phạm Tiến Đạt Beginner
      2022-06-03T05:56:18+00:00Replied to answer on June 3, 2022 at 5:56 am
      This answer was edited.

      Mình thấy ide báo lỗi.
      Mình sửa thêm như này thì được.

      public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
      • 1
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp
        • Report

You must login to add an answer.

Continue with Google
Continue with Facebook
or use


Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 629
  • Answers 1k
  • Best Answers 70
  • Users 322
  • Popular
  • Answers
  • monkey

    [Deep Learning] Làm thế nào để xác định được cái ...

    • 16 Answers
  • Tú Trần Anh

    [Ezyfox Server] Unity game client không gửi được command khi ...

    • 12 Answers
  • Thưởng Đặng Văn

    Multiple tenant multiple database .net core

    • 11 Answers
  • tvd12
    tvd12 added an answer Qua rất nhiều trình gửi mail và các dự án… August 12, 2022 at 3:15 pm
  • monkey
    monkey added an answer use cosmwasm_std::{ Response, StdError, StdResult, Addr, Storage }; use cw_storage_plus::Map;… August 11, 2022 at 4:33 am
  • monkey
    monkey added an answer # Set up biến môi trường: source <(curl --insecure https://raw.githubusercontent.com/CosmWasm/testnets/master/malaga-420/defaults.env)… August 10, 2022 at 9:31 am

Related Questions

  • Hihi

    Giới hạn bộ nhớ Java

    • 1 Answer
  • Lâm Văn Đời

    Cache Spring

    • 4 Answers
  • Hihi

    Hỏi về AWS S3 + Spring

    • 4 Answers

Top Members

tvd12

tvd12

  • 70 Questions
  • 1k Points
Enlightened
monkey

monkey

  • 101 Questions
  • 709 Points
Enlightened
Nguyễn Thái Sơn

Nguyễn Thái Sơn

  • 153 Questions
  • 234 Points
Professional

Trending Tags

.net core abstract class ai analytics android ansible anti-flooding apache poi api artificial intelligence async asyncawait atomicboolean backend backend nestjs bash script batch bean big project binding bitcoin blockchain blog boot-nodes branch british btree buffered build bundle c# cache caching callback career career path cast centos chat cloud cloud reliability commit company content-disposition contract cors cosmos cosmos-sdk css database datasource datastructure decentralized exchange deep learning deploy contract design-pattern devops dex distraction programing dns docker download draw.io du học duration dữ liệu lớn eclip editor employee english erc20 erc721 eth ethereum ethereum login extensions exyfox ezyfox ezyfox-boot ezyfox-server ezyfoxserver ezyhttp ezymq-kafka ezyredis facebook fe floating point flutter freetank french front-end frontend fullstack fulltextsearch future game game-box game-room game-server gateway get git glide go golang google grapql grpc guide hazelcast hibernate hibernateconfig html http https index indexing integration-test intellij interface interview io ipfs isolate issue it java javacore java core javascript java spring javaw java web job jpa js json jsp & servlet jvm jwt kafka keep promise kerberos keycloak kotlin language languague library load-balancing log log4j log4j-core login lưu trữ machine learning macos math maven merge messaging metamask microservice model mongo msgpack multiple tenant multithread multithreading mysql n naming naming convention netcore netty nft nft game nio nodejs non-blocking io opensource optimize orm pagination pancakeswap panic pgpool phỏng vấn pointer postgresql pre private_key programming promise push message android push notification python python unicode question queue rabbitmq reactive reactjs reactjs download recyclerview redis request resource rest roadmap ropssten ropsten rr rust rxjava s3 schedule search security server shift jis singleton sjis slack smart contract soap socket socket server soft delete sosanh spring spring-boot-test spring-jpa spring aop spring boot springboot spring data jpa spring redis springsecurity spring security springwebflux mysql sql sql server sse stackask storage stream structure trong spring boot system environment variables thread threadjava thymeleaf totp tracking location transfer transfer git uniswap unit test unity upload file validate vector view volatile vue vue cli web web3 web3 client webpack websocket windows 11 winforms work zookeeper

Footer

Stack Ask

Stack Ask is where Developers Ask & Answers. It will help you resolve any questions and connect you with other people.

About Us

  • Meet The Team
  • About Us
  • Contact Us

Legal Stuff

  • Terms of Service
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2021 Stack Ask. All Rights Reserved
Powered by youngmonkeys.org