私は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にアプローチするべき方法について指導してください。
PowerMockはEasyMockと一緒ですが、私はmockito PowerMockitoを使用しています。 私は試みました:サービスmockService = PowerMockito.mock(Service.class); PowerMockito.whenNew(Service.class、connectionPool、properties、1,1) .andReturn(mockService);これは投げている間違いです。助言がありますか? –
@AyushKumarあなたが受け取ったエラーを表示できますか? –
これは構文エラーを示していました。 私が提供した他のソリューションを試しましたが、メソッド呼び出しを嘲笑するわけではなく、まだ流通しています。 –