2011-01-07 7 views

答えて

12

それはMockitoと非常に簡単です:

@RunWith(MockitoJUnitRunner.class) 
public class RuleIdValidatorTest { 
    @Mock 
    private RuleStore ruleStoreMock; 

    @InjectMocks 
    private RuleIdValidator ruleIdValidator; 

    @Test 
    public void someTest() { 
     when(ruleStoreMock.doSomething("arg")).thenReturn("result"); 

     String actual = ruleIdValidator.doSomeThatDelegatesToRuleStore(); 

     assertEquals("result", actual); 
    } 
} 

Mockito javadocのか、私が書いたblog post@InjectMocksについてもっと読みますちょっと前の話題。

Mockito 1.8.3で利用可能です.1.9.0で強化されました。あなたは次の操作を行うことができ

10

あなたは、テスト中に返さrulestoreを模擬するためにMockitoのようなものを使用することができます。このStackOverflowのポストは、これを行うの良い例があります。

spring 3 autowiring and junit testing

+0

おかげで、私はその1を逃しました。 ReflectionTestUtils.setField(バリデータ "ruleStore"、ruleStore); – Steve

+0

ええ、Mockitoは良いです。シンプルで使いやすいです。 – chris

2

package com.mycompany;  

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.DependsOn; 
import org.springframework.stereotype.Component; 

@Component 
@DependsOn("ruleStore") 
public class RuleIdValidator implements ConstraintValidator<ValidRuleId, String> { 

    @Autowired 
    private RuleStore ruleStore; 

    // Some other methods 
} 

そして、あなたの春のコンテキストは次のようになります必要があります。

<context:component-scan base-package="com.mycompany" /> 

<bean id="ruleStore" class="org.easymock.EasyMock" factory-method="createMock"> 
    <constructor-arg index="0" value="com.mycompany.RuleStore"/> 
</bean> 
関連する問題