2017-01-16 7 views
0

私はJUNITSを初めて使い、コードのテストケースを書くのにMockitoとPowerMockitoを使用しようとしていますが、問題に直面しています。メソッドを模擬することができません

クラスコード:

public class Example implements Callable<Void> { 
    int startIndex; 
    int endIndex; 
    ConnectionPool connPool; 
    Properties properties; 

    public Example(int start, int end, 
      ConnectionPool connPool, Properties properties) { 
     this.startIndex = start; 
     this.endIndex = end; 
     this.connPool= connPool; 
     this.properties = properties; 
    } 

    @Override 
    public Void call() throws Exception { 
     long startTime = System.currentTimeMillis(); 
     try { 

      List<String> listInput = new ArrayList<>(); 
      Service service = new Service(
        dbConnPool, properties, startIndex, endIndex); 

      service.getMethod(listInput); 

      . 
      . 
      . 

JUNITコード:

@RunWith(PowerMockRunner.class) 
@PrepareForTest() 
public class ExampleTest { 

    @Mock 
    private ConnectionPool connectionPool; 

    @Mock 
    private Properties properties; 

    @Mock 
    private Service service = new Service(
      connectionPool, properties, 1, 1); 

    @Mock 
    private Connection connection; 

    @Mock 
    private Statement statement; 

    @Mock 
    private ResultSet resultSet; 

    @InjectMocks 
    private Example example = new Example(
      1, 1, connectionPool, properties); 


    @Test 
    public void testCall() throws Exception { 
     List<String> listInput= new ArrayList<>(); 
     listInput.add("data1"); 

     when(service.getMethod(listInput)).thenReturn(listInput); 
     example.call(); 
    } 

質問:どのように呼んで、サービスクラスとそのメソッド、getMethodを模擬するには?

説明:Serviceクラスには、getMethodメソッドがあり、これはDBと対話しています。だから、私はこのメソッドを模擬することができないので、コードが通過し、getMethodのすべてのオブジェクトを接続、結果セットなどとして模倣しなければならない。そうしないと、NullPointerExceptionがスローされる。

私が間違っていることを理解するのを手伝ってください。可能であれば、私はこの種のメソッド呼び出しのためにJUNITSにアプローチするべき方法について指導してください。

答えて

0

あなたのメソッドの内側にnew Serviceの呼び出しがある場合、Mockitoはオブジェクトをモックするのに役立ちません。

PowerMockito.whenNew(Service.class) 
      .withArguments(connectionPool, properties, 1, 1) 
      .thenReturn(mockService); 

this articleを確認してください: は、代わりに、同等があるPowerMockitoについてPowerMock.expectNew

Service mockService = PowerMock.createMock(Service.class); 
PowerMock.expectNew(Service.class, connectionPool, properties, 1, 1) 
     .andReturn(mockService); 

PowerMock.replay(mockService); 

を使用する必要があります。

+0

PowerMockはEasyMockと一緒ですが、私はmockito PowerMockitoを使用しています。 私は試みました:サービスmockService = PowerMockito.mock(Service.class); PowerMockito.whenNew(Service.class、connectionPool、properties、1,1) .andReturn(mockService);これは投げている間違いです。助言がありますか? –

+0

@AyushKumarあなたが受け取ったエラーを表示できますか? –

+0

これは構文エラーを示していました。 私が提供した他のソリューションを試しましたが、メソッド呼び出しを嘲笑するわけではなく、まだ流通しています。 –

関連する問題