如何在使用Mockito和Junit时自动装配Spring beans?

7

我正在尝试设置我的类以便在 Junit 中使用。

但是,当我尝试以下操作时,会出现错误。

当前测试类:

public class PersonServiceTest {

    @Autowired
    @InjectMocks
    PersonService personService;

    @Before
    public void setUp() throws Exception
    {
        MockitoAnnotations.initMocks(this);
        assertThat(PersonService, notNullValue());

    }

    //tests

错误:

org.mockito.exceptions.base.MockitoException: 
Cannot instantiate @InjectMocks field named 'personService'
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null

我该如何修复这个问题?

4个回答

5
你的代码中没有模拟任何内容。@InjectMocks设置了一个将被注入模拟对象的类。
你的代码应该像这样:
public class PersonServiceTest {

    @InjectMocks
    PersonService personService;

    @Mock
    MockedClass myMock;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        Mockito.doReturn("Whatever you want returned").when(myMock).mockMethod;


    }

    @Test()
      public void testPerson() {

         assertThat(personService.method, "what you expect");
      }

我不明白,.doReturn方法是做什么的? - java123999
我认为在这里你会找到一个很好的解释,关于如何进行模拟过程。如果你在阅读后有进一步的问题,我会尽力帮助你。https://dzone.com/articles/use-mockito-mock-autowired - Kepa M.

2
另一种解决方案是使用@ContextConfiguration注释与静态内部配置类,如下所示:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class PersonServiceTest {
    @Autowired
    PersonService personService;

    @Before
    public void setUp() throws Exception {
        when(personService.mockedMethod()).thenReturn("something to return");
    }

    @Test
    public void testPerson() {
         assertThat(personService.method(), "what you expect");
    }

    @Configuration
    static class ContextConfiguration {
        @Bean
        public PersonService personService() {
            return mock(PersonService.class);
        }
    }
}

无论如何,您需要模拟一些方法内部使用的内容,以获得该方法的期望行为。对正在测试的服务进行模拟没有意义。


1

你误解了这里模拟的目的。

当你像这样模拟一个类时,你假装它已经被注入到你的应用程序中。这意味着你不想注入它!

解决方法:将你想要注入的任何bean设置为@Mock,并通过@InjectMocks将它们注入到你的测试类中。

由于你只定义了服务,所以不清楚你想要注入的bean在哪里...

@RunWith(MockitoJUnitRunner.class);
public class PersonServiceTest {

    @Mock
    private ExternalService externalSvc;

    @InjectMocks
    PersonService testObj;
}

0

如果我没记错的话...经验法则是你不能同时使用它们..你要么使用MockitojunitRunner运行单元测试用例,要么使用SpringJUnitRunner,但不能同时使用它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接