How can I expect and test the same method in JMockit

Having the following class:

class ToTest{ @Autowired private Service service; public String make(){ //do some calcs obj.setParam(param); String inverted = service.execute(obj); return "<" + inverted.toString() + ">"; } } 

I would like to add a test that claims that service.execute is called with an object with parameter X.

I would do it with verification. I want to mock this call and make it return something verifiable. I do it with anticipation.

 @Tested ToTest toTest; @Injected Service service; new NonStrictExpectations(){ { service.exceute((CertainObject)any) result = "b"; } }; toTest.make(); new Verifications(){ { CertainObject obj; service.exceute(obj = withCapture()) assertEquals("a",obj.getParam()); } }; 

I get a null pointer to obj.getParam (). Verification does not seem to work. If I delete the expected action, but then I get a null pointer in the inverted .toString ().

How do you guys do this job?

+4
source share
1 answer

The following class of tests works fine for me using JMockit 1.4:

 public class TempTest { static class CertainObject { private String param; String getParam() { return param; } void setParam(String p) { param = p; } } public interface Service { String execute(CertainObject o); } public static class ToTest { private Service service; public String make() { CertainObject obj = new CertainObject(); obj.setParam("a"); String inverted = service.execute(obj); return "<" + inverted + ">"; } } @Tested ToTest toTest; @Injectable Service service; @Test public void temp() { new NonStrictExpectations() {{ service.execute((CertainObject) any); result = "b"; }}; toTest.make(); new Verifications() {{ CertainObject obj; service.execute(obj = withCapture()); assertEquals("a", obj.getParam()); }}; } } 

Can you show a complete example of a test that fails?

+1
source

Source: https://habr.com/ru/post/1502769/


All Articles