@InjectMocks和非模拟对象(Spring Data Repositories)

时间:2013-12-03 10:54:18

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

有没有办法用@InjectMocks注入非模拟对象?

我的安装程序有一个UserSignupService,它依赖于MailService和UserRepository(Spring Data Repository)。我有一个单元测试创​​建了一个MailService的间谍,我用@InjectMocks注释了UserSignupService。遗憾的是,这不会将UserRepository(非模拟)注入服务类。 将@InjectMocks与@Autowired结合使用不会注入模拟的MailService,而是注入应用程序上下文中的bean。

MockitoAnnotations.initMocks()在AbstractServiceTest.setUp()中运行。该类还包含单元测试的配置(SpringJunit4TestRunner等)

public class UserSignupServiceTest extends AbstractServiceTest {

  @Autowired @Spy
  private MailService<UserActivationMail> mailService;

  @InjectMocks
  private UserSignupServiceImpl service;

  @Before
  public void setUp() throws Exception {
    super.setUp();
  }
}

@Service
public class UserSignupServiceImpl implements UserSignupService {

  private final UserRepository repository;
  private final MailService<UserActivationMail> mailService;

  @Autowired
  public UserSignupServiceImpl(UserRepository repository,
                               MailService<UserActivationMail> mailService) {
    this.repository = repository;
    this.mailService = mailService;
  }
  //methods...
}

1 个答案:

答案 0 :(得分:0)

您需要初始化您的Mockito MockitoAnnotations.initMocks(this);

以下是我有的Spring JUnit测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring-context.xml" })
public class SpringKPTest {

    @Autowired
    SomeClassA SomeClassA;

    @Mock
    SomeClassB SomeClassB;



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