As I know, in JUnit I can set #PublicForTests annotation for logic tests.
I tried to find alternative in MSTest with no success.
What I'v found is people who said that I don't need to test private methods.
What is my alternative to check my logic of private methods?
From our comments, there are 2 main approaches that you can take to test private methods:
The first is to indirectly test your private method via the public method that uses it.
The second is to directly test your private method via Reflection.
Related
I'm trying to verify some methods are called for a newly created instance.
I followed Spock guide of mock constructor but it says too few invocations.
Too few invocations for:
3 * mockStep.addTarget(_) (0 invocations)
Unmatched invocations (ordered by similarity):
None
Pasting my code here...
public class Workflow {
public void createStep() {
Step step = new Step();
step.addTarget("A");
step.addTarget("B");
step.addTarget("C");
}
}
class WorkflowTest extends Specification {
Workflow workflow
def setup() {
workflow = new Workflow()
}
def "each new step should have 3 targets" () {
given:
def mockStep = Mock(Step)
GroovySpy(Step, global: true)
new Step() >> mockStep
when:
workflow.createStep()
then:
3 * mockStep.addTarget(_)
}
}
In the above code I'm trying to let all new Step() returns the mocked Step and to verify the mockStep.addTarget() is called 3 times. When I ran in debug mode, it seems Step step = new Step(); still returns a new instance instead of the mocked Step.
Don't use dirty tricks like global Groovy mocks but refactor for decoupling, dependency injection and the resulting better testability instead. Please read the "general comments" and "some more remarks" sections of my answer here for a reason why you should refactor. I do not want to repeat everything here.
As for the technical reason why your global Groovy mock does not work from Java code, I am quoting the Spock manaual:
When should Groovy mocks be favored over regular mocks?
Groovy mocks should be used when the code under specification is
written in Groovy and some of the unique Groovy mock features are
needed. When called from Java code, Groovy mocks will behave like
regular mocks. Note that it isn’t necessary to use a Groovy mock
merely because the code under specification and/or mocked type is
written in Groovy. Unless you have a concrete reason to use a Groovy
mock, prefer a regular mock.
Update:
The quickest way to refactor is to separate creating the step from adding targets. Actually the name createStep implies the method does just that. But instead it also adds targets. Use two methods for that and a method doing the workflow. Then you can use a Spy for stubbing createStep (which returns the created Step instance) and then check interactions if you really think that should be tested at all. Checking internal interactions is often a code smell (over-specification).
Alternatively, add a factory class for steps and inject an instance into the workflow class. Then you can easily mock the factory class and make it return a mock step.
If you don't understand what I mean by the two alternatives, please let me know.
This is a beta feature and no grantee it will work as expected and it will be depending on the version you are using .
Please refer to official documentation
Im trying to get familiar with using MOQ and mocking in general. So I want to test an api controller which uses an assembly which serves as a repository for getting/updating data etc.
eg a structure like this.
HomeController
Index
Repository.GetSomeData (returns JSON object)
This repository class has an interface, and that is what is injected via the .net core startup class. The method in this case, GetSomeData does a number of steps via calls to the Db, as well as reading a file from the file system, parsing it and moving it off to another folder.
Question: How can a "mocked" Repository work without doing the things that the "real" object does? All the examples I see are simple addition, returning strings etc.
When you mock something like your repository, you going to stub out methods on the repository to return some canned result. Calls to those methods on the repository mock, then, bypass the real methods and instead just do what you've stubbed.
Essentially, you need to first identity what methods will be utilized. Then, you should determined appropriate responses those methods should return based on the particular scenario you're attempting to unit test. Then, you create the mock and add stubs for those methods with those responses.
The whole point of mocking is to remove variables, so you're intentionally trying to get to the "happy path": the set of internal responses that put the action in the state you need it to be in for specific test you're conducting.
I wish to know how can I mock kotlin final class with PowerMock so I can test it. I followed guide for testing Java final classes but I still got this error
Cannot subclass final class
Is there any way to do that?
With Mockito 2.1.0+ you can mock final classess as well. This feature is optional, so you have to enable it by adding Mockito extension.
To do this:
Create a file named org.mockito.plugins.MockMaker and place it under the resources/mockito-extensions directory in your test folder.
The file contains a single line: mock-maker-inline
You can find more information in Mockito documentation.
Just create interfaces for your classes. Than you can simply mock your classes using interface.
I would like to use the features of both Arquillian and PowerMock in the same JUnit 4 test.
The problem is that both products are JUnit Runners which should be used with #RunWith, and this is not possible to use multiple #RunWith on the same test class, or to put multiple Runners class in the same #RunWith annotation.
Do you know any way to do that ?
You can use PowerMock without using the runner if you use the PowerMockRule (which is a TestRule). From the PowerMockRule:
Since version 1.4 it's possible to bootstrap PowerMock using a JUnit
Rule instead of using the PowerMockRunner and the RunWith annotation.
This allows you to use other JUnit runners while still benefiting from
PowerMock's functionality. You do this by specifying:
#RunWith(Arquillian.class);
public class MyTest {
#Rule
PowerMockRule rule = new PowerMockRule();
// Tests goes here
...
}
See also the answers to Junit Parameterized tests together with Powermock - how? and the following thread in the PowerMock google group: Using PowerMock without the RunWith?.
No, you either need to:
use one and create a test base class that does the things you wanted the other runner to do.
separate your test into multiple tests, each using different runners.
JUnit4 only supports one #RunWith annotation, and JUnit4's #RunWith annotation doesn’t accept multiple runners.
Reference: project13
How/would you test super-simple methods that are built on a persistence engine. I'm going to use JPA but any persistence mechanism I'm sure has its equivelents.
For example...
#Entity
public class Category {
#Id #GeneratedValue
private long id;
#NotNull #NotEmpty
private String name;
#NotNull
#ManyToOne
private User user;
//...Getters/Setters...
}
#Stateless
public void CategoryServiceImpl implements CategoryService {
#PersistenceContext EntityManager entityManager;
public void addCategory(Category input) {
entityManager.persist(input);
}
}
What kind of tests would be useful for addCategory. I can see the usefulness of TDD and unit testing but I'm just not sure what kinds of tests to do for simple methods like that. Not really looking for "how" to create the tests but "what" to test.
One philosophy is to be very hard-nosed about unit testing (before I explain what I mean, let me say that I rarely follow this philosophy myself). You are testing that this unit does what it is supposed to do, not that any depedent software (such the the persistence mechanism) works.
So this method of your receives a parameter "input" and passes it to entityManager.persist. That's it's job. So we use a mocking framework of some sort to get a mock entityManager, and we verify that indeed the parameter passed to the call of addCategory is received my the entityManager. That's it. We've tested all the responsibilities of the method.
In more complex scenarios this appraoch is pretty useful, you test all the conditionals in the method and pick up all sorts of "off-by-one" and misuse of null reference errors etc.
For something like this example I'm not convinced that we are going to find the interesting bugs.
So I'd be setting up little suites of tests using a real EntityManager, which push the boundaries of the data. And yes, this isn't truly "Unit" testing, but I don't care - I want to find defects!
For example:
Create a category object with an empty name
Call Add Category
What should happen? I assume that we intend that an exception be thrown? So we test that indeed that's what happens.
Some more tests:
Insert, then retrieve - verify all fields
Insert, then insert a duplicate, what error do we expect
and so on.
Instead of integration testing against an existing database you can perform decent unit tests by running your tests against an embedded in memory database like h2 which has been configured to create all its tables based on the annotations on connection. This works well for us for a database of about two hundred tables.