How to mock protected global variables boolean in java junit test [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 16 days ago.
This post was edited and submitted for review 15 days ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
How to mock protected global variables boolean in Java JUnit test?
public abstract class Base {
protected boolean varBoolean;
...
}
public class NameClass extends Base {
private List <String> arrayStr;
public void init() {
if (varBoolean) {
...
}
...
}
}
#RunWith(JUnit4.class)
#Slf4j
public class NameClassTest {
public void testInnit() {
}
...
}
How to mock protected varBoolean be equal true in Java unit test?
And mock private string list arrayStr

I can fix it.
#RunWith(JUnit4.class)
#Slf4j
public class NameClassTest {
#InjectMocks
NameClass nameClass;
#Test
public void testInit() throws Exception {
nameClass.varBoolean = true;
nameClass.init();
...
}
}
nameClass.varBoolean = true;

Add a test only constructor to NameClass with a varBoolean parameter. Call it in your test with whatever argument you want.

Related

Design Pattern for multiple similar APIs in one application [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 days ago.
Improve this question
Let's say I'm working with multiple different music stream APIs. User passes me the link from one of the supported streaming services. Similar API responses should be mapped on the same application's object for further processing, but every API has unique algorithm of doing that. What's the correct way of doing that?
I came up with next solution. I'm creating an interface MusicApi, which contains methods getAppObject and isLinkMatches
public interface MusicApi {
public static AppObject getAppObject(String link);
public static boolean isLinkMatches(String link);
}
For example we're working with these APIs. Let's say they're implementing method correctly.
public class NapsterApi implements MusicApi {}
public class SpotifyApi implements MusicApi {}
public class YoutubeApi implements MusicApi {} // As example of completely different audio extraction algorithm
Now I have to choose when to use which API. I've decided to create MusicApiSelector class
(Kept implementation listing simple without using Java Reflection API or Spring #Component)
public class MusicApiSelector {
private static final MusicApi[] registeredApis = new MusicApi[]{NapsterApi, SpotifyApi, YoutubeApi};
public static MusicApi getApi(String link) {
for (MusicApi api : registeredApis) {
if (api.isLinkMatches()) {
return api;
}
}
throw new Exception("This link is not supported")
}
}
Using this should look something like this
public class Main {
public static void main(String[] args) {
String link = https://www.youtube.com/watch?v=djV11Xbc914;
MusicApi api = MusicApiSelector.getApi(link);
AppObject appObject = api.getAppObject(link);
}
}
Can you tell me if that's valid approach how this pattern is called (i guess it's Strategy Pattern). And what I can do better (maybe some completely different patterns)

how to make dependency injection in spring java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
Improve this question
i have code bellow, i code without dependency injection,
i still dont get point what is advantage using dependency injection
interface class
#Component
public interface TextWriter {
public String WriteText(String s);
}
class one
public class YonoWriter implements TextWriter{
#Override
public String WriteText(String s) {
return s + " 1 ";
}
}
class two
public class Yono2Writer {
TextWriter text;
Yono2Writer(){
text = new YonoWriter();
}
public String hello(String s){
return this.text.WriteText(" 2 ") + s;
}
}
final class
#RestController
public class Yono3Writer {
Yono2Writer text;
Yono3Writer(){
text = new Yono2Writer();
}
#GetMapping("/")
public String hello2(){
return this.text.hello("3");
}
}
and the result is 2 1 3 and what is expected is 123 and how to implement dependency injection there ?
If you want to learn what more about dependency injection (DI) check spring docs
The summary of DI or IoC (inversion of control) is that the component defines the dependency and then the spring context injects a proper instance of the dependency, hence inversion of control. So instead of:
#RestController
public class Yono3Writer {
Yono2Writer text; // <- 1. component defines the dependency
Yono3Writer(){
text = new Yono2Writer(); // <- 2. component creates the dependency by itself as part of constructing the component
}
#GetMapping("/")
public String hello2(){
return this.text.hello("3");
}
}
You get this:
#RestController
public class Yono3Writer {
Yono2Writer text; // <- 1. component defines the dependency
Yono3Writer(Yono2Writer yono2Writer){
this.text = yono2Writer; // <- 2. a spring managed bean is injected using the constructor as part of constructing the component
}
#GetMapping("/")
public String hello2(){
return this.text.hello("3");
}
}
provided that you configured a bean of type Yono2Writer, one way to do that:
#Configuration
public class MyConfig {
#Bean
public Yono2Writer yono2Writer() {
return new Yono2Writer();
}
}
This is really helpful when you have a bunch of these dependencies for your component that are not all straight forward to implement unlike new Yono2Writer()

Real Time Scenarios to use singleton class in android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I know about singleton class. but i want to know Real Time Scenarios to use singleton class in android . Can anyone give me examples in android to use and with benefits of that scenario..
Two real good scenarios
Extend your application class and use it's instance to get access to the app context within any class
SQL Database is a good idea to be a singleton class
Here is an example of App usage
import android.app.Application;
public class MyApplication extends Application {
private static MyApplication instance = null;
public static MyApplication getInstance() {
return instance;
}
#Override
public void onCreate() {
if (instance == null) {
instance = this;
}
}
}
Access String in R
public class DummyClass {
private void getAppString(){
String r = MyApplication.getInstance().getString(R.string.app_name);
}
}

Best practice: family of classes with various type of configuration class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am defining a family of classes used to get data from different sources (from example, a class will get data from a database, another one from a file, etc.)
Since the data sources are so different, there is no common interface for their configurations.
They all share a common method getData() though.
The idea was to define a set of predefined configurations (most of the time, the configurations used will just depend on a locale, thus there would one configuration for usa, one for france, etc.).
I have create the interface:
public interface IDataSource {
public void initialize(Object config);
public List<String> getData();
}
And the class DataSourceA:
public class DataSourceA implements IDataSource {
public void initialize(Object config) {
DataSourceAConfig configA = (DataSourceAConfig) config;
initializeA(configA);
}
public List<String> getData() {
...
}
private void initializeA(DataSourceAConfig config) {
...
}
}
and DataSourceB:
public class DataSourceB implements IDataSource {
public void initialize(Object config) {
DataSourceBConfig configB = (DataSourceBConfig) config;
initializeB(configB);
}
public List<String> getData() {
...
}
private void initializeA(DataSourceBConfig config) {
...
}
}
I am not happy with that solution (for example, using initialize(Object config), then cast the config). I am looking for advice on how to rethink the problem.
Edit:
I generated the configuration implementations using jaxb. Then the user would have to pass the type of data source and the name of the configuration file to the data source factory to get the data source.
Make an interface(abstract class) like DataSourceConfig. DataSourceAConfig and DataSourceBConfig will implement(extend) it. In your initialize method, you can replace Object with DataSourceConfig.
If your datasources are so different, you should change the IDataSource too:
public interface IDataSource<T extends DataSourceConfig> {
public void initialize(T config);
public List<String> getData();
}
DataSourceConfig will be the common interface and DataSourceB will implement IDataSource like this:
public class DataSourceB implements IDataSource<DataSourceBConfig> {
public void initialize(DataSourceBConfig config) {
initializeB(config);
}
// everything else omitted for simplicity
}

How do I create a JUnit Test for CompareTo? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new at programming and I made a compareTo method and I want to create a test to see if it works but I don't know how to.
All in all, you need a basic understanding of JUnit.
Below is is a simple JUnit Test, but please see this blog post for a detailed explanation. Good luck!
#BeforeClass
public static void setUpBeforeClass() throws Exception {
// Run once before any method in this class.
}
#Before
public void setUp() throws Exception {
// Runs once before each method annotated with #Test
}
#Test
public void testSomething() {
// The Sample Test case
fail("Not yet implemented");
}
#Test
public void testAnotherThing() {
// Another Sample Test case
Me me = new Me();
assertEquals("cmd", me.getFirstName());
}
#After
public void tearDown() throws Exception {
// Runs once after each method annotated with #Test.
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
// Run once after all test cases are run
}
}
first create a junit test class (it should be in the option when you right click, it's not "Class")
by default you get a method,
public void test(){
fail("blah blah");
}
test is a method name and it does not matter what it is so feel free to change it as you wish.
fail is a method from org.junit package and you don't want fail there because it will automatically fail whatever you want to test so delete it for now
now I am assuming compareTo method returns negative number or zero or positive number.
so you might want to test whether it returns a value or not first.
(http://junit.sourceforge.net/javadoc/org/junit/Assert.html lists the methods you can use for testing.)
from the list, I see that assertNotNull checks for the return value by your method. if the method correctly works, it will return a value (test succeeds) but if it doesn't, it will throw exception (test fails).
#Test
public void test() {
org.junit.Assert.assertNotNull(yourpackage.yourclass.yourmethod(if static));
}
or
import yourpackage.yourclassname;
#Test
public void test() {
yourclassname test = new yourclassname();
org.junit.Assert.assertNotNull(test.compareTo());
}
but if you have the class with the junit test class in same package, you do not need to do any import.
hope it helps

Categories

Resources