简体   繁体   中英

Best practices using Mockito

I have a question about what are the best practices of using a Mock instantiation on different test classes.

Lets assume that I have a Mock of a class named PropertiesLoader

 @Mock
 private PropertiesLoader propertiesLoader;

And I want to call a function from this class named getkey() on two different Test classes. (TestCrypter) and (TestUserService)

Should I implement the following method on both classes?

public class TestCrypter{

@Mock
private PropertiesLoader propertiesLoader

@Test
public void firstTest(){
  Mockito.when(propertiesLoader.getKey()).thenReturn("123");
 }
}


public class TestUserService{

@Mock
private PropertiesLoader propertiesLoader

@Test
public void firstTest(){
  Mockito.when(propertiesLoader.getKey()).thenReturn("123");
 }
}

Or is there a cleaner and better way to do that?

Thanks in advance!

For me the duplicated code is fine if we are talking about tests.

The main goal is to keep test class expressive and easy to read, so sometimes it is better to keep some redundant code in test classes, without making some fancy abstract and utils.

In your case, "when" is defining some test specific behaviour, so it should be stored in the same place (because tests results may depend on this), because outside test will be hard to read and maintain.

However, if the usage of PropertiesLoader will be something really common, consider creating an abstract class (or something) which will cover these invocations, however make it parametrized (to keep tests logic separated).

Consider using an @Before method to setup mocking that applies to multiple (and/or all) tests. In your example, I would consider using the following:

@Before
public void preTestSetup()
{
    // init the mocks.
    // Not required if you are using the MockitoJunitRunner.
    MockitoAnnotations.initMocks(this);

    // I prefer doReturn.when over when.thenReturn.
    Mockito.doReturn("123").when(propertiesLoader).getKey();

    // if you'd like, use this instead of the doReturn above:
    Mockito.when(propertiesLoader.getKey()).thenReturn("123");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM