Reputation: 111
I have written a bolt and a topology. Now I need to do a Junit test case. My actual input is a Json and in my bolt I have written code to store this in MySQL. Now I need to test my logic which I have written in execute()
method. So how to create a object for the tuple in the test case or is there any other way to do this. I have attached the code of my execute()
method.
public void execute(Tuple input, BasicOutputCollector collector) {
int size = input.getFields().size();
Fields fields = input.getFields();
if (size == 1) {
logger.info("PostbackToRDSBolt execute method starts");
try {
eventJson = (JSONObject) JSONSerializer.toJSON((String) input.getValueByField(fields.get(0)));
address = (String) input.getValueByField(fields.get(0));
Id = (String) eventJson.get("Id");
click = (String) eventJson.get("click");
time = (String) eventJson.get("time");
uuid = UUID.randomUUID().toString();
type = "post";
//Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
dBUrl, username,
password);
stmt = con.createStatement();
stmt.execute("INSERT INTO " + tableName
+ "(id,data,type,txnid,groupname,time)values('" + uuid
+ "','" + address + "'," + "'" + type + "','"
+ Id + "','" + click + "','" + time
+ "')");
logger.info("inserted successfully in mysql");
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e1) {
logger.info("" + e1);
e1.printStackTrace();
}
}
}
}
Upvotes: 0
Views: 1132
Reputation: 62350
If you want to do JUnit testing, one approach would be to use Mockito library:
For example:
@Test
public void testExecute() {
Tuple t = mock(Tuple.class);
when(t.getFields()).thenReturn(new Fields("myAttribute"));
when(t.getValueByField("myAttribute").thenReturn("my json string to be tested");
MyBolt b = new MyBolt();
b.execute(t, mock(BasicOutputCollector.class));
// put your assertions here
}
For this to work, you should change your code in execute()
a little bit. From
int size = input.getFields().size();
Fields fields = input.getFields();
to
Fields fields = input.getFields();
int size = fields.size();
Otherwise, input.getFields()
is called twice but the test only specified a single return value for this method, and thus, the second call will return null
. (As an alternative, you can also mock both calls to getFields()
.)
If you don't want to mock everything you can also instantiate TupleImpl
objects (Tuple t = new TupleImpl(...)
) and pass them to execute()
in your test.
Upvotes: 3