Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a void method

I am trying to reach more code coverage. I have an "informational" method that just triggers notification, and response is not required. How do I unit test it?

public error(message?: any, ...optionalParams: any[]) {
    if (this.isErrorEnabled()) {
      console.error(`${this.name}: ${message}`, ...optionalParams);
    }
  }
like image 909
Bahodir Avatar asked Nov 15 '16 13:11

Bahodir


People also ask

How do you test a void method in unit testing?

Using the verify() method. Whenever we mock a void method we do not expect a return value that is why we can only verify whether that method is being called or not. Features of verify(): Mockito provides us with a verify() method which lets us verify whether the mock void method is being called or not.

How do you unit test methods?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.


1 Answers

You can test its side effects using spies, for example:

describe('error method', => {
    it('should log an error on the console', () => {
        spyOn(console, 'error');

        error(...);

        expect(console.error).toHaveBeenCalledWith(...);
    });

    ...
});
like image 69
jonrsharpe Avatar answered Nov 05 '22 22:11

jonrsharpe