【问题标题】:Unit Testing Mock Service Impl单元测试模拟服务实现
【发布时间】:2019-03-12 06:43:20
【问题描述】:

我在 Spring Boot 应用程序中也有一个 service 和 serviceImpl。当我想测试它并尝试在 junit 测试类中模拟我的服务时,我得到了NullPointerException 错误。

这是我的服务实现

package com.test;

import java.util.Date;

public class MyServiceImpl implements MyService {
    @Override
    public MyObject doSomething(Date date) {
        return null;
    }
}

这是我的测试课

package com.test;

import com.netflix.discovery.shared.Application;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.jupiter.api.Assertions.assertNull;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
class MyServiceImplTest {

    @Mock
    MyService myservice;

    @Test
    void doSomethingTest() {
        assertNull(myservice.doSomething(null));
    }
}

【问题讨论】:

  • 我用你的代码测试过,没有抛出异常...

标签: java spring unit-testing spring-boot mockito


【解决方案1】:

在使用@Mock 注释时,您需要初始化模拟。您可以在带有@Before 注释的方法中执行此操作:

@Before public void initMocks() {
    MockitoAnnotations.initMocks(this);
}

或者,您可以将您的跑步者从 SpringRunner 更改为:

@RunWith(MockitoJUnitRunner.class)

编辑:

您还必须从您的实现中创建一个 bean:

@Service
public class MyServiceImpl implements MyService

【讨论】:

  • myservice 对象为空
  • 感谢您的回复。但它还没有工作。我添加了@Service。然后添加@Before 方法。不起作用。将 @RunWith 参数更改为 MockitoJUnitRunner 并添加 service.does 不起作用
  • 你能粘贴整个班级吗,@SpringBootApplication 在哪里?
  • @SpringBootApplication public class ContradictionApplication { public static void main(String[] args) { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); SpringApplication.run(ContradictionApplication.class, args); } }
  • 这就是我要求编辑问题的原因。您需要将 service 和 impl 移动到 ContradictionApplication 的子包中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 2019-05-21
  • 2020-03-17
  • 2020-03-22
相关资源
最近更新 更多