Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I expect and verify 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'd like to add a test that asserts me that service.execute is called with an object with the param X.

I'd do that with a verification. I want to mock this call and make it return something testable. I do that with an expectations.

@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 on obj.getParam(). Apparently the verification does not work. If I remove the expectation it works but then I get a null pointer in inverted.toString().

How would you guys make this work?

like image 790
Jordi P.S. Avatar asked Nov 12 '22 21:11

Jordi P.S.


1 Answers

The following test class is working 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 test which fails?

like image 185
Rogério Avatar answered Nov 15 '22 00:11

Rogério