0

I have a problem with Mockito. I have two different class. My purpose is test “setChanges” function. this is my first class :

class M {
private String a;
private String b;
private boolean c = false;

public String getA() {
    return a;
} 
public void setA( String _a ) {
     a = _a;
} 
public String getC() {
    return c;
} 
public void setC( final boolean imp ) {
     c = imp;
} 

}

this is the main class which has “setChanges” function:

class MyMainClass {
private String getMyA() {
    return "Data";
}

private static void setChanges(final M m) {
    if (getMyA().equals(m.getA())){
        m.setC(true);
    }
}

}

How can I test "setChanges"? Which means that if getA() returns "Data", How can I check getC() that should be "true"?

M.Mori
  • 1
  • 2
  • Is there a way of setting `a` in class `M`, such as a constructor or a setter method? If so, you don't need Mockito for this. – Dawood ibn Kareem Feb 04 '19 at 17:35
  • Yes, there is a setter Method for a .it set by the user. – M.Mori Feb 04 '19 at 17:56
  • Then use it. Make an `M` with `a` set to `"Data"` and another `M` with `a` set to `"Something else"`. Call `setChanges` twice, and assert that the output in each case is the right thing. No mocking required. – Dawood ibn Kareem Feb 04 '19 at 17:58
  • Also, your `MyMainClass` doesn't actually compile - you've got a static method calling a non-static one without specifying what instance to call it on. You'll find your code easier to test once you can get it to compile. – Dawood ibn Kareem Feb 04 '19 at 18:07

2 Answers2

0

Thanks, It works with this code :

@Test

public void testsetChanges(){

MyMainClass  mmc  = new MyMainClass ();
M m = new M();
m.setA("Data");

Method method = MyMainClass.class.getDeclaredMethod(
            "setChanges",
            M.class
    );
    method.setAccessible(true);
    method.invoke(method, m );

assertTrue(m.getC());

}

M.Mori
  • 1
  • 2
-1

Pass in an instance of M which satisfies (or doesn't satisfy) getMyA and validate that M#getC returns true (or false, depending on what you're testing). No mocks required.

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • I think it doesn't work because the "setChanges" is static void function. – M.Mori Feb 04 '19 at 17:53
  • It'll work just fine because you would only be able to test the instance of `M` passed to your method *anyway*. – Makoto Feb 04 '19 at 17:54
  • @Test public void testsetChanges(){ MyMainClass mmc = new MyMainClass (); M m = new M(); m.setA("Data"); mmc.setChanges(m); assertTrue(m.getC()); } – M.Mori Feb 04 '19 at 18:02