1

How can we unit test private class ?

For example with an example of private class @Autowired with qualifier I would like to verify if the good qualifier is call

public class MyClass {
    @Autowired
    IHelloService helloService;

    public void sayHello(List<Person> list) {
        for(Person person : list) {
            helloService.sayHello(person);
        }
    }
}

.

@Primary
@Component
public class SayHelloService implements ISayHello {

    @Autowired
    @Qualifier("french")
    ISayHello french;
    @Autowired
    @Qualifier("english")
    ISayHello english;

    @Override
    public void sayHello(Person person) {
        switch (person.getLanguage) {
            case "EN":
                english.sayHello(Person person);
            break;
            case "FR":
                french.sayHello(Person person);
            break;
            default:
            break;
        }
    }
}

.

@Qualifier("french")
Component
class SayHelloFrenchService implements ISayHello {
    public void sayHello(Person person) {
        sysout("Bonjour " + person.getName());
    }
}

@Qualifier("english")
Component
class SayHelloFrenchService implements ISayHello {
    public void sayHello(Person person) {
        sysout("Hello " + person.getName());
    }
}

Edit: I failed my example: the twice qualifier class were private

Alexandre
  • 145
  • 2
  • 11
  • 1
    There are no private classes in your examples. Use constructor injection rather than field injection. – Michael Mar 06 '19 at 13:48
  • @Michael why do you suggest using constructor injection? – joninx Mar 06 '19 at 13:50
  • by private class, do you mean: instance variables? actually, you don't, otherwise they're less and less unit tests. you mock them – Stultuske Mar 06 '19 at 13:50
  • @russellhoff Because you can make the fields private and final without sacrificing your ability to test the class. – Michael Mar 06 '19 at 13:51
  • @russellhoff one reason to take it seriously, is because the Spring team advocates constructor injection. It makes testing a lot easier. – Stultuske Mar 06 '19 at 13:51
  • Thanks all of you. Found that [answer](https://stackoverflow.com/a/40620318/828551). – joninx Mar 06 '19 at 13:52
  • Sorry i failed my example, twice of my qualifier class are private. Like they are private and can be show only in the package, i can't use constructor injection because i can't find the class – Alexandre Mar 06 '19 at 14:08

1 Answers1

0

If i @Mock the interface it works.

I thought i must @Mock the implementation...

But i can't write tests of implementation of private class.

Alexandre
  • 145
  • 2
  • 11