-1

I have the following function:

public static String s(B b) {
        int t = b.t();
        String r ="Hello ";
        for(String z:s) {
            boolean x=b.f(t,5);
            if(x) {
                r+=z;
            }
        }
        return r;
    }

Which takes in B - Interface

The Interface B - Methods int t() and boolean f(int a, int b) were implemented in the same class within main as the following:

public static void main(String[] args) {
        A.s(new B() {                            //A - Class
            @Override                            //B - Interface
            public int t() {
                return 15;
            }
            @Override
            public boolean f(int a, int b) {
                return true;
            }
        });
    }

Issue: How can i test the public static String s(B b) - function from a jUnit - test when the function asks for a interface as a parameter, when the interface methods were implemented in main?

The Class is called A, Interface: B

Michael
  • 41,989
  • 11
  • 82
  • 128
  • Normal thing would be to create a stub or mock class that implements the interface. What has `main` got to do with this, how is it relevant to the testing? The method `s` doesn't compile and doesn't make much sense so it will be hard to give any specific advice for that method if that is what you're after. – Joakim Danielson Mar 21 '20 at 13:23
  • Thank you for your Answer! The point was when testing let's say i make a instance of the class `A example = new A();` when testing the function: `example.s(B b)` - it asks for the B b - Parameter which is a interface. Now if i implemented those methods within the main of the `A - Class`, how do i pass it to the function so that `.s` is executed? Or what other approach is better suited for such a test? Thank you in advance! –  Mar 21 '20 at 13:28
  • 1
    I would implement a stub class that implements `B` inside my test class and then pass an instance of it to `s` in the test. – Joakim Danielson Mar 21 '20 at 13:38

1 Answers1

1

When you want to test your s() method you can provide any reference to an object which implements the B interface. You can define an anonymous class which implements the interface as you did in your main() method. Or you can define a "normal" class which implements the interface as well. So you can write something like this:

public class Whatever implements B
{
    /* your methods from B */
}

Then you use this class like any other class inside your unit test:

@Test
public void checkSomething() {
    String result = A.s(new Whatever());
    Assertions.assertEquals("my string", result);
}
Progman
  • 16,827
  • 6
  • 33
  • 48