【问题标题】:Write JUnit test on controller in SpringBoot Without start application在没有启动应用程序的情况下在 SpringBoot 控制器上编写 JUnit 测试
【发布时间】:2021-12-12 18:06:45
【问题描述】:

我正在尝试测试我的控制器方法,它正在调用 dao 类的方法,现在 dao 类具有 @Autowired 存储库,并且 dao 类的方法也在调用存储库方法。 我最终在我的测试类中使用@mock 存储库来模拟它的行为。

测试类:

Mock
UserRepository userRepository;

Mockito.when(userRepository.findByEmailId("abc@gmail.com")).thenReturn(obj);

道类:

@Autowired
UserRepository userRepository;

obj=userRepository.findByEmailId(email);

现在,我的测试用例没有运行。我正在尝试为所有 @Autowiring 创建一个基类。 我该怎么办?

【问题讨论】:

    标签: spring-boot unit-testing junit controller mockito


    【解决方案1】:

    您不需要模拟 UserRepository,而是模拟 DAO,它是您的 Controller 的直接依赖项。类似于以下内容:

    @ExtendWith(SpringExtension.class)
    @WebMvcTest(ControllerClassName.class)
    public class ControllerClassNameTest {
    
        @Autowired
        protected MockMvc mvc;
    
        @MockBean
        private DaoClassName dao;
    
        @BeforeEach
        public void setUp() throws Exception {
            Mockito.when(dao.whateverMethodYouWantToMock()).thenReturn(xyz);
        }
    
        // Your tests here
    
    }
    

    请记住,您应该使用MockMvc 来测试您的控制器,以模拟真正的 HTTP 调用,而不是直接的方法调用。更多信息请访问https://www.baeldung.com/spring-boot-testing#unit-testing-with-webmvctest

    【讨论】:

    • 但我的 dao 方法有一个实体 obj,其中包含存储库方法返回的值。我的 repository.method 正在访问数据库。我的 dao 类:- 实体 obj=repository.mymethod;关于 obj 的其他一些工作;
    • 但是如果您不想启动应用程序(也就是进行集成测试),您必须模拟 DAO,这样您就不会访问数据库。
    • 好的,我会试试的。谢谢你
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    • 2015-01-28
    • 2019-02-19
    • 1970-01-01
    相关资源
    最近更新 更多