First of all i'm learning java and mockito, did search and cannot find proper answer yet.
The pseudo code is like this
public enum ProdEnum {
PROD1(1, "prod1"),
PROD2(2, "prod2"),
......
PROD99(2, "prod2");
private final int id;
private final String name;
private ProdEnum(int id, String name) {
this.id = id;
this.name = name;
}
prublic String getName() { return this.name; }
}
public class enum1 {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
System.out.println("Hello, World");
List<String> prodNames = Array.stream(ProdEnum.values())
.map(prodEnum::getName)
.collect(Collectors.toList());
// verify(prodNames);
}
}
My question is in unit test, how to generate mocked prodNames ?
Only 2 or 3 of the products needed for testing,
In my unit test i tried this
List<ProdEnum> newProds = Arrays.asList(ProdEnum.PROD1, ProdEnum.PROD2);
when(ProdEnum.values()).thenReturn(newProds);
but it says Cannot resolve method 'thenReturn(java.util.List<...ProdEnum>)'
Thanks !
You cannot mock statics in vanilla Mockito.
If your up for a little refactor then:
1) Move enum.values() call into a package level method:
..
List<String> prodNames = Array.stream(getProdNames())
.map(prodEnum::getName)
.collect(Collectors.toList());
..
List<String> getProdNames(){
return ProdEnum.values();
}
2) Spy on your SUT:
enum1 enumOneSpy = Mockito.spy(new enum1());
3) Mock the getProdNames() method:
doReturn(newProds).when(enumOneSpy).getProdNames();
Related
I am trying to migrate from JUnit4 to JUnit5 and also I'm new to ParametrizedTest in Junit5 and I have a scenario wherein I would like to provide different DisplayName and the Test argument(Object).
Here's the data source I would like to use as an input for #MethodSource("data")
public static Collection<Object[]> data() throws IOException {
List<Object[]> testCaseData = new ArrayList<>();
TestCaseReader testCaseReader = new TestCaseReader(TESTCASE_CSV_RESOURCE);
List<MyClass> testCaseList = testCaseReader.readTestCases();
for (MyClass testCase : testCaseList) {
if (testCase.isActive()) {
Object[] testParameter = new Object[2];
testParameter[0] = String.format("%03d: %s", testCase.getStartingLineNumber(), testCase.getName());
testParameter[1] = testCase;
testCaseData.add(testParameter);
}
}
return testCaseData;
}
And this is the Test
#ParameterizedTest(name = "Scenario: {0}, testCase={1}")
#MethodSource("data")
public void process(MyClass testCase) {
//...
//some operating on testCase methods/variables
}
When executing TestCase, I see the DisplayName is picked up correctly, but the other arguments is not resolvable it says
org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [com.sample.MyClass testCase] in method [public void.MultipleTestCase.process(com.sample.MyClass testCase)]
Could you please guide me what I have done wrong here!
Thanks
Providing test data as Collection<Object[]> is no longer the appropriate way in JUnit 5. You can use a Stream instead. If you need to provide multiple parameters for your test you can use Arguments to wrap them. They are automatically unwrapped upon test execution. The example below gives a general idea on how to do that. You can replace TestCase with MyClass and insert your TestCaseReader code in data.
public class ParameterizedTest {
static Stream<Arguments> data() {
// TODO: Add your TestCaseReader usage to create MyClass / TestCase instances.
List<TestCase> testCases =
List.of(new TestCase("test01", "data01"), new TestCase("test02", "data02"));
return testCases.stream().map(test -> Arguments.arguments(test.getName(), test));
}
#org.junit.jupiter.params.ParameterizedTest(name = "Scenario: {0}, testCase={1}")
#MethodSource("data")
public void process(String name, TestCase testCase) {
System.out.println(name + ": " + testCase.getData());
// TODO: Work with your test case.
}
private static final class TestCase {
private final String name;
private final String data;
public TestCase(String name, String data) {
this.name = name;
this.data = data;
}
public String getName() {
return name;
}
public String getData() {
return data;
}
}
}
I have a below piece of code :
Test class is a POJO of (id and name)
Test test=new Test();
Test test1=new Test();
Test test2=new Test();
for(Asset a : assets)
{
assetId=getAssetId();
test.set(assetId);
test1.set(assetId);
test2.set(assetId);
for(some loop)
{
test.set(assetName);
test1.set(assetName1);
test2.set(assetName2);
setMethod(test);
setMethod1(test1);
setMethod2(test2);
}
}
as we can see there's too much repetitive code. can anyone please help to optimise it?
You can refactor your code introducing new methods helping readability and manuteneability of the code.
First define a method to generate a List of Test
private List<Test> createTests(int size) {
List<Test> tests = new ArrayList();
for (int i = 0; i < size; i++) {
tests.add(new Test());
}
return tests;
}
Add a method to set the assetId on each test of a list.
private void setAssetId(List<Test> tests, String assetId) {
for (Test test: tests) {
test.set(assetId);
}
}
Than you can refactoring the first part of code as
List<Test> tests = createTests(3);
for (Asset asset: assets) {
setAssetId(tests, asset.getAssetId());
...
}
The inner loop is not clear (it is more a pseudo code, then java code), but the idea is the same.
If you see some duplication in your code extract a method and refactor the original code calling that method. The whole code will be a lot more readable and if repetitions are many can be also smaller.
With Lambda you can save more code.
Replace the syso with your stuff to do.
package main.java.stackoverflow.oopTest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class Test {
private int id;
private String name;
public Test(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Test(int id) {
this(id, "");
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public static void main(String[] args) {
List<Test> listOfTest = new ArrayList<>();
// create your POJOS
IntStream.range(0, 3).forEach(index -> {
listOfTest.add(new Test(index));
});
//iterate over your POJOS
listOfTest.forEach(t -> System.out.println(t.id));
}
}
We use the builder pattern extensively in our code base, with built objects all having a toBuilder() method. I want to write a unit test that ensures that no fields have been forgotten in the toBuilder() methods, i.e., for any buildable object, I want to a test roughly like this
MyClass obj = getTestObjectWithRandomData();
assertEquals(obj, obj.toBuilder().build());
Now, I can fairly easy write a basic version of getTestObjectWithRandomData() that uses reflection to assign a bunch of values to the fields of any object. However, the snag is that build() often contains tons of validation checks that will throw exceptions if, for example, a certain integer isn't within a sane range. Writing a generalized version of getTestObjectWithRandomData() that conforms all those class-specific validation checks would be impossible.
So, how can I do what I want to do? I'm tempted to segregate the construction and validation code into different methods so that the test doesn't trip on the validation, but then that means that people have to remember to call validate() or whatever on objects after they create them. Not good.
Any other ideas?
How about using Lombok? Would that be an option for you? It will auto-generate the builder code and you'll never again have to worry about it.
https://projectlombok.org/features/Builder
Simply annotate your classes with #Builder
With Lombok
import lombok.Builder;
import lombok.Singular;
import java.util.Set;
#Builder
public class BuilderExample {
private String name;
private int age;
#Singular private Set<String> occupations;
}
Vanilla Java
import java.util.Set;
public class BuilderExample {
private String name;
private int age;
private Set<String> occupations;
BuilderExample(String name, int age, Set<String> occupations) {
this.name = name;
this.age = age;
this.occupations = occupations;
}
public static BuilderExampleBuilder builder() {
return new BuilderExampleBuilder();
}
public static class BuilderExampleBuilder {
private String name;
private int age;
private java.util.ArrayList<String> occupations;
BuilderExampleBuilder() {
}
public BuilderExampleBuilder name(String name) {
this.name = name;
return this;
}
public BuilderExampleBuilder age(int age) {
this.age = age;
return this;
}
public BuilderExampleBuilder occupation(String occupation) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}
this.occupations.add(occupation);
return this;
}
public BuilderExampleBuilder occupations(Collection<? extends String> occupations) {
if (this.occupations == null) {
this.occupations = new java.util.ArrayList<String>();
}
this.occupations.addAll(occupations);
return this;
}
public BuilderExampleBuilder clearOccupations() {
if (this.occupations != null) {
this.occupations.clear();
}
return this;
}
public BuilderExample build() {
// complicated switch statement to produce a compact properly sized immutable set omitted.
// go to https://projectlombok.org/features/Singular-snippet.html to see it.
Set<String> occupations = ...;
return new BuilderExample(name, age, occupations);
}
#java.lang.Override
public String toString() {
return "BuilderExample.BuilderExampleBuilder(name = " + this.name + ", age = " + this.age + ", occupations = " + this.occupations + ")";
}
}
}
Given the following classes:
class Logger {
public void log(String someInfo,
String someOtherInfo,
VssNotificationStatus status,
Supplier<String> message)
{}
}
class Asset {
private String name;
private String alias;
Asset(String name, String alias) {
this.name = name;
this.alias = alias;
}
public String getName() {
return name;
}
public String getAlias() {
return alias;
}
}
class ClassUnderTest {
private Logger logger;
ClassUnderTest(Logger logger) {
this.logger = logger;
}
public void methodUnderTest(Asset asset) {
logger.log(asset.getName(), asset.getAlias(), VssNotificationStatus.ASSET_PREPARED, () -> String.format("%s is running", "methodUnderTest"));
}
}
And the following test code:
#RunWith(MockitoJUnitRunner.class)
public class TestA {
private ClassUnderTest clazz;
#Mock
private Logger logger;
#Before
public void setup() {
clazz = new ClassUnderTest(logger);
}
#Test
public void test() {
// given
String info1 = "info1";
String info2 = "info2";
Asset asset = mock(Asset.class);
given(asset.getName()).willReturn(info1);
given(asset.getAlias()).willReturn(info2);
// when
clazz.methodUnderTest(asset);
// then
verify(logger).log(eq(asset.getName()), eq(asset.getAlias()), eq(VssNotificationStatus.ASSET_PREPARED), any());
}
}
fails at the verify line with
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded
I tried to use isA(Supplier.class), specify Supplier.class in the any method, but still same error. It feels like Mockito is not mocking properly this method.
Those failing tests were passing properly before refactoring the last parameter from simple String parameter to a Supplier<String>.
I'm using mockito-core 2.13.0
It looks like Matchers doesn't like when you pass in a mocked method instead of using the value you used when mocking this method directly. The following verify works perfectly fine.
verify(logger).log(eq(info1), eq(info2), eq(VssNotificationStatus.ASSET_PREPARED), any());
So matchers should use real values and not getting them from a mocked object.
I wish to achieve the following behavior.
My class under test has a dependency on some other class, I wish to mock this dependency with jMock. Most of the methods would return some standard values, but there is one method, where I wish to make a call to a stubbed implementation, I know I can call this method from the will(...) but I want the method to be called by the exact same parameters that were passed to the mocked method.
Test
#Test
public void MyTest(){
Mockery context = new Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
IDependency mockObject = context.mock(IDependency.class);
Expectations exp = new Expectations() {
{
allowing(mockObject).methodToInvoke(????);
will(stubMethodToBeInvokedInstead(????));
}
};
}
Interface
public interface IDependency {
public int methodToInvoke(int arg);
}
Method to be called instead
public int stubMethodToBeInvokedInstead(int arg){
return arg;
}
So how do I capture the parameter that were passed to the method being mocked, so I could pass them to the stubbed method instead?
EDIT
Just to give another example, let's say I wish to mock the INameSource dependency in the following (C#) code, to test the class Speaker
public class Speaker
{
private readonly string firstName;
private readonly string surname;
private INameSource nameSource ;
public Speaker(string firstName, string surname, INameSource nameSource)
{
this.firstName = firstName;
this.surname = surname;
this.nameSource = nameSource;
}
public string Introduce()
{
string name = nameSource.CreateName(firstName, surname);
return string.Format("Hi, my name is {0}", name);
}
}
public interface INameSource
{
string CreateName(string firstName, string surname);
}
This is how it can be done in Rhino Mocks for C# I understand it can't be as easy as this since delegates are missing in Java
The solution from Duncan works well, but there is even a simpler solution without resort to a custom matcher. Just use the Invocation argument that is passed to the CustomActions invoke method. At this argument you can call the getParameter(long i) method that gives you the value from the call.
So instead of this
return matcher.getLastValue();
use this
return (Integer) invocation.getParameter(0);
Now you don't need the StoringMatcher anymore: Duncans example looks now like this
#RunWith(JMock.class)
public class Example {
private Mockery context = new JUnit4Mockery();
#Test
public void Test() {
final IDependency mockObject = context.mock(IDependency.class);
context.checking(new Expectations() {
{
// No custom matcher required here
allowing(mockObject).methodToInvoke(with(any(Integer.class)));
// The action will return the first argument of the method invocation.
will(new CustomAction("returns first arg") {
#Override
public Object invoke(Invocation invocation) throws Throwable {
return (Integer) invocation.getParameter(0);
}
});
}
});
Integer test1 = 1;
Integer test2 = 1;
// Confirm the object passed to the mocked method is returned
Assert.assertEquals((Object) test1, mockObject.methodToInvoke(test1));
Assert.assertEquals((Object) test2, mockObject.methodToInvoke(test2));
}
public interface IDependency {
public int methodToInvoke(int arg);
}
Like Augusto, I'm not convinced this is a good idea in general. However, I couldn't resist having a little play. I created a custom matcher and a custom action which store and return the argument supplied.
Note: this is far from production-ready code; I just had some fun. Here's a self-contained unit test which proves the solution:
#RunWith(JMock.class)
public class Example {
private Mockery context = new JUnit4Mockery();
#Test
public void Test() {
final StoringMatcher matcher = new StoringMatcher();
final IDependency mockObject = context.mock(IDependency.class);
context.checking(new Expectations() {
{
// The matcher will accept any Integer and store it
allowing(mockObject).methodToInvoke(with(matcher));
// The action will pop the last object used and return it.
will(new CustomAction("returns previous arg") {
#Override
public Object invoke(Invocation invocation) throws Throwable {
return matcher.getLastValue();
}
});
}
});
Integer test1 = 1;
Integer test2 = 1;
// Confirm the object passed to the mocked method is returned
Assert.assertEquals((Object) test1, mockObject.methodToInvoke(test1));
Assert.assertEquals((Object) test2, mockObject.methodToInvoke(test2));
}
public interface IDependency {
public int methodToInvoke(int arg);
}
private static class StoringMatcher extends BaseMatcher<Integer> {
private final List<Integer> objects = new ArrayList<Integer>();
#Override
public boolean matches(Object item) {
if (item instanceof Integer) {
objects.add((Integer) item);
return true;
}
return false;
}
#Override
public void describeTo(Description description) {
description.appendText("any integer");
}
public Integer getLastValue() {
return objects.remove(0);
}
}
}
A Better Plan
Now that you've provided a concrete example, I can show you how to test this in Java without resorting to my JMock hackery above.
Firstly, some Java versions of what you posted:
public class Speaker {
private final String firstName;
private final String surname;
private final NameSource nameSource;
public Speaker(String firstName, String surname, NameSource nameSource) {
this.firstName = firstName;
this.surname = surname;
this.nameSource = nameSource;
}
public String introduce() {
String name = nameSource.createName(firstName, surname);
return String.format("Hi, my name is %s", name);
}
}
public interface NameSource {
String createName(String firstName, String surname);
}
public class Formal implements NameSource {
#Override
public String createName(String firstName, String surname) {
return String.format("%s %s", firstName, surname);
}
}
Then, a test which exercises all the useful features of the classes, without resorting to what you were originally asking for.
#RunWith(JMock.class)
public class ExampleTest {
private Mockery context = new JUnit4Mockery();
#Test
public void testFormalName() {
// I would separately test implementations of NameSource
Assert.assertEquals("Joe Bloggs", new Formal().createName("Joe", "Bloggs"));
}
#Test
public void testSpeaker() {
// I would then test only the important features of Speaker, namely
// that it passes the right values to the NameSource and uses the
// response correctly
final NameSource nameSource = context.mock(NameSource.class);
final String firstName = "Foo";
final String lastName = "Bar";
final String response = "Blah";
context.checking(new Expectations() {
{
// We expect one invocation with the correct params
oneOf(nameSource).createName(firstName, lastName);
// We don't care what it returns, we just need to know it
will(returnValue(response));
}
});
Assert.assertEquals(String.format("Hi, my name is %s", response),
new Speaker(firstName, lastName, nameSource).introduce());
}
}
JMock doesn't support your use case (or any other mocking framework I know of in java).
There's a little voice in my head that says that what you're trying to do is not ideal and that your unit test might be to complicated (maybe it's testing too much code/logic?). One of the problems I see, is that you don't know which values those mocks need to return and you're plugging something else, which might make each run irreproducible.