web-dev-qa-db-ja.com

MockitoとJunitを使用するときにSpringBeanをAutoWireする方法は?

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

どうすればこれを修正できますか?

6
java123999

コード内で何もモックしていません。 @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");
      }
3
Kepa M.

別の解決策は、次のように静的内部構成クラスで@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);
        }
    }
}

とにかく、テストしたいメソッドがそのメソッドの望ましい振る舞いを得るために内部で使用するものをモックする必要があります。テストしているサービスをあざけるのは意味がありません。

2
Enigo

ここでモックの目的を誤解しています。

このようなクラスをモックアウトすると、アプリケーションに注入されたように見せかけます。つまり注入したくない!

これに対する解決策:注入する予定のBeanを@Mockとして設定し、@InjectMocksを介してテストクラスに注入します。

定義されたサービスだけがあるため、注入するBeanがどこにあるかは不明ですが...

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

    @Mock
    private ExternalService externalSvc;

    @InjectMocks
    PersonService testObj;
}
1
Makoto

私が間違っていない場合...経験則では、両方を一緒に使用することはできません。MockitojunitRunnerまたはSpringJUnitRunnerを使用してユニットテストケースを実行すると、両方を一緒に使用することはできません。

0
dev